Module 6 · Intermediate · Logistic regression

Softmax regression for more than two classes

Softmax regression with Python: scores to probabilities, cross-entropy loss, the gradient, a NumPy build on penguins checked with scikit-learn, and its limits.

By theprogrammers team · · 18 min read

An expense-tracking app reads your UPI payments and sorts each one into food, travel, shopping or bills. That's not a yes/no question. There are four possible answers, and the app should say how sure it is about each: "82% food, 15% shopping, 3% travel".

Logistic regression answers yes/no questions. Softmax regression (also called multinomial logistic regression) is the same idea extended to any number of classes. Each class gets its own score, and the softmax function turns the scores into probabilities that add up to 1. It's the standard linear model for multi-class problems, and the same softmax sits at the end of almost every neural network classifier, including the ones in large language models that pick the next word.

What you need first: logistic regression explained, logistic regression from scratch (its last section introduced softmax briefly), sigmoid and softmax functions and matrix multiplication.

Key terms

  • Multi-class classification: predicting one of three or more classes, such as penguin species or expense categories.
  • Score (or logit): a number for each class, where bigger means "more likely this class". Scores can be any number, positive or negative.
  • Softmax: the function that turns a list of scores into probabilities that are all positive and add up to 1.
  • One-hot encoding of the label: writing the true class as a row with a 1 for the correct class and 0 elsewhere, such as Chinstrap = [0, 1, 0].
  • Cross-entropy loss: minus the log of the probability the model gave to the correct class. The multi-class version of log loss.
  • One-vs-rest: an alternative that trains one separate yes/no model per class.

The problem: three penguin species

The Palmer penguins data has three species: Adelie, Chinstrap and Gentoo. We'll predict the species from two measurements first, so everything can be drawn on a flat picture.

Download the data: penguins.csv (14 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("penguins.csv").

import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split

penguins = sns.load_dataset("penguins").dropna(subset=["bill_length_mm", "flipper_length_mm"])
species = ["Adelie", "Chinstrap", "Gentoo"]
X = penguins[["bill_length_mm", "flipper_length_mm"]].to_numpy()
y = penguins["species"].map({name: k for k, name in enumerate(species)}).to_numpy()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
mean, std = X_train.mean(axis=0), X_train.std(axis=0)
X_train_s, X_test_s = (X_train - mean) / std, (X_test - mean) / std    # scale with training numbers only
print(X_train_s.shape, np.bincount(y_train))
(256, 2) [113  51  92]

The species become numbers 0, 1 and 2 with map, because NumPy maths needs numbers. np.bincount counts how many of each label there are. The features are standardised with the training mean and standard deviation, for the same reason as in logistic regression from scratch: gradient descent works much better when features are on similar scales.

Why not just use logistic regression three times?

The obvious idea is one-vs-rest: train three separate yes/no models, "Adelie or not?", "Chinstrap or not?", "Gentoo or not?", and pick the most confident. It works, and scikit-learn can do it. But look at what the three models say about one penguin:

from sklearn.linear_model import LogisticRegression

one_penguin = X_test_s[:1]
for k, name in enumerate(species):
    yes_no = LogisticRegression().fit(X_train_s, (y_train == k).astype(int))
    print(f"P({name}) from its own model: {yes_no.predict_proba(one_penguin)[0, 1]:.3f}")
P(Adelie) from its own model: 0.164
P(Chinstrap) from its own model: 0.348
P(Gentoo) from its own model: 0.042

Each model gives a sensible-looking probability, but they were trained separately and know nothing about each other, so the three numbers don't add up to 1. Is this penguin "mostly Adelie"? What do the leftover (or extra) percentages mean? Softmax regression fixes this: one model, where the classes compete for a single 100%.

From scores to probabilities: softmax

Softmax regression gives every class a score. Suppose for one penguin the scores are Adelie 2.0, Chinstrap 0.5 and Gentoo −1.0. Softmax turns them into probabilities in two steps:

  1. Exponentiate each score: e^2.0 ≈ 7.39, e^0.5 ≈ 1.65, e^−1.0 ≈ 0.37. Now every number is positive, and bigger scores give much bigger numbers.
  2. Divide by the total (7.39 + 1.65 + 0.37 = 9.41), so they add up to 1: 0.79, 0.18 and 0.04.
Softmax for one penguin with three class scores: Adelie 2.0, Chinstrap 0.5 and Gentoo minus 1.0. Exponentiating gives 7.39, 1.65 and 0.37, which add up to 9.41. Dividing each by 9.41 gives probabilities 0.79, 0.18 and 0.04, drawn as orange bars that add up to 1.

In symbols, the probability of class k is:

softmax(z)ₖ = e^(zₖ) ÷ Σⱼ e^(zⱼ)

Read it as: "e to the power of class k's score, divided by the sum of e to the power of every class's score." Check the numbers in Python:

def softmax(scores):
    scores = scores - scores.max(axis=1, keepdims=True)   # same answer, but no overflow on big scores
    exp_scores = np.exp(scores)
    return exp_scores / exp_scores.sum(axis=1, keepdims=True)

print(softmax(np.array([[2.0, 0.5, -1.0]])).round(3))
print(softmax(np.array([[102.0, 100.5, 99.0]])).round(3))
[[0.786 0.175 0.039]]
[[0.786 0.175 0.039]]

The function works on a table of scores, one row per penguin, so axis=1 means "across the classes in each row", and keepdims=True keeps the result as a column so the division lines up row by row. The second line shows why the code subtracts each row's largest score first: adding the same number (100) to every score doesn't change the probabilities, because only the gaps between scores matter. Subtracting the maximum keeps np.exp away from huge numbers that would overflow. Sigmoid and softmax functions covers this trick and why softmax with two classes is exactly the sigmoid.

Where the scores come from

Each class has its own weights and bias. A penguin's score for class k is a weighted sum of its features, just like logistic regression:

zₖ = wₖ₁ × bill + wₖ₂ × flipper + bₖ

With two features and three classes, that's a 2 × 3 table of weights W (one column per class) and three biases b. For all penguins at once, the scores are a matrix product:

Z = X W + b

Read: "the scores table is the features table times the weights table, plus the biases." The shapes show it works: (penguins × 2) times (2 × 3) gives (penguins × 3), one score per penguin per class. Then softmax turns each row of scores into probabilities, and the prediction is the class with the largest probability.

The loss: cross-entropy

How wrong is a prediction? Look only at the probability the model gave to the correct class, and take minus its log:

loss = −log(*p*_correct)

Probability given to the correct classLoss = −log(p)What it means
0.990.01Confident and right: almost no penalty
0.790.24Fairly sure and right: small penalty
0.331.10A guess among three classes
0.043.22Confident and wrong: big penalty

That's cross-entropy. It's the same log loss as in logistic regression; with two classes, they're identical. The training loss is the average over all penguins. It punishes confident mistakes heavily, which is what you want from a classifier that gives probabilities.

The gradient: predicted minus true

To train with gradient descent, you need to know how the loss changes when each score changes. The answer turns out to be very neat. Write the true class as a one-hot row y (Adelie = [1, 0, 0]). Then for each class:

∂loss/∂zₖ = pₖ − yₖ

Read: "the slope of the loss with respect to class k's score is the predicted probability minus the true value (1 or 0)." For the penguin above, if it really is a Chinstrap (y = [0, 1, 0]):

Classpyp − yWhat gradient descent does to the score
Adelie0.790+0.79Pushes it down a lot (it was wrongly high)
Chinstrap0.181−0.82Pushes it up a lot (the right answer was too low)
Gentoo0.040+0.04Pushes it down a little

That matches common sense: raise the correct class's score, lower the others, each in proportion to how wrong it was. Getting from the formula to p − y takes a page of chain-rule algebra (differentiating the log, then the softmax division); it's skipped here, and you'll check it numerically below instead.

From scores back to weights, the chain rule multiplies by the features, exactly as in binary logistic regression. Averaged over n penguins:

gradient for W = (1/n) Xᵀ (P − Y), and gradient for b = average of (P − Y) over the rows

Here P is the table of predicted probabilities and Y the table of one-hot labels. Compare with the binary case from the from-scratch lesson, (1/n) Xᵀ(p − y): it's the same formula, with a column per class instead of one column.

Check the gradient numerically

Don't take the formula on trust. Nudge one score a tiny amount, measure how the loss changes, and compare with p − y:

def cross_entropy(probabilities, labels):
    rows = np.arange(len(labels))
    return -np.mean(np.log(probabilities[rows, labels]))

scores = np.array([[2.0, 0.5, -1.0]])
true_class = np.array([1])                     # the penguin is a Chinstrap
p = softmax(scores)
formula = p - np.eye(3)[true_class]            # np.eye(3)[1] is the one-hot row [0, 1, 0]

h = 1e-6
numeric = []
for k in range(3):
    nudged = scores.copy()
    nudged[0, k] += h
    numeric.append((cross_entropy(softmax(nudged), true_class) - cross_entropy(p, true_class)) / h)
print("formula p - y:", formula.round(4))
print("numerical:    ", np.round(numeric, 4))
formula p - y: [[ 0.7856 -0.8247  0.0391]]
numerical:     [ 0.7856 -0.8247  0.0391]

probabilities[rows, labels] picks, from each row, the probability in the correct class's column. np.eye(3) is the 3 × 3 identity matrix, and picking its row k gives the one-hot row for class k. The two lines agree to four decimal places: the formula is right.

Build it in NumPy

Now train it. Start with all weights at zero (every class equally likely), then repeat: compute scores, softmax, the gradient, and step downhill:

n_features, n_classes = X_train_s.shape[1], 3
W = np.zeros((n_features, n_classes))
b = np.zeros(n_classes)
Y_train = np.eye(n_classes)[y_train]           # one-hot labels, shape (penguins, 3)
learning_rate = 0.5

for epoch in range(1001):
    P = softmax(X_train_s @ W + b)
    if epoch % 250 == 0:
        print(f"epoch {epoch:4}: loss {cross_entropy(P, y_train):.3f}")
    W -= learning_rate * X_train_s.T @ (P - Y_train) / len(X_train_s)
    b -= learning_rate * (P - Y_train).mean(axis=0)

test_P = softmax(X_test_s @ W + b)
print("test accuracy:", round(float(np.mean(test_P.argmax(axis=1) == y_test)), 3))
epoch    0: loss 1.099
epoch  250: loss 0.137
epoch  500: loss 0.129
epoch  750: loss 0.127
epoch 1000: loss 0.126
test accuracy: 0.965

At epoch 0, every probability is 1/3, so the loss is −log(1/3) ≈ 1.099, a pure guess. It falls quickly and then levels off. argmax(axis=1) picks the column with the highest probability in each row, which is the predicted class.

Predict: most test penguins are classified correctly. Which pair of species do you expect the mistakes to come from? Look at the picture.

The picture to keep: a plane cut into regions

Colour every point on the map by the class the model would predict there:

import matplotlib.pyplot as plt

bill_grid, flipper_grid = np.meshgrid(np.linspace(30, 62, 300), np.linspace(168, 235, 300))
grid = np.column_stack([bill_grid.ravel(), flipper_grid.ravel()])
grid_class = softmax(((grid - mean) / std) @ W + b).argmax(axis=1).reshape(bill_grid.shape)

colours = ["#c2410c", "#0f766e", "#1d4ed8"]
fig, ax = plt.subplots(figsize=(8, 6))
ax.contourf(bill_grid, flipper_grid, grid_class, levels=[-0.5, 0.5, 1.5, 2.5],
            colors=["#fbe9dc", "#d5ece9", "#dbe4fb"])
for k, name in enumerate(species):
    rows = y_train == k
    ax.scatter(X_train[rows, 0], X_train[rows, 1], s=18, color=colours[k], label=name)
ax.set_xlabel("Bill length (mm)")
ax.set_ylabel("Flipper length (mm)")
ax.set_title("Softmax regression cuts the plane with straight boundaries")
ax.legend(loc="upper left")
plt.show()
A scatter plot of training penguins, bill length across and flipper length up, over three shaded regions. The orange region on the left (short bills) is Adelie, the green region at the lower right (long bills, shorter flippers) is Chinstrap, and the blue region at the top (long flippers) is Gentoo. The boundaries between regions are straight lines meeting near the middle. A few points sit on the wrong side of a boundary, mostly near the Adelie–Chinstrap border and a few near the Chinstrap–Gentoo border.

np.meshgrid makes a fine grid of bill and flipper values covering the plot, ravel turns it into a list of points, and contourf fills each area with the colour of its predicted class. Every boundary is a straight line: between any two classes, the boundary is where their scores are equal, and each score is a straight-line function of the features. That's the picture to remember: softmax regression cuts the feature space into regions with straight cuts. The few training points on the wrong side sit along the borders: mostly where Adelie and Chinstrap bills overlap, and a few where Chinstrap and Gentoo flippers overlap.

Check against scikit-learn

Scikit-learn's LogisticRegression uses softmax automatically when there are more than two classes. By default it also adds an L2 penalty (C=1.0), which our version doesn't have, so turn it off with penalty=None for a fair comparison:

library = LogisticRegression(penalty=None).fit(X_train_s, y_train)
library_P = library.predict_proba(X_test_s)

agree = int(np.sum(library_P.argmax(axis=1) == test_P.argmax(axis=1)))
print(f"same predictions: {agree} of {len(test_P)}")
print("largest probability difference:", round(float(np.abs(library_P - test_P).max()), 3))
print("scikit-learn test accuracy:", round(library.score(X_test_s, y_test), 3))
same predictions: 85 of 86
largest probability difference: 0.054
scikit-learn test accuracy: 0.953

All but one of the test predictions match, and no probability differs by more than about 0.05. The small differences come from our gradient descent stopping after 1,000 epochs, while scikit-learn's solver runs until the weights barely change. The one penguin that differs sits right on the Adelie–Chinstrap border, where a tiny change in the weights tips it from one side to the other, which is also why the two accuracies differ by one penguin. The library is a faster way of doing what you just built by hand.

Experiment: change learning_rate = 0.5 to 0.05 and run the training loop again. With steps ten times smaller, the loss at epoch 1,000 is still 0.162 instead of 0.126: the model is still walking downhill. Then try 5.0. Here, bigger steps simply get there faster (the loss is already 0.364 after one epoch and ends at 0.125), because cross-entropy for this small, scaled problem is a gentle bowl. On other problems, a rate that large can overshoot, as in gradient descent explained; the only way to know is to watch the loss.

All four features

With only two features, the overlap between Adelie and Chinstrap causes the mistakes. Using all four measurements in a pipeline:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

four = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
full = penguins.dropna(subset=four)
X4_train, X4_test, y4_train, y4_test = train_test_split(
    full[four], full["species"], test_size=0.25, random_state=0, stratify=full["species"])

model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X4_train, y4_train)
print("test accuracy:", round(model.score(X4_test, y4_test), 3))
print(model.predict_proba(X4_test[:2]).round(3), model.classes_)
test accuracy: 0.988
[[0.458 0.522 0.02 ]
 [0.999 0.    0.   ]] ['Adelie' 'Chinstrap' 'Gentoo']

Scikit-learn also accepts the species names directly as labels and sorts them into classes_, which gives the column order of predict_proba. Here it's back to the default L2 penalty, which is the usual choice in practice: it keeps the weights from growing huge when classes are perfectly separable.

Where it fails: boundaries that aren't straight

Because every boundary is a straight line, softmax regression can't separate classes arranged in rings. Here are three made-up classes: an inner disc, a middle ring and an outer ring:

rng = np.random.default_rng(0)
radius = np.concatenate([rng.uniform(0, 1, 200), rng.uniform(1.5, 2.5, 200), rng.uniform(3, 4, 200)])
angle = rng.uniform(0, 2 * np.pi, 600)
rings_X = np.column_stack([radius * np.cos(angle), radius * np.sin(angle)])
rings_y = np.repeat([0, 1, 2], 200)

flat = LogisticRegression().fit(rings_X, rings_y)
print("straight boundaries:", round(flat.score(rings_X, rings_y), 3))

with_distance = np.column_stack([rings_X, (rings_X ** 2).sum(axis=1)])   # add x² + y²
curved = LogisticRegression().fit(with_distance, rings_y)
print("with x² + y² added: ", round(curved.score(with_distance, rings_y), 3))
straight boundaries: 0.418
with x² + y² added:  1.0

Predict before reading: why is the first score so poor? No straight line can separate a disc from a ring around it. Each class gets a region shaped like a slice of the plane, but the true classes are nested circles. Adding one engineered feature, the squared distance from the centre (x² + y²), fixes it: in that new feature, the three classes are simply "small", "medium" and "large", which straight cuts separate easily. This is feature engineering doing what the model can't. (Both scores here are on the training data, because the point is whether the model can draw the right shape at all.)

When to use softmax regression

SituationUse softmax regression?Instead
Several classes, you want calibrated-ish probabilities and a simple modelYes
You need to explain which features push towards which classYes: read each class's weights
Many features, such as word counts for text categoriesYes, with L2 regularisationNaive Bayes is a fast alternative
Classes separated by curved or nested shapesNot on its ownEngineer features, or use KNN, trees or SVM with kernels
Several labels can be true at once (a movie that's both comedy and romance)No: softmax forces one winnerOne sigmoid per label (multi-label)
Very many classes (thousands of words)It's the output layer of neural networks for thisNeural networks, with softmax at the end

Common mistakes

  • Using softmax when labels aren't exclusive. Softmax makes classes compete for 100%. If a photo can contain both a dog and a cat, use a separate sigmoid for each label.
  • Forgetting to subtract the maximum score. np.exp(1000) overflows to inf, and the probabilities become nan.
  • Mixing up the columns. predict_proba columns follow classes_, which scikit-learn sorts. Check the order before reading the numbers.
  • Not scaling the features. Gradient descent crawls, and the regularisation penalty treats features unfairly.
  • Reading the boundaries as curved. Without engineered features, softmax regression only draws straight boundaries.

Practice

  1. Scores for one transaction are food 1.0, travel 1.0, shopping 3.0. Work out the softmax probabilities by hand (e ≈ 2.718), then check with the softmax function.
Show the answer

e^1 ≈ 2.718, e^1 ≈ 2.718, e^3 ≈ 20.09. The sum is about 25.52. Probabilities: 2.718 ÷ 25.52 ≈ 0.107, 0.107, and 20.09 ÷ 25.52 ≈ 0.787.

print(softmax(np.array([[1.0, 1.0, 3.0]])).round(3))
[[0.107 0.107 0.787]]

Food and travel have equal scores, so they get equal probabilities.

  1. Predict: you add 5 to every class's score. What happens to the probabilities? Why?
Show the answer

Nothing. e^(z + 5) = e^z × e^5, so every top and the bottom of the fraction are multiplied by the same e^5, which cancels. Only the gaps between scores matter. That's also why subtracting the maximum score is safe.

  1. A model gives the correct class a probability of 0.5. What's the cross-entropy for that example? What if it gave 0.05?
Show the answer

−log(0.5) ≈ 0.69 and −log(0.05) ≈ 3.00. The confident mistake costs more than four times as much.

  1. In the gradient table, why is the Gentoo row's p − y so small, even though the model was wrong about this penguin?
Show the answer

The model only gave Gentoo 0.04, so it was already almost right about Gentoo ("not Gentoo"). Its gradient pushes that score down only a little. Most of the correction goes to the classes it was most wrong about: Adelie (too high) and Chinstrap (too low).

  1. Spot the bug:
def bad_softmax(scores):
    exp_scores = np.exp(scores)
    return exp_scores / exp_scores.sum()

It's used on a table of scores for 100 penguins. What goes wrong?

Show the answer

exp_scores.sum() adds up every number in the whole table, so each row's probabilities sum to about 1/100 instead of 1. It needs exp_scores.sum(axis=1, keepdims=True) to divide each row by its own total. It also doesn't subtract the maximum, so large scores would overflow.

  1. A news app wants to tag each article with every topic it covers: politics, sport, business, technology. Should it use softmax regression? Explain.
Show the answer

No. An article about a cricket board's finances is both sport and business, but softmax makes the topics compete for a single 100%, so it would spread probability between them and push you to pick one. Use one sigmoid output per topic (one-vs-rest without normalising), and tag every topic whose probability is above a threshold.

Interview questions

What is the difference between softmax regression and one-vs-rest logistic regression?

One-vs-rest trains a separate binary classifier per class, each ignoring the others, so their probabilities don't sum to 1 and must be normalised afterwards. Softmax (multinomial) regression trains one model with a weight vector per class, and the softmax ties them together so the probabilities sum to 1 and the classes compete directly. Multinomial is usually preferred when classes are mutually exclusive.

Why is the gradient of cross-entropy with softmax equal to p − y?

Differentiating −log of the softmax output for the correct class with respect to each score gives the predicted probability minus the one-hot target. The log cancels the exponential in softmax, leaving a simple difference. It means each score is pushed up or down in proportion to how far its probability is from the truth.

Why do neural network classifiers use softmax in the last layer?

The last layer produces one score per class, and softmax turns them into a probability distribution, which pairs with cross-entropy loss to give simple, well-behaved gradients (p − y). It's softmax regression applied to features learned by the earlier layers.

Key takeaways

  • Softmax regression gives each class a score (a weighted sum of features) and turns scores into probabilities that add up to 1.
  • Softmax: exponentiate, then divide by the total. Only the gaps between scores matter.
  • The loss is cross-entropy, −log of the correct class's probability; the gradient for each score is p − y.
  • Training is the binary logistic regression loop with a weight column per class: W −= rate × Xᵀ(P − Y)/n.
  • Every boundary is a straight line; curved or nested classes need engineered features or another model.
  • Use it when classes are mutually exclusive; use one sigmoid per label when several can be true at once.

Frequently asked questions

Is softmax regression the same as multinomial logistic regression?

Yes. Softmax regression, multinomial logistic regression and maximum entropy classifier are names for the same model: a linear score per class, softmax to get probabilities, and cross-entropy loss.

Does scikit-learn's LogisticRegression use softmax for many classes?

Yes. With more than two classes and the default solver, LogisticRegression fits a multinomial (softmax) model. To get one-vs-rest instead, wrap it in OneVsRestClassifier.

What is the difference between softmax and sigmoid?

Sigmoid turns one score into one probability, for yes/no problems or independent labels. Softmax turns several scores into probabilities that add up to 1, for choosing one of many classes. With two classes, softmax gives exactly the same answer as the sigmoid of the difference between the two scores.

What to learn next

  1. Diabetes prediction project: the full logistic regression workflow on real medical data.
  2. Classification metrics: precision, recall and F1, including averages over many classes.
  3. KNN algorithm explained: a model that can draw curved boundaries.