Sign in

Multiclass classifier

Multiclass classifier (softmax regression)

Softmax regression: a linear classifier for three or more classes that gives each class a score and turns the scores into probabilities that sum to 1.

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

  1. Find the distinct labels, store them in classes_, and replace each label by its index from 0 to C−1C - 1.
  2. Start with all weights and biases at zero, so every class begins with probability 1/C1/C.
  3. Compute the scores z=xW+b\mathbf{z} = \mathbf{x} W + \mathbf{b}, one per class, for every row.
  4. Apply the softmax to get probabilities, and measure the mean cross-entropy plus the l2 term.
  5. 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 η\eta.
  6. 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 eze^{z} 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

IfUse instead
There are only two classesLogistic regression (the binary classifier lesson)
An example can belong to several classes at onceOne sigmoid output per class, trained with binary cross-entropy
The class boundaries are not linearA random forest, gradient boosted trees or an MLP with a softmax output

Math foundations

  1. Class scores

    z=xW+b,W∈Rd×C\mathbf{z} = \mathbf{x} W + \mathbf{b}, \qquad W \in \mathbb{R}^{d \times C}

    One score per class, each a weighted sum of the features. Column kk of WW holds the weights of class kk.

  2. The softmax

    pk=ezk∑j=1Cezjp_k = \frac{e^{z_k}}{\sum_{j=1}^{C} e^{z_j}}

    Turns scores into probabilities. Only the differences between scores matter: adding the same constant to all of them changes nothing.

  3. The cross-entropy loss

    L(W,b)=−1n∑i=1nlog⁡pi,yi+λ2∥W∥2L(W, \mathbf{b}) = -\frac{1}{n}\sum_{i=1}^{n} \log p_{i, y_i} + \frac{\lambda}{2}\lVert W \rVert^2

    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.

  4. Gradient with respect to the scores

    ∂L∂zik=1n(pik−1[yi=k])\frac{\partial L}{\partial z_{ik}} = \frac{1}{n}\left(p_{ik} - \mathbb{1}[y_i = k]\right)

    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.

  5. Gradient with respect to the weights

    ∇WL=1nX⊤(P−Y)+λW,∇bL=1n∑i(pi−yi)\nabla_W L = \frac{1}{n} X^\top (P - Y) + \lambda W, \qquad \nabla_{\mathbf{b}} L = \frac{1}{n}\sum_{i}(\mathbf{p}_i - \mathbf{y}_i)

    The score gradient carried back to the weights by the features. YY is the matrix of one-hot labels.

  6. The update

    W←W−η ∇WL,b←b−η ∇bLW \leftarrow W - \eta \, \nabla_W L, \qquad \mathbf{b} \leftarrow \mathbf{b} - \eta \, \nabla_{\mathbf{b}} L

    Full-batch gradient descent. The loss is convex, so with a suitable step it approaches the single best value.

Symbols

x\mathbf{x}
input row with d features
CC
number of classes
W,bW, \mathbf{b}
weight matrix (d by C) and one bias per class
zkz_k
score of class k, also called a logit
pkp_k
predicted probability of class k
yiy_i
index of the true class of row i
P,YP, Y
matrices of predicted probabilities and one-hot labels, n by C
1[⋅]\mathbb{1}[\cdot]
1 when the condition holds, otherwise 0
λ\lambda
L2 strength
η\eta
step size, the lr parameter

Worked by hand

Three classes with scores z=(2,1,0)\mathbf{z} = (2, 1, 0) for one row. The true class is the first. Use e2=7.389e^{2} = 7.389 and e1=2.718e^{1} = 2.718.

∑jezj=7.389+2.718+1=11.107\sum_j e^{z_j} = 7.389 + 2.718 + 1 = 11.107
p=(7.38911.107,  2.71811.107,  111.107)=(0.6652,  0.2447,  0.0900)\mathbf{p} = \left(\tfrac{7.389}{11.107},\; \tfrac{2.718}{11.107},\; \tfrac{1}{11.107}\right) = (0.6652,\; 0.2447,\; 0.0900)
L=−ln⁡0.6652=0.4076L = -\ln 0.6652 = 0.4076
∂L∂z=(0.6652−1,  0.2447,  0.0900)=(−0.3348,  0.2447,  0.0900)\frac{\partial L}{\partial \mathbf{z}} = (0.6652 - 1,\; 0.2447,\; 0.0900) = (-0.3348,\; 0.2447,\; 0.0900)

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.0
Read 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

  1. 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 WW the predictions stay the same, so many weight matrices give one model. Ask which of them the penalty prefers.

  2. 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 p1=ez1/(ez1+ez2)p_1 = e^{z_1} / (e^{z_1} + e^{z_2}) and divide top and bottom by ez1e^{z_1}. Look at what remains in the exponent.

  3. 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.

  4. 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.