math.vinhnx.ca / machine learning / logistic regression
Machine learning

Logistic regression

A straight line, a squashing function and a loss that punishes confident mistakes. Watch gradient descent fit it live, add and drag points while it trains, and see what happens when the classes can be separated perfectly.

Probability of class B

click: add · shift-click: other class · drag · alt-click: delete

Every point through the sigmoid

score z = w·φ(x)

Training

The model

Give each point a score that is linear in its features, $z = \mathbf w^\top \boldsymbol\phi(\mathbf x)$, and turn the score into a probability with the logistic (sigmoid) function:

$$P(y = 1 \mid \mathbf x) = \sigma(z) = \frac{1}{1 + e^{-z}}.$$

Equivalently, the log-odds $\log\frac{p}{1-p}$ are exactly $z$. That is why the weights read as “each unit of this feature multiplies the odds by $e^{w_k}$”. The decision boundary $p = 0.5$ is where $z = 0$, a straight line when $\boldsymbol\phi(\mathbf x) = (1, x, y)$.

The loss, and its very clean gradient

Fitting by maximum likelihood means minimising the log-loss (cross-entropy):

$$L(\mathbf w) = -\frac1n \sum_i \Big[y_i \log p_i + (1 - y_i)\log(1 - p_i)\Big] + \frac{\lambda}{2}\|\mathbf w\|^2.$$

Because $\sigma'(z) = \sigma(z)(1 - \sigma(z))$, nearly everything cancels and the gradient is just “prediction minus truth, times the features”:

$$\nabla L = \frac1n \sum_i (p_i - y_i)\,\boldsymbol\phi(\mathbf x_i) + \lambda \mathbf w.$$

$L$ is convex, so gradient descent cannot get stuck in a bad local minimum. What you are watching is a slide to the unique optimum, if one exists.

Surprise: perfect data breaks it

If a line separates the classes perfectly, there is no optimum. Scaling $\mathbf w$ up makes every probability more confident and every term of the loss smaller, forever. So with $\lambda = 0$ the weight norm grows without bound (roughly like $\log t$) and the probability map sharpens into a step. Statisticians call this complete separation; in R it shows up as the warning “fitted probabilities numerically 0 or 1 occurred”. Any $\lambda > 0$ fixes it by making large weights cost something.

Try it: . Watch ‖w‖ climb on the training plot, then raise λ.

Lines can’t do XOR, until you change the features

On XOR data no straight line does better than a coin flip. Logistic regression is linear in its features, though, not in $x$ and $y$. Add $x^2$, $xy$ and $y^2$, and the boundary becomes a conic that can carve up the plane. This is the same trick kernels play in the SVM, done by hand.

Try it: , then switch to quadratic.