NEURAL NETWORKS / PROBABILITIES / FIELD GUIDEscores → exponentials → probabilities
Back to field guides

FIELD GUIDE 11

Softmax Function Explained,
Step by Step

Scores in, probabilities out.

Short answerThe softmax function takes a list of any real numbers (scores, often called logits) and turns them into a list of probabilities: every output is between 0 and 1, and all of them add up to exactly 1.
Glass jars of different sizes filled with colored marbles on a wooden shelf in soft daylight
Softmax shares out one whole between the options, and bigger scores get bigger shares.
Updated November 11, 2026Beginner-first / Worked example + code

00 Short answer

The quick
version.

Short answer: the softmax function takes a list of any real numbers (scores, often called logits) and turns them into a list of probabilities: every output is between 0 and 1, and all of them add up to exactly 1. It does that by taking e to the power of each score and dividing by the total. Bigger scores get a bigger share, the order of the scores never changes, and no option ever gets exactly zero. That's why softmax sits at the end of most classifiers and language models, and inside every attention layer.

01 Start here

\1

Neural networks are good at producing scores: "this image looks 2.0 cat, 1.0 dog, 0.1 rabbit." Raw scores are hard to use. They can be negative, they don't add up to anything in particular, and you can't read them as "how likely". Softmax converts them into a probability distribution you can sample from, compare, or train with.

It's called softmax because it's a smooth, "soft" version of picking the maximum. A hard argmax says "cat, 100%, everything else 0%". Softmax says "cat gets most of the probability, but dog and rabbit keep a share", and it does so in a way that can be differentiated, so a network can learn through it.

02 The math

\1

For a vector of scores z with K entries, the softmax of entry i is:

softmax(z)i=ezi∑j=1Kezj

In plain text: softmax(z_i) = exp(z_i) / Σ_j exp(z_j).

Two steps:

  1. Exponentiate every score. This makes every value positive and stretches the gaps between scores.
  2. Normalize: divide each exponentiated value by their sum, so the results add up to 1.

03 Worked example

\1

Say a tiny classifier outputs these logits for one image:

Class Logit z exp(z) Probability = exp(z) / sum
cat 2.0 7.389 0.659 (65.9%)
dog 1.0 2.718 0.242 (24.2%)
rabbit 0.1 1.105 0.099 (9.9%)
Sum 11.212 1.000

The numbers are made up for illustration, not output from a real model. Notice what happened:

  • The ranking stayed the same. Cat > dog > rabbit, before and after.
  • The gaps grew. A logit gap of 1.0 (cat vs dog) became a probability ratio of e¹ ≈ 2.7. Every extra point of logit multiplies the odds by about 2.7.
  • Nothing hit zero. Even the weakest class keeps about 10%.

You can check it with a calculator: exp(2.0) = 7.389, exp(1.0) = 2.718, exp(0.1) = 1.105, and each divided by their sum.

04 Key ideas

\1

  • Outputs are in (0, 1) and sum to 1. That's what makes them a probability distribution.
  • Order-preserving. The largest score always gets the largest probability.
  • Shift-invariant. Adding the same number to every score changes nothing: softmax(z + c) = softmax(z). In the example, logits of 102.0, 101.0 and 100.1 give exactly the same 0.659 / 0.242 / 0.099. This property is what makes the stable version below possible.
  • Not scale-invariant. Multiplying the scores does change the result. Doubling the example logits to 4.0, 2.0 and 0.2 gives about 0.864 / 0.117 / 0.019: the distribution gets sharper. Dividing them makes it flatter. That's exactly how temperature works in language models (more below).
  • Smooth and differentiable, which is why gradient descent can train through it.

05 In practice

\1

On a computer, exp() overflows fast. In 32-bit floating point, exp(89) is already too big to represent. A real model can easily produce a logit of 1,000, and naive code returns inf / inf = NaN.

The fix uses shift invariance: subtract the maximum score before exponentiating.

softmax(z)i=ezi−max(z)∑jezj−max(z)

Now the largest exponent is e⁰ = 1, nothing can overflow, and the answer is mathematically identical. Every serious library does this for you.

06 Code

\1

import numpy as np

def softmax(z, axis=-1):
    z = np.asarray(z, dtype=float)
    z_shifted = z - np.max(z, axis=axis, keepdims=True)  # stability trick
    exp_z = np.exp(z_shifted)
    return exp_z / np.sum(exp_z, axis=axis, keepdims=True)

logits = [2.0, 1.0, 0.1]
print(softmax(logits).round(3))          # [0.659 0.242 0.099]
print(softmax([1002, 1001, 1000.1]).round(3))  # same answer, no overflow

In PyTorch, use torch.softmax(x, dim=-1) (or torch.nn.functional.softmax). The dim argument matters: it's the axis whose values should add up to 1, usually the last one (classes or vocabulary). For training, use the library's combined loss (for example torch.nn.CrossEntropyLoss, which takes raw logits) instead of applying softmax yourself first. It's faster and more numerically stable.

If you want to build the rest of a network around it, our neural network from scratch in Python tutorial uses the same NumPy style.

07 Compare

\1

Softmax Sigmoid
Input A vector of K scores One score (applied to each output separately)
Output K probabilities that sum to 1 Each output between 0 and 1, independent
Use when Exactly one class is correct (cat or dog or rabbit) Several labels can be true at once (an image can be "outdoor" and "has a dog")
Typical loss Categorical cross-entropy Binary cross-entropy

They're closely related. Softmax over two scores, a and 0, gives exactly sigmoid(a) for the first class. Sigmoid is softmax's two-class special case.

08 Connect it

\1

As an output layer, softmax turns the final layer's scores into class probabilities. (Hidden layers use activations like ReLU instead; softmax is rarely used there.) The feed-forward network lesson shows where that output layer sits.

Softmax is almost always paired with cross-entropy loss: loss = −log(p_correct). In the example, if "cat" is the right answer, the loss is −log(0.659) ≈ 0.417. The pairing has a famously clean gradient. The gradient of the loss with respect to each logit is simply:

∂L∂zi=pi−yi

where y is 1 for the correct class and 0 otherwise. For the example that's −0.341 for cat (push its logit up), +0.242 for dog and +0.099 for rabbit (push those down). The model nudges each score by exactly how wrong its probability was. Gradient descent does the rest; see gradient descent explained.

For softmax on its own, the derivative is a full matrix (the Jacobian): ∂p_i/∂z_j = p_i (δ_ij − p_j). Each output depends on every input, because they all share one denominator.

09 Connect it

\1

Softmax is also the heart of the attention mechanism in transformers. For each token, attention computes a score against every other token (the dot product of a query with each key), divides by √d_k, and applies softmax across those scores. The result is a set of attention weights that add up to 1, which decide how much of each token's value vector gets mixed in:

Attention(Q,K,V)=softmax(QK⊤dk)V

The √d_k scaling is there because of the "not scale-invariant" property: as vectors get longer, dot products get larger, and softmax would become so sharp that almost all weight lands on one token, with gradients close to zero. The attention lesson lets you play with these weights, and the transformer block lesson shows the tensor shapes, where softmax runs over the last axis of a (B, h, T, T) score tensor.

10 Connect it

\1

At the very end of a language model, softmax turns a score for every token in the vocabulary into next-token probabilities. Temperature divides the logits before that softmax: softmax(z / T). Below 1 the distribution gets sharper, above 1 it gets flatter. That's the scale property from above in action. For worked numbers, top-p and recommended settings, see what temperature means in an LLM.

Old brass balance scale with small weights on a sunlit wooden desk
Every option gets a share of the weight. The shares always balance to one.

11 Watch out

\1

  • Softmax over the wrong axis. With a batch of shape (batch, classes), softmax goes over classes, not batch. Check that each row sums to 1.
  • Applying softmax twice. Many loss functions expect raw logits and apply (log-)softmax internally. Feeding them probabilities silently hurts training.
  • Reading probabilities as confidence you can trust. Softmax outputs always look like a tidy distribution, even for inputs the model has never seen. A 0.95 doesn't guarantee the model is right 95% of the time; calibration is a separate question.
  • Using softmax for multi-label problems. If several labels can be true, use sigmoid per label instead.
  • Forgetting the stability trick in hand-written code.

FAQ Softmax function / quick answers

Questions,
answered.

Short explanations with the limits left visible.

· informational guide

01 / answerWhat is the softmax function in simple terms?

It's a function that turns a list of scores into probabilities. It raises e to each score and divides by the total, so every output is between 0 and 1, they add up to 1, and bigger scores get bigger shares.

02 / answerWhat is the softmax formula?

softmax(z_i) = exp(z_i) / Σ_j exp(z_j). Each score is exponentiated, then divided by the sum of all the exponentiated scores.

03 / answerWhy is it called softmax?

Because it's a smooth ("soft") version of the max. A hard argmax gives the winner 100% and everything else 0%; softmax gives the winner the largest share while every other option keeps some probability, and it stays differentiable.

04 / answerWhy does softmax use the exponential function?

Exponentials make every value positive, turn differences in scores into ratios (each extra point of score multiplies the odds by about 2.7), and pair neatly with cross-entropy loss, giving the simple gradient p − y.

05 / answerWhat's the difference between softmax and sigmoid?

Softmax produces probabilities across several mutually exclusive classes that sum to 1. Sigmoid squashes each score independently to between 0 and 1, which suits multi-label problems. For two classes, softmax reduces to sigmoid.

06 / answerWhat is numerically stable softmax?

It's softmax computed after subtracting the largest score from every score. The result is identical, because softmax is shift-invariant, but exp() can no longer overflow.

07 / answerWhere is softmax used in transformers?

In two places: inside every attention layer, to turn query-key scores into attention weights, and at the output, to turn vocabulary logits into next-token probabilities.

08 / answerIs softmax an activation function?

Yes, it's usually described as an activation function, but it's used almost only in output layers and in attention, not in hidden layers.

Sources Papers / official docs

Read the
sources.

↗keep exploring

More explainAI
field guides.