◐APLab.academy
CoursesToolsPremium
··
Sign In
APLAB.ACADEMY © 2026 · BUILT BY AP LAB
COURSESTOOLSPRIVACYTERMS
CLASSICAL MACHINE LEARNING: SUPERVISED LEARNING FOUNDATIONS / L04 — LOGISTIC REGRESSION AND CLASSIFICATION04 / 15 · █████░░░░░░░░░░░░░░░ 27%
LESSONS · 15
01Mathematical Foundations of Machine Learning02The Supervised Learning Framework03Linear Regression: From Theory to Practice04Logistic Regression and Classification05Regularization: L1, L2, and Elastic Net06Decision Trees: Intuition and Implementation07Random Forests and Bagging08Gradient Boosting: From AdaBoost to XGBoost09Support Vector Machines: Linear Case10Kernel Methods and Non-linear SVMs11Evaluation Metrics: Beyond Accuracy12Cross-Validation and Model Selection13The Art of Feature Engineering14Feature Selection and Dimensionality Reduction15End-to-End ML Project: From Data to Deployment
ON THIS PAGE
Introduction: From Continuous to CategoricalLearning Objectives1. From Regression to ClassificationThe Classification Problem2. The Sigmoid Function: From Scores to ProbabilitiesWhy Not Linear Regression?The Sigmoid (Logistic) FunctionThe Logistic Regression Model
LESSONS · 15 · 04 / 15▾
01Mathematical Foundations of Machine Learning02The Supervised Learning Framework03Linear Regression: From Theory to Practice04Logistic Regression and Classification05Regularization: L1, L2, and Elastic Net06Decision Trees: Intuition and Implementation07Random Forests and Bagging08Gradient Boosting: From AdaBoost to XGBoost09Support Vector Machines: Linear Case10Kernel Methods and Non-linear SVMs11Evaluation Metrics: Beyond Accuracy12Cross-Validation and Model Selection13The Art of Feature Engineering14Feature Selection and Dimensionality Reduction15End-to-End ML Project: From Data to Deployment
LESSON 04 · INTERMEDIATE · 60 MIN · ◆ 4 INSTRUMENTS

Logistic Regression and Classification

Extend to classification: sigmoid function, maximum likelihood for classification, decision boundaries, and multi-class strategies.

Introduction: From Continuous to Categorical

Imagine you're building an email spam filter. Unlike predicting house prices (a number), you need to predict a category: spam or not spam. You can't use linear regression here – it predicts continuous values like 127.3, but you need a probability between 0 and 1.

Logistic regression solves this by applying a special function (the sigmoid) that "squashes" any real number into the range [0, 1], converting it to a probability.

Key Insight: Despite its name, logistic regression is a classification algorithm! It's called "regression" for historical reasons, but it outputs probabilities that we convert to class predictions.

FIG. 02Decision Boundary Visualizer
INTERACTIVE
LOADING INSTRUMENT
Fig. 022D visualization of classification decision boundaries

Try it: drag the weight/threshold sliders and add or move data points, then watch the colored decision boundary and the probability shading shift in response. Notice how the boundary stays a straight line no matter how you tune it — that's the defining limitation of logistic regression we'll unpack below.

Learning Objectives

  • Understand binary and multi-class classification
  • Derive the logistic regression model from first principles
  • Master the sigmoid function and decision boundaries
  • Implement binary cross-entropy loss
  • Train logistic regression with gradient descent
  • Visualize decision boundaries interactively
  • Extend to multi-class classification

1. From Regression to Classification

The Classification Problem

In classification, we predict discrete categories (classes):

TypeClassesExamples
Binary2 classesSpam/Not Spam, Disease/Healthy, Cat/Dog
Multi-class(k > 2) classesDigit Recognition (0-9), Image Classification (cat/dog/bird)
Multi-labelMultiple per sampleMovie genres, Medical diagnoses

This lesson focuses on binary classification (2 classes: 0 and 1).

FIG. 04Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive Python code execution environment

2. The Sigmoid Function: From Scores to Probabilities

Why Not Linear Regression?

If we try linear regression for classification: [ \hat{y} = \mathbf{w}^T \mathbf{x} ]

Problems:

  • ❌ Output can be any value (e.g., -10, 5, 127)
  • ❌ We need probabilities in [0, 1]
  • ❌ Hard to interpret (\hat{y} = 2.7) as a class

The Sigmoid (Logistic) Function

[ \sigma(z) = \frac{1}{1 + e^{-z}} ]

Properties:

  • Maps any real number to [0, 1]
  • (\sigma(0) = 0.5) (decision boundary)
  • (\sigma(z) \to 1) as (z \to +\infty)
  • (\sigma(z) \to 0) as (z \to -\infty)
  • Smooth and differentiable everywhere
FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

The Logistic Regression Model

[ \hat{y} = P(y=1 | \mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x}) = \frac{1}{1 + e^{-\mathbf{w}^T \mathbf{x}}} ]

Interpretation:

  • (\hat{y}) = probability that sample belongs to class 1
  • (1 - \hat{y}) = probability of class 0
  • Decision rule: predict class 1 if (\hat{y} > 0.5), else class 0

3. Decision Boundaries

Visualizing Classification

The decision boundary is where the model is uncertain: (P(y=1) = 0.5)

For logistic regression: (\mathbf{w}^T \mathbf{x} = 0)

SEE

🧪 Push the idea further: TensorFlow Playground starts exactly where logistic regression ends — a single sigmoid neuron on 2-D data. Click "Run" on the linear dataset, then switch to the circle dataset to watch it fail. In the next lesson on decision trees (and later with kernels), you'll fix that failure two very different ways.

(Use the Decision Boundary Visualizer at the top of this lesson to experiment with the boundary as you read this section.)

Linear Decision Boundaries

Logistic regression creates linear decision boundaries in feature space: the set of points where (\mathbf{w}^T \mathbf{x} = 0) is always a straight line (a hyperplane in higher dimensions). The shaded confidence regions on either side correspond to (P(y=1) > 0.5) and (P(y=1) < 0.5).

You can see this directly in the Decision Boundary Visualizer at the top of the lesson, and the full from-scratch training + plotting code appears in Section 5 below.


4. Binary Cross-Entropy Loss

Why Not MSE?

MSE is non-convex for logistic regression – multiple local minima make optimization hard.

Instead, we use Binary Cross-Entropy (Log Loss):

[ J(\mathbf{w}) = -\frac{1}{n} \sum_{i=1}^{n} \left[ y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i) \right] ]

Where (\hat{y}_i = \sigma(\mathbf{w}^T \mathbf{x}_i))

Intuition:

  • If (y_i = 1): loss = (-\log(\hat{y}_i)) → high loss if (\hat{y}_i) is small
  • If (y_i = 0): loss = (-\log(1-\hat{y}_i)) → high loss if (\hat{y}_i) is large
FIG. 08Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive Python code execution environment

Gradient for Logistic Regression

The gradient of cross-entropy with respect to weights is:

[ \nabla_{\mathbf{w}} J = \frac{1}{n} \mathbf{X}^T (\hat{\mathbf{y}} - \mathbf{y}) ]

Amazing fact: Same form as linear regression! Just replace predictions with sigmoid outputs.


5. Training Logistic Regression

Interactive Model Training

FIG. 10ML Model Trainer
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Train machine learning models interactively

When Linear Isn't Enough — Step Through Backprop

Logistic regression is a 1-layer network. Add one hidden layer and you can solve problems no straight line can — like XOR. Open the Gradient Lab and try the XOR preset: click Train and watch the decision boundary curl into the right shape, then switch to CIRCLES and MOONS.

Press Step instead of Train to advance one SGD step at a time. A small arrow appears on a sampled point showing −∂L/∂x — the direction the gradient is pushing the input space, which is the same direction the weights are learning to not go.

FIG. 12Gradient Lab
INTERACTIVE
LOADING INSTRUMENT
Fig. 122D classification with a hand-rolled MLP. Step through SGD, watch the decision boundary form.

The forward/backward equations on display under SHOW MATH are exactly what you'd implement in NumPy. Cross-entropy with a softmax over two classes reduces to the same (ŷ − y) gradient you derived earlier — the network just chains it through the hidden layer.

Implementation from Scratch

FIG. 14Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive Python code execution environment

6. Multi-Class Classification

One-vs-Rest (OvR)

For (k) classes, train (k) binary classifiers:

  • Classifier 1: Class 1 vs. {2, 3, ..., k}
  • Classifier 2: Class 2 vs. {1, 3, ..., k}
  • ...

Prediction: Choose class with highest probability.

Softmax Regression (Multinomial Logistic)

Direct extension to multi-class:

[ P(y = k | \mathbf{x}) = \frac{e^{\mathbf{w}k^T \mathbf{x}}}{\sum{j=1}^{K} e^{\mathbf{w}_j^T \mathbf{x}}} ]

This is the softmax function – generalizes sigmoid to (k) classes.

FIG. 16Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive Python code execution environment

Key Takeaways

✓ Logistic Regression: Classification algorithm using sigmoid function

✓ Sigmoid Function: (\sigma(z) = \frac{1}{1+e^{-z}}) maps real numbers to [0, 1]

✓ Model: (P(y=1|\mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x}))

✓ Loss: Binary cross-entropy (convex, probabilistically motivated)

✓ Training: Gradient descent with same update rule as linear regression

✓ Decision Boundary: Linear in feature space (where (\mathbf{w}^T \mathbf{x} = 0))

✓ Multi-Class: One-vs-Rest or Softmax regression


Practice Problems

Problem 1: Implement Sigmoid

FIG. 18Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Interactive Python code execution environment

Problem 2: Compute Cross-Entropy Loss

FIG. 20Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive Python code execution environment

Problem 3: Decision Boundary Interpretation

Given (\mathbf{w} = [2, -1, 3]) (including bias), what is the decision boundary equation?

FIG. 22Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive Python code execution environment

Next Steps

You've mastered binary classification with logistic regression! Next:

  • Lesson 5: Regularization – preventing overfitting with L1/L2 penalties
  • Lesson 6: Decision Trees – non-linear decision boundaries

Logistic regression is used everywhere: web click prediction, medical diagnosis, credit scoring, and more!


Further Reading

Interactive Visualizations

  • MLU-Explain: Logistic Regression — scroll-story with an in-browser model that retrains as you drag points across the boundary.
  • MLU-Explain: Double Descent — a classification-first tour of modern generalization theory; builds directly on this lesson's decision-boundary picture.
  • TensorFlow Playground — the quintessential decision-boundary sandbox. Set activation to "Sigmoid" + 0 hidden layers for pure logistic regression, then add features to see why we'll need non-linear models next.
  • Seeing Theory — Frequentist Inference — background on likelihood, the engine behind cross-entropy.

Video Tutorials

  • StatQuest — Logistic Regression: Main Ideas and the maximum-likelihood follow-up (Josh Starmer) — the clearest audio-visual explanation of the sigmoid and its loss.
  • Google ML Crash Course — Logistic Regression — short interactive exercises on sigmoids, log-loss, and thresholding.

Papers & Articles

  • A Comparison of Numerical Optimizers for Logistic Regression — Tom Minka. Why L-BFGS and Newton methods converge faster than vanilla gradient descent for logistic loss.
  • The Softmax Layer in Large Language Models — a modern reminder that multi-class logistic regression is still the output layer of every transformer.

Documentation & Books

  • Book: An Introduction to Statistical Learning (2e) — James, Witten, Hastie, Tibshirani, Chapter 4 (free PDF).
  • ML Cheatsheet — Cross-Entropy Derivation — step-by-step derivation.
  • scikit-learn: Logistic Regression — implementation reference with solver comparison.

Remember: Logistic regression is a linear model that learns linear decision boundaries. For non-linear problems, we'll need more powerful models (coming soon)!

CONNECTED CONCEPTS
logistic-regressionclassificationsigmoiddecision-boundary
← PREVIOUS
03. Linear Regression: From Theory to Practice
NEXT →
05. Regularization: L1, L2, and Elastic Net
INSTRUMENTS ON PAGE · 04
FIG. 02 · INTERACTIVE
Decision Boundary Visualizer
FIG. 04 · INTERACTIVE
Python Code Executor
FIG. 10 · INTERACTIVE
ML Model Trainer
∂
FIG. 12 · INTERACTIVE
Gradient Lab
YOUR NOTES