Logistic regression, visually

Draw a line on the log-odds scale, squash it into a probability, and train it by walking downhill.

Estimating class probabilities (a classifier) with a regression model

Problem (direct approach): if we estimate P̂(Y = 1 | x) = w · x, the estimates aren't bounded. If some sample x′ gets an 80% chance of class 1, P̂(Y = 1 | x′) = w · x′ = 0.8, then doubling it gives a 160% chance: P̂(Y = 1 | 2x′) = w · 2x′ = 1.6. The linearity is the problem!

Approach: instead of using regression to estimate the probability directly, use it to estimate the log odds z = ln P(Y = 1 | x)P(Y = 0 | x), which can be any number. With one feature, that gives the model

z = w0 + w1x ⇒ p̂ = P̂(Y = 1 | x) = σ(z) = 11 + e−z

Predict 1 when p̂ > 0.5, which is when z > 0. The decision boundary is the x where the line crosses 0: x = −w0 / w1.

A sample's loss is −ln of the probability the model gave its true class; the loss of w is the mean over the samples (the cross-entropy, in nats).

Training: walk downhill on the loss

Goal: choose w0 and w1 with the smallest mean cross-entropy loss. Unlike MSE, there is no formula for the best w.

Approach: the same as for MSE. Start anywhere, step against the gradient, and repeat.

loss(w) = −1n ∑i [ yi ln p̂i + (1 − yi) ln(1 − p̂i) ]
∇loss(w) = 1n ∑i (p̂i − yi) 1xi w ← w − η ∇loss(w)

This has the same form as the MSE gradient −2n∑ ri1xi, with the error now p̂i − yi: the red segment from each sample to the sigmoid. The loss is in nats (ln). In bits (log2, as on the problem sets) every loss and gradient is 1/ln 2 ≈ 1.44 times larger: the same surface, and the same walk with η times ln 2.

Try this

Data (xi, yi)

Log odds

In either panel, drag a square handle to tilt the line, or empty space to shift it. The probability panel plots against z (the sigmoid itself) or x. Drag a sample sideways; click it to flip its class.

Probability

class 0 class 1 ring: predicted model best fit true error p̂ − y

Loss surface

class 0 class 1 ring: predicted current best fit error p̂ − y

Loss by step