Sub topic 4
The sigmoid: turning a score into a probability
This chapter assumes you know basic Python and NumPy, linear regression, and conditional probability. It also assumes you have seen odds and log-odds in the previous chapter.
The model in one line
Logistic regression computes a linear score and passes it through the sigmoid function. The score is z = w·x + b. The sigmoid maps any real number to a value between 0 and 1:
σ(z) = 1 / (1 + e^(−z))
The model's output is P(y = 1 | x) = σ(w·x + b).
Where the sigmoid comes from
The previous chapter showed that log-odds can take any real value. So we let the linear score equal the log-odds of the positive class:
log( p / (1 − p) ) = z
Exponentiate both sides to get p / (1 − p) = e^z. Solve for p:
- p = e^z (1 − p)
- p (1 + e^z) = e^z
- p = e^z / (1 + e^z) = 1 / (1 + e^(−z))
The sigmoid is the inverse of the logit. The logit turns a probability into a score. The sigmoid turns a score back into a probability.
Properties worth remembering
- σ(0) = 0.5, so a score of zero means the model is undecided.
- σ(−z) = 1 − σ(z), so the curve is symmetric around 0.5.
- The output is never exactly 0 or 1, but it gets close for large |z|.
- The derivative is σ(z)(1 − σ(z)). It is largest at z = 0 and near zero in the tails. This detail shows up again when we compute the gradient.
Seeing it in code
The code below evaluates the sigmoid at a few scores. It uses a form that avoids overflow when z is a large negative number.
import numpy as np
def sigmoid(z):
z = np.asarray(z, dtype=float)
out = np.empty_like(z)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
ez = np.exp(z[~pos])
out[~pos] = ez / (1.0 + ez)
return out
scores = np.array([-10, -2, 0, 2, 10])
print(sigmoid(scores).round(4))
# [0. 0.1192 0.5 0.8808 1. ]A worked case: suppose w = 1.5, b = −1, and x = 2. Then z = 1.5 · 2 − 1 = 2, and p = σ(2) ≈ 0.88. The model says the example has about an 88% chance of being in the positive class.
Common errors
- Calling the output a label. The sigmoid gives a probability. Turning it into a class needs a threshold, which the next chapter covers.
- Computing exp(−z) directly for very negative z. This overflows to infinity and can produce warnings. The two-branch version above avoids it.
- Reading the slope as constant. One unit of x always changes the log-odds by w. It changes the probability by an amount that depends on where you are on the curve.
Exercise
A model has w = 0.8 and b = −2. For x = 5, what is the score z, and is the predicted probability above or below 0.5?
Show answer
z = 0.8 · 5 − 2 = 2. Since z is positive, σ(2) ≈ 0.88, which is above 0.5.
Exercise
Starting from p / (1 − p) = e^z, show that σ(−z) = 1 − σ(z).
Show answer
σ(−z) = 1 / (1 + e^z). Also 1 − σ(z) = 1 − 1 / (1 + e^(−z)) = e^(−z) / (1 + e^(−z)). Multiply the top and bottom by e^z to get 1 / (e^z + 1), which equals σ(−z).