Classification and logistic regression
Is this email spam or not? Will this visitor click the ad or not? Guessing "this side or that side" like this is called classification. The most basic way to do it is logistic regression. Move the S-shaped curve that turns a score into a probability, and the line that splits two groups.
Short answer. Classification means guessing which side something belongs to. Logistic regression multiplies the inputs by weights and adds a bias to get a score (z = w × x + b). Then it puts the score through the sigmoid function to get a probability between 0 and 1. The place where the probability is 0.5 is the line that splits the two groups (the decision boundary).
You can also click or drag on the graph to move x. The blue curve is the current curve. The gray dashed curve is the one for w = 1, b = 0. The background is green where p is 0.5 or more and orange where it is below 0.5. The black vertical dashed line is the x where p = 0.5. At the starting values (w = 1, b = 0) the score z equals x, so you can read the bottom axis as the score.
Definitions
The text below explains with pictures and experiments. These are the textbook definitions. The input is , the weights are , the bias is b, and the label is y ∈ {0, 1}. The data are n points , and pi is the probability the model gives the i-th point.
- sigmoid function
- The function below. It maps every real number z to a number between 0 and 1. It is also called the logistic function. σ(0) = 0.5 and σ(−z) = 1 − σ(z).
- logistic regression
- A binary classification model. It writes the probability that the label is 1 as the sigmoid of a linear function of the input (the score z). Training means choosing the weights w and the bias b.
- odds, logit
- The odds of a probability p is p divided by 1 − p. The logit is the natural log of the odds. In logistic regression the logit equals the score z. So if only xj goes up by 1 and the other inputs stay the same, the odds are multiplied by . This factor is called the odds ratio.
- decision boundary
- Fix a threshold t (0 < t < 1) and predict 1 when p ≥ t, otherwise 0. The decision boundary is the set of points where the prediction changes. In logistic regression it is the set of points that satisfy the equation below, so when w ≠ 0 it is a hyperplane (a line when there are two inputs). For t = 0.5 the right side is 0.
- cross-entropy loss
- For each point, take minus the natural log of the probability given to the correct side, then average over the points. It is also called log loss or negative log-likelihood. Training looks for the w and b that make this value smallest.
1. Regression and classification: guessing a number or a side
Regression means guessing a number: a house price from its size, or tomorrow's temperature from today's. The answer can be any number. Fitting a straight line with least squares is the most basic kind of regression.
Classification means picking one group out of a fixed list: spam or not, click or no click. With two groups, we write one side as 1 and the other as 0. In the experiments on this page, the green circles are 1 and the orange squares are 0.
| Regression | Classification (two groups) | |
|---|---|---|
| Answer | A number (a price of 320,000) | 0 or 1 (not spam, spam) |
| What the model gives | That number | The probability of 1 (0.93) |
| How wrong (loss) | The difference, squared | Cross-entropy (section 5) |
| Basic model | Linear regression | Logistic regression |
The name logistic "regression" comes from the fact that the model predicts a number: a probability. Since that probability is then cut at a threshold (usually 0.5) to pick a side, it is used for classification.
2. Why go through a sigmoid instead of using the line as it is
First, multiply the input by a weight and add a bias to get a score. With one input, that is z = w × x + b. The score can be anything, like −100 or 57. But a probability has to be between 0 and 1. If you used the score as a probability, you would get nonsense "probabilities" like 1.7 or −0.4.
You could also fit a straight line to answers written as 0 and 1 with least squares, but that causes trouble. A point far from the boundary, which is already clearly on the right side, still counts as an error because the line gives it "more than 1". It pulls the line toward itself, and the boundary moves to the wrong place.
So the score goes into an S-shaped curve. That curve is the sigmoid function (also called the logistic function).
p = 1 ÷ (1 + e^(−z))
e is a number close to 2.718. When the score z is large, e^(−z) is close to 0, so p is close to 1. When z is a large negative number, e^(−z) is huge, so p is close to 0. When z is 0, e^0 = 1, so p = 1 ÷ 2 = 0.5. Whatever the score, p stays between 0 and 1 and never actually reaches 0 or 1.
| Score z | −5 | −2 | −1 | 0 | 1 | 2 | 5 |
|---|---|---|---|---|---|---|---|
| Probability p | 0.007 | 0.119 | 0.269 | 0.5 | 0.731 | 0.881 | 0.993 |
What w and b do. A large w makes the curve steep, so the model becomes sure as soon as x moves a little away from the middle. A w close to 0 makes the curve flat, so the model is unsure everywhere. A negative w flips the curve, so p goes down as x goes up. b slides the curve left and right. p = 0.5 where z = 0, which is at x = −b ÷ w.
What the score means. Solve the formula backward and you get z = ln(p ÷ (1 − p)). p ÷ (1 − p) is "chance it happens ÷ chance it does not", called the odds. So when the score z goes up by 1, the odds get multiplied by e (about 2.72). Books call this score the logit. The next section shows, one step at a time with pictures, how the sigmoid formula is built backward from this relation.
Try this. ① At the starting value x = 2, p = 0.881. Move x to −2 and p = 0.119. The two add up to 1, because the curve is symmetric around its middle point (0, 0.5). ② Even at x = 8, p shows as "> 0.999". It gets very close to 1 but never reaches it. ③ Put x at 1. Raising w to 3 gives p = 0.953, and lowering it to 0.3 gives 0.574. ④ With w = 1, raise b to 2. The curve slides 2 to the left and crosses 0.5 at x = −2. ⑤ Set w to 0 and the curve goes flat. p is the same for every x.
3. How the formula is built: p = 1 ÷ (1 + e^(−z))
Where does the sigmoid formula from section 2 come from? The score and the probability live on different ranges. Change the scale of the probability twice (first to odds, then to log-odds) until its range matches the score, set the two equal, and then solve backward.
Press "Next" to go one step at a time. The formula on top changes one piece at a time (a light orange background marks the new piece, dark orange marks what is still wrong), the picture changes, and the reason appears below. The top of the picture is a graph with the score z across, and its vertical scale changes at each step between probability, odds and log-odds. Light orange bands are values that are impossible on that scale. The bottom of the picture puts the same three scales side by side as number lines, and the line that matches the graph's vertical scale gets a shaded background. The five small dots are the scores −2 to 2 from the table in section 2 (orange for negative, green for 0 or more). The black dot is the one you move with the slider. From step ② on, dashed lines join the same dot across the lines.
- The ranges do not match:
p = z ?The scorez = w × x + bcan be anything from −∞ to ∞, but a probability p has to be between 0 and 1. Take the starting value of the first experiment, z = 2, as the probability and you get p = 2. On the graph, the straight line p = z breaks out past 0 and 1 (orange). Change its slope and it still breaks out somewhere, as long as it is straight. Why: you cannot join two numbers with different ranges with "=". One of them needs a new scale so the ranges match. - Odds instead of probability:
p ÷ (1 − p) = z ?The odds are "chance it happens ÷ chance it does not". p = 0.5 gives 1, p = 0.75 gives 0.75 ÷ 0.25 = 3, and p = 0.9 gives 9. As p gets close to 1 the odds grow without limit, so the top is now open all the way to ∞. But the bottom still stops at 0. The half with p below 0.5 (the two orange dots, 0.135 and 0.368) is squeezed between 0 and 1, and the half with p of 0.5 or more (the green dots 1, 2.718 and 7.389) spreads out from 1 to ∞. Why: the top is fixed, but odds can never be negative, so the places where z is negative (orange on the graph) still cannot be matched. - Take the log:
ln(p ÷ (1 − p)) = zln sends numbers below 1 to negative values and numbers above 1 to positive values. So the half squeezed between 0 and 1 spreads out over −∞ to 0, and 1 to ∞ becomes 0 to ∞. The range is now −∞ to ∞. The five dots land at −2, −1, 0, 1, 2, evenly spaced and symmetric around 0 (odds of 1 ÷ 9 and 9 become −2.197 and 2.197). We set this log-odds equal to the score z, and the line on the graph turns all blue. Why: the ranges now match, so "=" is allowed. This line is not proven. It is the assumption that logistic regression makes (see "Why log-odds?" below). - Solve backward, part 1:
p ÷ (1 − p) = e^zln and e^ undo each other (e^(ln a) = a). Put both sides under e^ and the ln on the left goes away. With z = 2 the odds are e^2 = 7.389. When z goes up by 1 to 3, the odds become e^3 = 20.086, which is e times as much (× 2.718). On the graph, the straight line turns into the rising curve e^z on the odds scale, and all of it stays above 0. Why: this is where "when the score z goes up by 1, the odds get multiplied by e" from section 2 comes from. The 1, 2.718 and 7.389 on the odds line are e^0, e^1 and e^2. - Solve backward, part 2:
p = e^z ÷ (1 + e^z)Multiply both sides by (1 − p):p = e^z − p × e^z. Move p × e^z to the left:p × (1 + e^z) = e^z. Divide both sides by (1 + e^z):p = e^z ÷ (1 + e^z). With z = 2 that is 7.389 ÷ 8.389 = 0.881, the same as the starting value of the first experiment. The graph's vertical scale goes back to probability, and the curve bends into an S that fits inside the 0 to 1 band. Why: e^z is always above 0, and the top (e^z) is exactly 1 less than the bottom (1 + e^z). So for any z, p is above 0 and below 1. - Tidy up:
p = 1 ÷ (1 + e^(−z))Divide the top and the bottom by e^z. The top becomes 1, and the bottom becomes 1 ÷ e^z + 1 = e^(−z) + 1 (because 1 ÷ e^z = e^(−z)). With z = 2 that is 1 ÷ (1 + 0.135) = 0.881, the same value. Why: e^z now appears only once, which is easier to read, and you can see right away that as z grows, e^(−z) (purple dashes) goes to 0 and p goes to 1. The two forms are the same formula, so the code on this page uses this form when z is 0 or more and the form from step ⑤ when z is negative. Either way the power of e is 0 or less, so the math never overflows.
| Score z | −2 | −1 | 0 | 1 | 2 |
|---|---|---|---|---|---|
| Probability p | 0.119 | 0.269 | 0.5 | 0.731 | 0.881 |
| Odds p ÷ (1 − p) = e^z | 0.135 | 0.368 | 1 | 2.718 | 7.389 |
| Log-odds ln(odds) | −2 | −1 | 0 | 1 | 2 |
Each time z goes up by 1, the log-odds go up by adding 1, and the odds go up by multiplying by e. The probability does neither, so its steps are uneven (0.15, 0.23, 0.23, 0.15). Instead it is symmetric around 0.5 (0.119 + 0.881 = 1, 0.269 + 0.731 = 1).
Why log-odds? It is not the only way to stretch 0 to 1 out to −∞ to ∞. For example, running the cumulative probability of the normal distribution backward gives the probit model. So step ③ is a choice, not a proof. Choosing the log-odds gives an easy meaning ("when the score goes up by 1, the odds get multiplied by e"), and together with cross-entropy it makes the slope in section 6 come out as the clean (p − answer) × input.
Try this. ① Press "Next" once and the odds line appears. The two orange dots are squeezed between 0 and 1 (0.135 and 0.368), and the three green dots spread out to 1, 2.718 and 7.389. ② Press it again and the five dots land evenly at −2 to 2 on the bottom line, and the orange disappears from the line on the graph. ③ At step ④, move the z slider from 2 to 3. The odds go from 7.389 to 20.086, e times as much. A value past the edge of the picture is marked with a triangle at the edge. ④ At the last step, z = −4 gives p = 0.018 and z = 4 gives 0.982. The two add up to 1. ⑤ At the first step, set z to 0.5. p = z lands inside 0 to 1 and looks fine, but move it to 1.3 and it is back outside the band (orange).
4. Splitting a plane: the decision boundary
With two inputs (x₁ across, x₂ up) there are two weights. The score is z = w₁ × x₁ + w₂ × x₂ + b and the probability is p = sigmoid(z). Every spot on the plane gets its own p.
The spots where p = 0.5 are the spots where z = 0, that is, where w₁ × x₁ + w₂ × x₂ + b = 0. That is a straight line. On one side z > 0, so p > 0.5 (called 1). On the other side p < 0.5 (called 0). This line is the decision boundary. With three inputs the boundary is a flat plane, and with more inputs it is a flat sheet one dimension lower. In every case it is straight and flat.
The arrow w = (w₁, w₂) is at a right angle to the boundary and points toward the side where p grows (because the score is a dot product). The farther you go from the boundary in the direction of w, the closer p gets to 1. The longer w is, the faster p changes near the boundary.
Train (gradient descent)
Fit it yourself
Drag the points, or pick a point and type its numbers. You can have 2 to 40 points. A point with a black outline is currently called wrong, and the dashed ring marks the picked point. The black arrow w is at a right angle to the boundary and points toward the side where p grows. The data is made up, built from a random number generator with a fixed seed, so you always get the same data. Real problems have tens to thousands of inputs and cannot be drawn on a plane, but the math is the same.
Try this. ① At the start w₁ = w₂ = b = 0, so p is 0.5 everywhere. There is no boundary, the loss is 0.693 and 10 of the 20 points are correct (p = 0.5 counts as "0.5 or more", so every point is called green). ② Under "Fit it yourself", raise only w₁ to 1. The vertical line x₁ = 0 becomes the boundary, all 20 points are correct, and the loss is 0.262. Raise w₂ to 1 too and the loss drops to 0.078. The count of correct points is the same, but the loss also looks at how sure each correct answer was. ③ Put w₂ back to 0 and set w₁ to −1. The boundary is in the same place but the sides are flipped: all 20 points are wrong and the loss is 1.652.
5. How wrong is it: cross-entropy loss
To train, we need one number that says how wrong the model is right now. Logistic regression scores each point like this and takes the average.
if the answer is 1: −ln(p), if the answer is 0: −ln(1 − p)
ln is the natural log (base e). Both formulas are −ln of "the probability given to the right answer". If that probability is close to 1, the loss is close to 0. If it is close to 0, the loss grows without limit. In other words, being sure and wrong costs a lot.
| Probability given to the right answer | 0.99 | 0.9 | 0.5 | 0.1 | 0.01 |
|---|---|---|---|---|---|
| Loss −ln(probability) | 0.01 | 0.105 | 0.693 | 2.303 | 4.605 |
This is cross-entropy. If you compute the cross-entropy between the right answer (100% on 1) and the prediction (p on 1), you get exactly the formula above. You can read it as the average "surprise" the model feels when it sees the answer. The starting loss of 0.693 in the experiment is ln 2. It is the loss of a model that knows nothing and gives every point 0.5. With a base-2 log it would be 1 bit.
Making this loss small is the same as making the chance of seeing the right answers (the likelihood) as large as possible. Making a product of probabilities large is the same as making the sum of their logs large, and this loss is that sum with a minus sign, averaged. That is why it is also called the negative log-likelihood.
For logistic regression this loss is bowl-shaped (convex) in the weights. There are no shallow side valleys to get stuck in, so with a sensible step size you go down to the lowest point from any start. But when the two groups split cleanly along a straight line, there is no bottom. Bigger weights keep pushing the loss closer to 0 (section 12).
6. Training: the slope is (prediction − answer) × input
Training means changing w₁, w₂ and b so the loss goes down. The method is gradient descent: compute the slope of the loss and take a step the other way.
slope for w₁ = average[ (p − answer) × x₁ ]slope for w₂ = average[ (p − answer) × x₂ ]slope for b = average[ (p − answer) ]one step: weight ← weight − step size × slope
It is a clean shape. For each point it is just how wrong it is (p − answer) times the size of the input. Points that are already right (p close to the answer) barely change anything, and points that are badly wrong change a lot. When you fit a least squares line with gradient descent, the slope also has the shape (prediction − answer) × input, so the two look the same.
Why it comes out so clean. Taking the slope of the loss with respect to a weight means multiplying three pieces (the chain rule). ① How the loss changes with p is (p − answer) ÷ (p × (1 − p)). ② The slope of the sigmoid, how p changes with z, is p × (1 − p). ③ How z changes with w₁ is x₁. Multiply them and p × (1 − p) cancels out top and bottom, leaving only (p − answer) × x₁. That is why cross-entropy and the sigmoid make such a good pair.
Worked example: one step with two points
Point A = (2, 1) is green (answer 1). Point B = (−1, −2) is orange (answer 0). The starting weights are w₁ = w₂ = b = 0, and the step size is 1.
- Scores and probabilities. All weights are 0, so z_A = z_B = 0 and p_A = p_B = 0.5.
- Loss. A: −ln(0.5) = 0.693. B: −ln(1 − 0.5) = 0.693. Average 0.693.
- How wrong (p − answer). A: 0.5 − 1 = −0.5. B: 0.5 − 0 = 0.5.
- Slopes. For w₁: ((−0.5) × 2 + 0.5 × (−1)) ÷ 2 = (−1 − 0.5) ÷ 2 = −0.75. For w₂: ((−0.5) × 1 + 0.5 × (−2)) ÷ 2 = −0.75. For b: (−0.5 + 0.5) ÷ 2 = 0.
- One step. w₁ = 0 − 1 × (−0.75) = 0.75, w₂ = 0.75, b = 0.
- Check. z_A = 0.75 × 2 + 0.75 × 1 = 2.25 → p_A = 0.905. z_B = 0.75 × (−1) + 0.75 × (−2) = −2.25 → p_B = 0.095. The loss for both A and B is −ln(0.905) = 0.1, so the average is 0.1. One step took the loss from 0.693 down to 0.1. The boundary is
0.75 × x₁ + 0.75 × x₂ = 0, which is the line x₂ = −x₁.
Try this. ① In the experiment, press "Worked example (two points)" (step size 1) and then "One step". You get w₁ = 0.75, w₂ = 0.75, b = 0 and a loss of 0.1, just like above. ② Press "Clean split" and then "One step" once. A boundary appears, the loss drops from 0.693 to 0.144, and all 20 points are correct. ③ Then press "Auto". It stops around step 830, when the slope is almost 0. The loss is 0.001, w₁ and w₂ are above 3, and the background color gets strong right up to the boundary. ④ Press "A little mixed" and then "Auto". It stops after 42 steps with a loss of 0.422 and 19 of 24 points correct (79%). No straight line can get every mixed point right.
7. The threshold does not have to be 0.5
What logistic regression gives you is a probability. The rule "call it 1 if p is at least this much" uses a threshold, and the usual value is 0.5. Changing the threshold slides the boundary sideways without turning it, because the boundary becomes w₁ × x₁ + w₂ × x₂ + b = ln(t ÷ (1 − t)) and only the right side changes (t is the threshold).
There are two ways to be wrong.
| Name | Meaning | Lower threshold | Higher threshold |
|---|---|---|---|
| Miss | Really 1 but called 0 (sick, but told "fine") | Fewer | More |
| False alarm | Really 0 but called 1 (real mail called "spam") | More | Fewer |
No threshold lowers both at once. Pick it by which mistake costs more. A test for a disease should not miss, so it uses a low threshold. A spam filter should not throw away important mail, so it uses a high threshold. "Of the points called 1, how many were right" is called precision. "Of the real 1s, how many were caught" is called recall. Lowering the threshold raises recall and usually lowers precision.
Try this. Press "A little mixed", let "Auto" finish, then move the threshold slider. ① At 0.5 there are 3 misses and 2 false alarms. ② At 0.1 there are 0 misses and 9 false alarms. No green point is missed, but 9 of the 12 orange points are called green. ③ At 0.9 there are 8 misses and 1 false alarm. ④ At 0.3 there is 1 miss and 2 false alarms, so 88% are correct, which is more than at 0.5 (79%). Training only makes the loss small. It does not directly push up the share of correct answers, so this can happen.
8. What a straight line cannot split
The boundary of logistic regression is always a straight line. So it cannot split data like "Center and ring", where one group surrounds the other. Wherever you draw the line, orange ring points are left on both sides.
Here training heads toward "everything is orange". It gives every point a chance of being green of about 0.29 to 0.43. Their average, 0.365, is almost the same as the share of green points in the data (8 of 22, 0.364). That is because the slope for b is 0 exactly when "average of p = average of the answers". The shape tells it nothing useful, so it only learns which group is more common.
There are two ways out.
- Make a new input. Add the squared distance from the origin,
x₁² + x₂², as an input. In this data every center point has a value of 4.45 or less and every ring point has 9.05 or more, so one threshold splits them. The catch is that a person has to figure out which input to make. - Use a neural network. Several logistic regressions (neurons) each draw their own line, and mixing their results again gives a curved boundary. Training finds the useful inputs by itself. This continues on the neural network page.
Try this. Press "Center and ring" and then "Auto". It stops after 19 steps: loss 0.652, 14 of 22 correct (64%), 8 misses, 0 false alarms. It missed all 8 green points and only got the orange ones. Even if you move w₁, w₂ and b by hand, no straight line gets more than 15 of 22.
9. Three or more groups: softmax
With three or more groups, like cat, dog and bird, each group gets its own weights and its own score. The function that turns those scores into probabilities is softmax.
probability of group k = e^(z_k) ÷ (e^(z_1) + e^(z_2) + … + e^(z_K))
Putting each score in e^ makes them all positive, and dividing by the total makes them add up to 1. For example, scores (2, 1, 0) give e^2 = 7.389, e^1 = 2.718, e^0 = 1, a total of 11.107, and probabilities (0.665, 0.245, 0.09). The loss is the same cross-entropy: −ln of the probability given to the right group.
With two groups, softmax is the same as the sigmoid. Since e^(z₁) ÷ (e^(z₁) + e^(z₀)) = 1 ÷ (1 + e^(−(z₁ − z₀))), it is the sigmoid of the difference between the two scores. A language model choosing the next word also turns one score per word into probabilities with softmax. How one word is then drawn from those probabilities is on the sampling page.
10. One neuron in a neural network is a logistic regression
A single neuron in a neural network multiplies its inputs by weights, adds them up with a bias, and puts the result through an activation function. If that function is the sigmoid, one neuron is exactly a logistic regression. It is trained the same way too: compute the slope of the loss and fix the weights with gradient descent.
A neural network stacks many of these neurons in layers. Inner layers often use a function that is cheaper to compute, like ReLU, instead of the sigmoid. The last layer often uses a sigmoid for two groups and softmax for three or more. So even a large classification model does exactly what this page shows at its very end: score, then probability, then cross-entropy. The story continues on the neural network page.
11. Reading it like a statistician: the coefficient is an odds ratio
So far this page has looked at logistic regression as a way to guess. In statistics (medical and public health research) the same model is used for a different question: "if this factor is present, how much does the chance of the outcome change?" So the focus moves to how to read the fitted coefficients. Statistics books write the bias b as b₀ and the weight w as b₁ (also β₀ and β₁), and call them regression coefficients. The formula is the same.
Odds and log-odds
In section 3 we set the log-odds equal to the score and solved backward to get the sigmoid. Statistics books start from that "set equal" line.
odds = p ÷ (1 − p)ln(odds) = b₀ + b₁ × x
The assumption is that ln of "chance it happens ÷ chance it does not" (the odds), which is the log-odds or logit, is a straight line in x. The probability p itself is not a straight line in x but an S-shaped curve. When x = 0 only b₀ is left on the right, so b₀ is "the log-odds when x = 0".
Reading the coefficient: e^b₁ is the odds ratio
When x goes up by 1, the right side goes up by b₁. So the log-odds go up by adding b₁. Undoing the ln turns adding into multiplying (section 3, step ④), so the odds get multiplied by e^b₁.
(odds at x + 1) ÷ (odds at x) = e^(b₀ + b₁ × (x + 1)) ÷ e^(b₀ + b₁ × x) = e^b₁
This ratio of two odds, e^b₁, is called the odds ratio. It is the same wherever x is, so one coefficient reads as one number. Above 1 means the odds go up, exactly 1 means no change (b₁ = 0, no relation), and below 1 means they go down (a negative b₁).
Worked example. Say a model with x = 1 for smokers and x = 0 for non-smokers gives b₁ = 0.69 (a made-up number). e^0.69 = 1.99, about 2. You read it as "smokers have about 2 times the odds of getting the disease compared with non-smokers". For a value that runs on, like age, it reads "the odds get multiplied by e^b₁ for each extra year", and by e^(10 × b₁) for 10 extra years.
The gray bar is the probability at x = 0 and the blue bar the probability at x = 1. The black dashed line marks where the x = 0 probability is. The numbers on the right are the probability and the odds for each row, and the purple line at the bottom is the odds ratio and the change in probability. Think of x as something that is either absent (0) or present (1), like smoking. There is no data here: b₀ is computed from p₀ (b₀ = ln(p₀ ÷ (1 − p₀))).
Try this. ① At the starting values (p₀ = 0.1, b₁ = 0.69) the probability at x = 1 is 0.181. The odds go from 0.111 to 0.222, an odds ratio of 1.99. The probability goes up by 0.081, × 1.81. ② Keep b₁ and move p₀ to 0.5. The odds ratio stays at 1.99, but the probability goes up to 0.666, a change of 0.166 (× 1.33). At 0.9 it only goes up to 0.947, a change of 0.047. ③ Lower p₀ to 0.01. The probability is multiplied by 1.97, almost the same as the odds ratio of 1.99. Only for rare outcomes can you read the odds ratio as "times the probability". ④ Set b₁ to 0: the odds ratio is 1 and the two bars are the same. At −0.69 the odds ratio is 0.5 and the probability drops from 0.1 to 0.053.
An odds ratio is not "times the probability"
Reading an odds ratio of 2 as "twice the probability" is wrong. How much the probability goes up when the odds double depends on where it starts. From 10% it goes to 18% (× 1.82), from 50% to 67% (× 1.33), and from 90% to 95% (× 1.05). From 1% it goes to 1.98%, almost twice.
For a rare outcome, 1 − p is close to 1, so the odds and the probability are almost the same. Only then is the odds ratio close to the ratio of the probabilities (the relative risk). The more common the outcome, the more the two drift apart, and the odds ratio ends up farther from 1 than the relative risk. The odds ratio page puts the two side by side.
Several variables: the adjusted odds ratio
ln(odds) = b₀ + b₁ × smoking + b₂ × age
With several variables, e^b₁ becomes "the odds ratio between smokers and non-smokers with age held the same" (the adjusted odds ratio, adjusted OR). It can differ from the odds ratio you get with smoking alone (the crude OR). That happens when age is tied to both smoking and the disease. How to deal with a variable that sneaks in like this is on the confounding page. A variable you did not put in the model is not adjusted for. The plane experiment in section 4 is the same model with two inputs, so e^w₁ there is the odds ratio for x₁ with x₂ held the same.
How the coefficients are found: maximum likelihood
Statistics software finds the coefficients as "the values that make the likelihood largest". Assume some b₀ and b₁ are right, compute the chance of getting exactly the data you have (who is 1 and who is 0), and pick the b₀ and b₁ that make that chance largest (maximum likelihood estimation, MLE). As section 5 showed, the log of that chance with a minus sign, averaged, is the cross-entropy loss. So making the likelihood largest is the same job as making the loss smallest in sections 5 and 6, and without regularization (the penalty in section 12) the answer, the coefficients, is the same too. Only the method used to get there may not be gradient descent. When the two groups split cleanly along a straight line, there is no largest point, the coefficients grow forever (section 12), and the odds ratio cannot be read.
Confidence intervals and tests
With slightly different data, b₁ would have come out slightly different. The size of that wobble is the standard error, and statistics software prints it next to each coefficient. The 95% confidence interval of the odds ratio is built on the b₁ side first, then put through e^. The 1.96 is there because 95% of a normal distribution lies within 1.96 standard deviations of the mean.
e^(b₁ − 1.96 × standard error) to e^(b₁ + 1.96 × standard error), or in short e^(b₁ ± 1.96 × standard error)
Example: with b₁ = 0.69 and a standard error of 0.3 you get 0.69 ± 0.588, that is 0.102 to 1.278. Put through e^, the odds ratio's interval is 1.11 to 3.59. It does not contain 1, so you say the odds ratio differs from 1 (there is a relation). With a standard error of 0.4 the interval is 0.91 to 4.37. It contains 1, so it is hard to say there is a difference. The same call can be made with b₁ ÷ standard error: 0.69 ÷ 0.3 = 2.3 is above 1.96, and 0.69 ÷ 0.4 = 1.725 is not. This is the Wald test (above 1.96 means b₁ = 0 is rejected at the 5% level). The interval is not centered on 1.99 but stretches out to the right, because an even interval on the b₁ side was put through e^.
# See the coefficients, odds ratios and their 95% confidence intervals with Python (statsmodels)
import numpy as np
import statsmodels.formula.api as smf
# data: a table (pandas DataFrame) with columns y (0 or 1), x and age
model = smf.logit("y ~ x + age", data).fit()
np.exp(model.params) # odds ratios. The one for x is the odds ratio with age held the same (adjusted OR)
np.exp(model.conf_int()) # 95% confidence intervals of the odds ratios
# Unlike scikit-learn's default, there is no regularization, so you get the maximum likelihood coefficients as they are
12. Properties worth knowing
| Property | Meaning | Where to see it |
|---|---|---|
| p is always between 0 and 1, and 0.5 when z = 0 | Any score becomes a probability, and it never reaches 0 or 1 | Experiment 1 shows "> 0.999" even at x = 8 |
sigmoid(−z) = 1 − sigmoid(z) | The curve is symmetric around (0, 0.5). The chance of 1 and the chance of 0 have the same shape | 0.881 at x = 2, 0.119 at x = −2 |
| The boundary is a straight line (a flat sheet) | w₁x₁ + w₂x₂ + b = 0. w is at a right angle to it | The black line and the arrow w in the experiment in section 4 |
| Slope = average[(p − answer) × input] | Fix more where the answer is more wrong and the input is bigger | The worked example in section 6 |
| With a clean split, the weights grow forever | The loss only keeps getting closer to 0. In practice a penalty that keeps weights small (regularization) stops this | "Clean split", then "Auto" |
Where it is used
- Spam filters. Inputs are how many times each word appears in an email, and the output is the chance it is spam. A high threshold keeps real mail from being thrown away.
- Click prediction. It predicts the chance that a person clicks an ad or a recommended item. The probability itself is used to rank items or to compute expected values, so it matters more than a plain 0 or 1.
- Helping with medical diagnosis. Age, blood pressure and test results go in, and the chance of a disease comes out. The weights show how much each number raises the chance, so it is a common baseline where results need explaining. Missing a case is dangerous, so the threshold is set low.
- A first baseline. It is fast and simple, so people run it first as a "we should at least get this much" baseline before building a complex model.
# Train on the two points of the worked example with Python (scikit-learn)
from sklearn.linear_model import LogisticRegression
X = [[2, 1], [-1, -2]] # point A, point B
y = [1, 0] # green = 1, orange = 0
model = LogisticRegression().fit(X, y)
model.predict_proba([[0.5, 0.5]]) # [[chance of 0, chance of 1]]
# Regularization (a penalty that keeps weights small) is on by default, so the numbers differ a little from this page
Frequently asked questions
Is logistic regression regression or classification?
It predicts a probability between 0 and 1, which is a single number, so it got the name regression. That probability is then cut at a threshold to decide which side a point is on, so in practice it is used for classification.
Why use cross-entropy instead of squared error?
With squared error after a sigmoid, a point that is confidently and badly wrong gets a slope close to 0, so it barely gets fixed, and the loss is no longer bowl-shaped. With cross-entropy the slope is simply (prediction − answer) × input, and the more wrong a point is, the bigger the fix.
Is the output of the sigmoid really a probability?
It is between 0 and 1 and training pushes it to behave like a probability, but you cannot always trust it. For example, when the two groups split cleanly along a line, more training pushes the outputs too far toward 0 and 1. If you need the probability itself, check it on data you held back.
Does the threshold have to be 0.5?
No. A lower threshold gives fewer misses and more false alarms, and a higher one does the opposite. Pick it by which mistake costs more. A medical test that must not miss a disease uses a low threshold. A spam filter that must not throw away real mail uses a high one.
What if there are three or more groups?
Compute one score per group, then use softmax to turn the scores into probabilities that add up to 1. With exactly two groups, softmax works out to the same thing as the sigmoid.
Words
| Plain words used here | What books call it |
|---|---|
| Guessing which side | Classification. With two groups, binary classification |
| Guessing a number | Regression |
| S-shaped curve | Sigmoid function, logistic function |
| Score z | Logit, log-odds |
| Chance it happens ÷ chance it does not | Odds |
| How many times the odds get multiplied when x goes up by 1 (e^b₁) | Odds ratio (OR) |
| Odds ratio with the other variables held the same | Adjusted odds ratio (adjusted OR). The one from a single variable is the crude odds ratio (crude OR) |
| Finding the coefficients that make the data most likely | Maximum likelihood estimation (MLE) |
| Comparing coefficient ÷ standard error with 1.96 | Wald test |
| ln and e^ (a pair that undo each other) | Natural logarithm and the exponential function, inverse functions of each other |
| Weight, bias | Weight, bias (also called the intercept) |
| Dividing line | Decision boundary |
| Can be split by one straight line | Linearly separable |
| Threshold | Threshold, cutoff |
| Miss | False negative (FN) |
| False alarm | False positive (FP) |
| Share of correct answers | Accuracy |
| Right among those called 1 / caught among the real 1s | Precision / recall |
| Loss (cross-entropy) | Cross-entropy loss, log loss, negative log-likelihood |
| Step size | Learning rate |
| Penalty that keeps weights small | Regularization |
| Turning scores into probabilities for three or more groups | Softmax, multinomial logistic regression |
| The function a neuron applies at the end | Activation function |
Sources
- D. R. Cox, The Regression Analysis of Binary Sequences, Journal of the Royal Statistical Society Series B 20(2), 215–232. A classic paper on using the logistic model for data made of 0s and 1s.
- Tengyu Ma, Andrew Ng, CS229 Lecture Notes, chapter 2, Classification and logistic regression (2.1 logistic regression, 2.3 multi-class classification and softmax).
- Google Machine Learning Crash Course, Logistic regression, Thresholds and the confusion matrix.
- scikit-learn LogisticRegression documentation.
- statsmodels Logit documentation.