A spam filter adds up evidence from an email: a suspicious link, the word "winner", an unknown sender.3. But what does 2.3 mean? Is that spam? How sure is it? A score can be any number, from −1,000 to +1,000. What you want is a probability: "87% likely to be spam".
Two functions do that conversion, and they're among the most used formulas in all of machine learning:
- The sigmoid turns one score into a probability between 0 and 1, for yes/no questions.
- The softmax turns several scores into probabilities that add up to 1, for choosing between many classes: cat, dog or bird.
Both are built from the number e. This lesson explains them step by step, with worked numbers, charts and NumPy code, including the trick that keeps softmax from crashing on large numbers. It's the last lesson of the exponents and logarithms module, and it ties the whole module together.
What you need first: the number e explained and logarithms explained.
Key terms
- Score (or logit): the raw number a model calculates before converting it to a probability. It can be any real number.
- Sigmoid: σ(z) = 1/(1 + e⁻ᶻ), which squeezes any score into 0 to 1.
- Softmax: converts a list of scores into probabilities that sum to 1.
- Threshold: the probability above which you predict "yes", often 0.5.
- Temperature: a number that makes softmax probabilities sharper or flatter.
The sigmoid function
σ(z) = 1 / (1 + e⁻ᶻ)
Follow what happens for different scores z:
| z | e⁻ᶻ | 1 + e⁻ᶻ | σ(z) |
|---|---|---|---|
| very negative, −10 | huge, 22,026 | huge | close to 0 |
| −2 | 7.39 | 8.39 | 0.119 |
| 0 | 1 | 2 | exactly 0.5 |
| 2 | 0.135 | 1.135 | 0.881 |
| very positive, 10 | tiny, 0.000045 | about 1 | close to 1 |
Because e⁻ᶻ is always positive, the bottom is always more than 1, so σ(z) is always between 0 and 1, never reaching either. It's a perfect fit for a probability.
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
z = np.array([-5, -2, 0, 2, 5])
print(sigmoid(z).round(3))
zs = np.linspace(-8, 8, 300)
fig, ax = plt.subplots()
ax.plot(zs, sigmoid(zs), lw=2)
ax.axhline(0.5, color="grey", ls="--", lw=0.8)
ax.axvline(0, color="grey", lw=0.8)
ax.plot(z, sigmoid(z), "o", color="black")
ax.set_xlabel("score, z")
ax.set_ylabel("σ(z): probability")
ax.set_title("The sigmoid squeezes any score into 0 to 1")
plt.show()
[0.007 0.119 0.5 0.881 0.993]
Key properties:
- σ(0) = 0.5: a score of zero means "no idea either way".
- Symmetric: σ(−z) = 1 − σ(z). A score of −2 gives 0.119, and +2 gives 0.881, which adds to 1.
- Saturates: beyond about ±5, extra score hardly changes the probability. Being "more sure" than 99% barely moves.
From probability to decision: the threshold
The sigmoid gives a probability; a threshold turns it into a decision. With a threshold of 0.5, predict "spam" when σ(z) ≥ 0.5, which happens exactly when the score z ≥ 0. Moving the threshold trades false alarms for missed cases, an inequality you tune with classification metrics.
Going back: the logit
The sigmoid's inverse is the logit, ln(p / (1 − p)), which turns a probability back into a score:
p = sigmoid(2.0)
print(round(p, 4), round(np.log(p / (1 - p)), 4))
0.8808 2.0
p/(1 − p) is the odds (0.88/0.12 ≈ 7.4 to 1), so the score is the log-odds. That's how logistic regression works: it predicts log-odds with a straight line, z = b + w₁x₁ + w₂x₂ + …, then applies the sigmoid. Each coefficient says how much a feature raises the log-odds.
The softmax function
What if there are three or more classes? Say an image model gives the scores cat: 2.0, dog: 1.0, bird: 0.1. Softmax converts them in two steps:
- Exponentiate each score: e^2.0 = 7.389, e^1.0 = 2.718, e^0.1 = 1.105. This makes every value positive, and makes bigger scores much bigger.
- Divide each by the total (11.212), so they add to 1.
| Class | Score | eˢᶜᵒʳᵉ | Probability |
|---|---|---|---|
| cat | 2.0 | 7.389 | 7.389 / 11.212 = 0.659 |
| dog | 1.0 | 2.718 | 2.718 / 11.212 = 0.242 |
| bird | 0.1 | 1.105 | 1.105 / 11.212 = 0.099 |
In symbols: softmax(zᵢ) = e^(zᵢ) / Σⱼ e^(zⱼ). The Σ means "add up over all classes"; it gets its own lesson in summation notation.
def softmax(scores):
exps = np.exp(scores - np.max(scores)) # the stability trick, explained below
return exps / exps.sum()
scores = np.array([2.0, 1.0, 0.1])
probs = softmax(scores)
print(probs.round(3), probs.sum())
[0.659 0.242 0.099] 1.0
Notice that the cat's score is only twice the dog's, but its probability is almost three times as high. Exponentiating exaggerates differences: the "soft" version of picking the maximum, hence the name softmax.
Sigmoid is softmax with two classes
Softmax of the scores [z, 0] gives exactly [σ(z), 1 − σ(z)]:
print(softmax(np.array([2.0, 0.0])).round(4), round(sigmoid(2.0), 4))
[0.8808 0.1192] 0.8808
So the sigmoid is just the two-class special case of softmax.
The stability trick
Computers can't store e¹⁰⁰⁰: it overflows to infinity, and infinity divided by infinity gives nan (not a number). A model with large scores would crash.
The fix: subtract the largest score from every score first. By the index law eᵃ⁻ᶜ = eᵃ/eᶜ, this divides the top and bottom of every fraction by the same eᶜ, so the probabilities don't change. But now the largest exponent is e⁰ = 1, and nothing can overflow:
print(softmax(np.array([1000.0, 999.0, 998.0])).round(3))
[0.665 0.245 0.09 ]
The scores 1000, 999, 998 have the same gaps as 2, 1, 0, so they give the same probabilities as softmax([2, 1, 0]). That's why the softmax function above includes - np.max(scores), and why libraries like PyTorch and scikit-learn always do this internally.
Temperature: sharper or flatter
Dividing the scores by a temperature T before softmax controls how confident the probabilities are:
for T in [0.5, 1.0, 2.0]:
print(T, softmax(scores / T).round(3))
0.5 [0.864 0.117 0.019]
1.0 [0.659 0.242 0.099]
2.0 [0.502 0.304 0.194]
- Low temperature (below 1): sharper; the top class dominates.
- High temperature (above 1): flatter; the choices become more even.
This is exactly the "temperature" setting of AI chatbots: they choose each next word with a softmax over all possible words, and higher temperature makes less likely words more likely to be picked, so the replies are more varied.
Where they're used
| Function | Used in |
|---|---|
| Sigmoid | logistic regression, binary classifiers, multi-label problems (each label is its own yes/no), gates inside some neural networks |
| Softmax | the last layer of multi-class neural networks, multinomial logistic regression, language models choosing the next word, attention in transformers |
Both are paired with log loss: the model is trained to maximise the log of the probability it gives to the correct class, using the logarithm rules from this module.
Practice
- What is σ(0)? What happens to σ(z) as z becomes very large, and very negative?
Show the answer
σ(0) = 0.5. It approaches 1 for very large z and 0 for very negative z, without reaching either.
- If σ(3) ≈ 0.953, what is σ(−3)?
Show the answer
By symmetry, 1 − 0.953 = 0.047.
- Work out the softmax of the scores [1, 1, 1].
Show the answer
All exponentials are equal, so each probability is 1/3.
- Work out the softmax of [0, ln(3)] by hand.
Show the answer
e⁰ = 1 and e^(ln 3) = 3. Total 4. Probabilities: [0.25, 0.75].
- Why does subtracting the maximum score not change the softmax result?
Show the answer
Subtracting c from every score divides every eˢᶜᵒʳᵉ by eᶜ, top and bottom of each fraction alike, so the ratios, and therefore the probabilities, are unchanged.
Key takeaways
- The sigmoid σ(z) = 1/(1 + e⁻ᶻ) turns one score into a probability between 0 and 1; σ(0) = 0.5.
- Its inverse, the logit ln(p/(1 − p)), turns a probability back into log-odds.
- Softmax exponentiates several scores and divides by their total, giving probabilities that sum to 1.
- The sigmoid is softmax with two classes.
- Subtract the maximum score before exponentiating to avoid overflow.
- Temperature sharpens (low) or flattens (high) the probabilities.
Frequently asked questions
What is the sigmoid function used for?
It converts any real-valued score into a probability between 0 and 1, which makes it the output function for yes/no classifiers such as logistic regression.
What is the difference between sigmoid and softmax?
Sigmoid converts one score into one probability, for two-class problems. Softmax converts a list of scores into a probability for each class, all adding to 1, for problems with many classes. With two classes, they're equivalent.
Why subtract the maximum in softmax?
Exponentials of large scores overflow to infinity in a computer. Subtracting the largest score from all scores keeps every exponent at most 0, without changing the resulting probabilities.
What to learn next
- Start the maths notation module with summation notation (Σ) explained.
- Revisit why data scientists use log scales.