Lesson 3.3foundation3 h⚡ live demo

Logistic regression and softmax classification

Turning a linear score into a probability — and why that is a neuron

Logistic regression is the simplest classifier worth understanding deeply, and it is secretly a one-layer neural network with a sigmoid or softmax output. Its loss — cross-entropy derived from a Bernoulli likelihood — is the loss of every classifier and every language model in this path (4.3 Loss functions catalog, 7.6 Decoder-only: GPT and autoregressive generation), and its gradient p^−y\hat{\mathbf{p}} - \mathbf{y} is the gradient that flows out of every softmax layer (4.4 Backpropagation, fully derived).

You'll be able to

  • Explain why a sigmoid of a linear score is the right model for a binary probability, via log-odds
  • Derive binary cross-entropy as the negative log-likelihood of a Bernoulli model
  • Derive the gradient Xᵀ(p̂ − y)/n and explain why there is no closed form but the problem is convex
  • Generalize to softmax regression for K classes and state its gradient
  • Choose decision thresholds under class imbalance and judge whether predicted probabilities are calibrated
  • Recognize logistic regression as nn.Linear + sigmoid and implement it in NumPy and PyTorch

Key ideas

  1. Logistic regression models the log-odds as a linear function: log(p/(1−p)) = wᵀx + b, so the decision boundary p = 0.5 is a hyperplane.
  2. Binary cross-entropy is the negative log-likelihood of a Bernoulli model; wrong-and-confident predictions are punished without bound.
  3. The gradient at the logit is p − y, so ∇J = Xᵀ(p̂ − y)/n — the same 'features × errors' form as linear regression.
Show 5 more key ideas
  1. No closed form, but the loss is convex (Hessian XᵀSX ⪰ 0), so gradient descent or Newton/IRLS finds the global optimum; separable data need L2 regularization.
  2. Softmax regression generalizes to K classes with p_c = e^{z_c}/Σ e^{z_k}, loss −log p_y and gradient p − y_onehot; it is shift-invariant.
  3. A threshold is a decision, not part of the model; move it with costs and class imbalance, and check calibration with reliability diagrams.
  4. Logistic/softmax regression is nn.Linear plus sigmoid/softmax — a one-layer neural network; every classifier head and LM output layer is one.
  5. Compute the loss from logits (log(1 + e^{−z})) rather than from probabilities to avoid log(0).

Suggested path through this lesson