Overview
Logistic regression answers a yes or no question. Softmax regression extends it to a choice among several classes. Each class has its own weight vector, and the model computes one score per class for an input. The softmax function then turns those scores into probabilities: it makes them all positive and divides by their total, so the highest score gets the largest share. Training raises the score of the correct class and lowers the others, by an amount that depends on how wrong the current probabilities are.
A short history
Softmax regression is the extension of logistic regression to several classes, known in statistics as multinomial logistic regression. It was developed through the 1960s and 1970s, and Daniel McFadden's work on the multinomial logit model of choice contributed to his 2000 Nobel prize in economics. John Bridle introduced the name softmax around 1990 when describing it as the output layer of a neural network, which is where most students now meet it.
How it works
- Find the distinct labels, store them in classes_, and replace each label by its index from 0 to .
- Start with all weights and biases at zero, so every class begins with probability .
- Compute the scores , one per class, for every row.
- Apply the softmax to get probabilities, and measure the mean cross-entropy plus the l2 term.
- Compute the gradient, which is the features times the gap between predicted probabilities and the one-hot labels, and take a full-batch step of size .
- After the configured number of epochs, predict the class with the highest score.
Watch out for
- The classes must be mutually exclusive, because the probabilities are forced to sum to 1. For labels that can occur together, use one sigmoid per label instead.
- Boundaries between classes are straight planes, so classes that wrap around each other are not separated without extra features.
- On separable data the weights grow without limit and the probabilities become overconfident. Set l2 above zero to keep them in check.
- Computing directly overflows for large scores. The template subtracts the row maximum first, and your own code should do the same.
Use cases
When to use it
Classification with more than two mutually exclusive classes when a linear boundary is a fair first guess, and as the baseline before a neural network. It is also the final layer of almost every neural classifier.
In industry
- Document handling
- Sorting incoming emails, tickets or forms into one of several departments from word features.
- Transport and economics
- Discrete choice models: estimating which travel mode or product a person will choose from several options.
- Deep learning
- The final layer of almost every neural classifier, which turns the network's scores into class probabilities.
Choosing it: what must hold
- Three or more classes, with exactly one correct class per example.
- Classes that can be separated by linear boundaries in the features supplied.
- A reasonable number of examples for every class.
When to choose something else
| If | Use instead |
|---|---|
| There are only two classes | Logistic regression (the binary classifier lesson) |
| An example can belong to several classes at once | One sigmoid output per class, trained with binary cross-entropy |
| The class boundaries are not linear | A random forest, gradient boosted trees or an MLP with a softmax output |
Math foundations
Class scores
One score per class, each a weighted sum of the features. Column of holds the weights of class .
The softmax
Turns scores into probabilities. Only the differences between scores matter: adding the same constant to all of them changes nothing.
The cross-entropy loss
The mean negative log of the probability given to the true class. It is zero only if every true class gets probability 1. Biases are not penalised.
Gradient with respect to the scores
Predicted probability minus the target, which is 1 for the true class and 0 for the rest. The true class is pushed up and every other class is pushed down in proportion to its probability.
Gradient with respect to the weights
The score gradient carried back to the weights by the features. is the matrix of one-hot labels.
The update
Full-batch gradient descent. The loss is convex, so with a suitable step it approaches the single best value.
Symbols
- input row with d features
- number of classes
- weight matrix (d by C) and one bias per class
- score of class k, also called a logit
- predicted probability of class k
- index of the true class of row i
- matrices of predicted probabilities and one-hot labels, n by C
- 1 when the condition holds, otherwise 0
- L2 strength
- step size, the lr parameter
Worked by hand
Three classes with scores for one row. The true class is the first. Use and .
The gradient entries sum to zero. A descent step raises the first score and lowers the other two, the second more than the third because it holds more of the wrong probability.
Visual example
Loading the example.
Try this
- Three classes, three scores per point: the highest wins.
- Add points of the third class in a corner and watch its region grow.
Code sample
import numpy as np
from impl import MulticlassClassifier
from config import MulticlassClassifierConfig
rng = np.random.default_rng(0)
centers = np.array([[0.0, 3.0], [-3.0, -2.0], [3.0, -2.0]])
y = rng.integers(0, 3, size=300)
X = centers[y] + rng.normal(size=(300, 2))
labels = np.array(["red", "green", "blue"])[y]
model = MulticlassClassifier(MulticlassClassifierConfig(epochs=300)).fit(X, labels)
print(model.predict(X[:5])) # class names
print(model.predict_proba(X[:1]).round(3)) # one row of probabilities, columns follow model.classes_
print((model.predict(X) == labels).mean()) # training accuracy, close to 1.0Read the implementation (92 lines)
"""Multiclass classifier: softmax (multinomial logistic) regression trained by gradient descent.
NumPy only. Scores are Z = X W + b with W of shape (d, C). Probabilities are softmax(Z) along the class axis.
The objective is the mean cross-entropy plus 0.5 * l2 * ||W||^2.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MulticlassClassifierConfig
except ImportError: # run from the template's own folder
from config import MulticlassClassifierConfig
def softmax(z: np.ndarray) -> np.ndarray:
"""Softmax along the last axis, shifted by the row maximum so large scores do not overflow."""
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def log_softmax(z: np.ndarray) -> np.ndarray:
"""log(softmax(z)) along the last axis, computed without taking the log of a tiny number."""
z = z - z.max(axis=-1, keepdims=True)
return z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
class MulticlassClassifier:
"""Softmax regression. After `fit`: `classes_` (C,), `params["W"]` (d, C), `params["b"]` (C,)."""
def __init__(self, config: MulticlassClassifierConfig | None = None) -> None:
self.config = config or MulticlassClassifierConfig()
self.classes_: np.ndarray | None = None
self.params: dict[str, np.ndarray] = {}
self.loss_history_: list[float] = []
def initialize(self, n_features: int, n_classes: int) -> None:
"""Set zero weights for `n_features` inputs and `n_classes` classes."""
self.params = {"W": np.zeros((n_features, n_classes)), "b": np.zeros(n_classes)}
def loss_and_grads(self, X: np.ndarray, y_index: np.ndarray) -> tuple[float, dict]:
"""Objective and its gradients.
X: (n, d). y_index: class indices in 0..C-1, shape (n,). Returns (loss, {"W": (d, C), "b": (C,)}).
"""
W, b = self.params["W"], self.params["b"]
n = len(X)
Z = X @ W + b
loss = -log_softmax(Z)[np.arange(n), y_index].mean() + 0.5 * self.config.l2 * np.sum(W**2)
# d loss / d Z = (softmax(Z) - one_hot(y)) / n
dZ = softmax(Z)
dZ[np.arange(n), y_index] -= 1.0
dZ /= n
grad_b = dZ.sum(axis=0) if self.config.fit_intercept else np.zeros_like(b)
return float(loss), {"W": X.T @ dZ + self.config.l2 * W, "b": grad_b}
def fit(self, X: np.ndarray, y: np.ndarray) -> "MulticlassClassifier":
"""Fit the model. X: features, shape (n, d). y: labels of any hashable type, shape (n,)."""
X = np.asarray(X, dtype=float)
y = np.asarray(y)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n entries")
self.classes_, y_index = np.unique(y, return_inverse=True)
if len(self.classes_) < 2:
raise ValueError("y must hold at least two classes")
self.initialize(X.shape[1], len(self.classes_))
self.loss_history_ = []
for _ in range(self.config.epochs):
loss, grads = self.loss_and_grads(X, y_index)
self.loss_history_.append(loss)
for key in self.params:
self.params[key] -= self.config.lr * grads[key]
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
"""Class scores before softmax. X: (n, d). Returns shape (n, C)."""
if not self.params:
raise RuntimeError("call fit before predicting")
return np.asarray(X, dtype=float) @ self.params["W"] + self.params["b"]
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Class probabilities. X: (n, d). Returns shape (n, C); columns follow `classes_`, rows sum to 1."""
return softmax(self.decision_function(X))
def predict(self, X: np.ndarray) -> np.ndarray:
"""Most probable label for each row. X: (n, d). Returns shape (n,), values from `classes_`."""
return self.classes_[self.decision_function(X).argmax(axis=1)]
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""Accuracy: the share of rows whose predicted label equals y."""
return float((self.predict(X) == np.asarray(y)).mean())- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Generate three clouds of points in two dimensions with different centres. Fit MulticlassClassifier with the default MulticlassClassifierConfig and read score on held-out points. Then call predict_proba on a point midway between two centres and on a point far outside all three, and compare how confident the model is in each case.
Check on learning
- Adding the same number to every class score leaves the probabilities unchanged. What does that say about the weights, and why does the l2 penalty help?
A way to think about it
If you add one vector to every column of the predictions stay the same, so many weight matrices give one model. Ask which of them the penalty prefers.
- For two classes, show that softmax regression gives the same model as logistic regression. Which quantity plays the role of the single weight vector?
A way to think about it
Write and divide top and bottom by . Look at what remains in the exponent.
- A point far from all training data receives probability 0.99 for one class. Should you trust it? Why does a linear softmax model behave this way?
A way to think about it
Scores grow linearly with distance from the boundary, so the gap between scores keeps widening. Confidence here reflects distance from a boundary, not closeness to the data.
- Why does the template compute the loss with log_softmax rather than taking the log of softmax?
A way to think about it
Consider a score gap of 800. The probability rounds to exactly zero and its log is minus infinity, while the direct formula stays finite.