Linear regression predicts an amount. Many questions want a yes or no instead: is this email spam, is this sign an arrow, will this hiker need a rescue. A model for those should answer with a chance between 0 and 1, and a straight line can't: it runs off below 0 and above 1. Logistic regression keeps the line as a score and squeezes the score through the sigmoid, an S-shaped curve that turns any number into a chance. It is trained by maximum likelihood (lesson 100), and its loss, the log loss, has a slope so simple, p − y, that the same expression returns in nearly every classifier and language model. A single neuron with a sigmoid is exactly this model, so this lesson is also the first complete neuron of the section: score, squeeze, loss, slope, step.
What you'll be able to do
Turn a line's score into a chance with the sigmoid, σ(z) = 1/(1 + e⁻ᶻ), and read it off the S-curve
Measure a yes-or-no prediction with the log loss, and see why it punishes confident mistakes
Derive and use the loss's slope with respect to the score, p − y, in a short training loop
Train a two-feature sign detector, read it as one neuron, choose a threshold, and get the same loss and slopes from PyTorch's nn.BCEWithLogitsLoss
Quick check
Have a guess before you start. A model should give the chance a sign is an arrow. Why not use a straight line, ŷ = wx + b, as the chance?
Lines are too slow to compute
Chances must be whole numbers
A line runs below 0 and above 1
A line can't have a slope
Show the answer
A line runs below 0 and above 1
Far enough along x, any sloped line passes 1 and, the other way, drops below 0. A chance must stay between them.
The math: score, squeeze, loss
Purpose. Predict the chance of a yes, and measure how good that prediction was.
The score. As in linear regression, each example gets a score z = w·x + b: a weighted sum of its features plus a bias. A high score means "probably yes", a low one "probably no", but it can be any number.
The squeeze. The sigmoid turns the score into a chance:
z
−4
−2
0
2
4
σ(z)
0.018
0.119
0.5
0.881
0.982
A score of 0 gives 0.5, a coin toss. Big positive scores approach 1 and big negative ones approach 0, never reaching either. The decision boundary is where z = 0: on one side the model leans yes, on the other no.
Quick check
From lesson 100: a model gave the right answer probability p. What is its negative log-likelihood for that one answer?
1 − p
log p
−log p
p²
Show the answer
−log p
The NLL of one observation is −log of the probability given to what happened. The log loss below is exactly this.
The loss. If the true answer is yes (y = 1), the loss is −log p; if it's no (y = 0), −log(1 − p). So a prediction of 0.9 for a real yes costs 0.105, a shrug of 0.5 costs 0.693, and a confident 0.01 costs 4.605: the loss punishes confident mistakes far more than timid ones.
The picture. Step through one example, from features to slope. The drawing is the sigmoid's S-curve, the chance standing over every score. Watch the score land on the floor, climb to the curve to become a chance, meet the right answer (the ring), and last the gap between them: that gap is the slope.
Try it now
Then set right answer to 0 and press Use these numbers: the same chance 0.6225 now costs 0.9741, the ring drops to the floor, and the slope turns positive.
Symbols and formula.
σ(z)=1+e−z1L=−[ylogp+(1−y)log(1−p)]∂z∂L=p−y
In plain words: squeeze the score into a chance; charge −log of the chance given to what really happened; the push on the score is just "predicted minus true".
Where p − y comes from. The chain rule of lesson 74 multiplies two links. The loss's slope with respect to p is −y/p + (1 − y)/(1 − p), and the sigmoid's slope is p(1 − p). Multiplied, almost everything cancels: −y(1 − p) + (1 − y)p = p − y. When the prediction matches the truth the push is 0; the further off, the harder the push. The slope for each weight is then (p − y)·x, lesson 81's "multiply along the path".
Quick check
What is σ(0)?
0
e
1
0.5
Show the answer
0.5
1 ÷ (1 + e⁰) = 1 ÷ 2 = 0.5: a score of 0 sits exactly on the decision boundary.
In your own words
In your own words: why does the log loss punish a confident wrong answer so much more than an unsure one?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: sigmoid, loss, slope, loop
Purpose. Write the three pieces, then train the score's w and b by gradient descent.
import numpy as np
defsigmoid(z):
return1 / (1 + np.exp(-z))
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
y = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0])
w, b = 0.0, 0.0for step inrange(5000):
p = sigmoid(w * x + b)
w = w - 0.1 * np.mean((p - y) * x)
b = b - 0.1 * np.mean(p - y)
p = sigmoid(w * x + b)
print(round(w, 3), round(b, 3), round(-b / w, 2))
print(p.round(2).tolist())
It runs right here in your browser, with nothing to install.
Eight readings, x from 1 to 8, with the answer mostly no below 4.5 and mostly yes above. Training settles at w = 1.271 and b = −5.714, so the boundary, where z = 0, sits at x = 5.714 ÷ 1.271 = 4.5. Two points are on the "wrong" side, x = 4 (a yes) and x = 5 (a no): no single boundary can separate them, so the model gives them middling chances, 0.35 and 0.65, rather than confident wrong ones.
Code flow. Here is the same loop on four points, three passes, with every piece on its own line: the score, the squeeze, the loss, the slope p − y, and the two updates. Step through and watch the boxes: p is one chance per point, and dz is how far each one is from its answer.
A named mistake: logging 0. If a prediction reaches exactly 0 or 1, np.log(0) returns minus infinity and the loss becomes infinite or NaN. Floats get there sooner than you'd think: σ(40) rounds to exactly 1.0, so 1 − p is 0.
import numpy as np
p = 1 / (1 + np.exp(-40.0))
print(p == 1.0, 1 - p)
Libraries guard against it by clipping p into [ε, 1 − ε] before the log, or by computing the loss straight from the score in a stable form, as PyTorch does in the AI part. When a training loss suddenly prints nan, a log of 0 is the first suspect.
Worked example
Worked example: the loss for good and bad predictions
Compute the log loss for five predictions of a real yes, from confident and right to confident and wrong.
import numpy as np
p = np.array([0.99, 0.9, 0.5, 0.1, 0.01])
loss = -np.log(p)
print(loss.round(3).tolist())
print(round(float(loss.mean()), 3))
In the lesson you can change this and run it.
The losses run 0.010, 0.105, 0.693, 2.303 and 4.605. Going from 0.99 to 0.9 costs a tenth of a point; going from 0.1 to 0.01 costs 2.3 points. Averaged, the one confident mistake supplies more than half the total. That lopsidedness is deliberate: it's what drives a classifier away from confident errors first, and it's why a model that says 0.5 for everything still beats one that is sometimes sure and wrong.
Quick check
What does this print?
import numpy as np
z = np.array([-4.0, -2.0, 0.0, 2.0, 4.0])
print((1 / (1 + np.exp(-z))).round(3).tolist())
[-4.0, -2.0, 0.0, 2.0, 4.0]
[0.018, 0.119, 0.5, 0.881, 0.982]
[0.0, 0.0, 0.5, 1.0, 1.0]
[0.982, 0.881, 0.5, 0.119, 0.018]
Show the answer
[0.018, 0.119, 0.5, 0.881, 0.982]
The math part's table: below a half for negative scores, a half at 0, above a half for positive ones, and σ(−z) = 1 − σ(z).
Draw it. The trained model from the first cell, w = 1.271 and b = −5.714, as a curve over x, with the eight readings as dots. The third argument, "o", tells plt.plot to draw dots instead of a line:
The math part's S-curve again, stretched and slid along x by the weight and the bias.
Quick check
Read the plot. Where does the curve cross a chance of 0.5?
At x = 4.5, between the two mixed points
At x = 5.714, the bias
At x = 0, where the score is 0
At x = 1.271, the weight
Show the answer
At x = 4.5, between the two mixed points
The chance is 0.5 where the score 1.271x − 5.714 is 0: x = 5.714 ÷ 1.271 = 4.5, the boundary the first cell printed. It sits between x = 4 (a yes) and x = 5 (a no).
Drill
Train the boundary
Fill in the two update lines of this training loop with the slopes (p − y)·x and (p − y), averaged, and learning rate 0.1. Then set boundary to −b/w, rounded to 2 places, and acc to the share of points the model gets right at threshold 0.5.
import numpy as np
defsigmoid(z):
return1 / (1 + np.exp(-z))
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
y = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0])
w, b = 0.0, 0.0for step inrange(5000):
p = sigmoid(w * x + b)
w = w
b = b
boundary = 0
acc = 0print(boundary, acc)
In the lesson, your code is checked as you write it.
In your own words
The trained model gives x = 4 and x = 5 chances of 0.35 and 0.65 instead of confident answers. Why is that the right behavior?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: a neuron, and a threshold
Purpose. See logistic regression as one neuron, and choose where to turn its chance into a decision.
A neuron. A neuron with a sigmoid computes a weighted sum of its inputs plus a bias, then squeezes it: exactly z = w·x + b and p = σ(z). Trained with the log loss, it is logistic regression. A network stacks many of them, and its last layer for a yes-or-no question is still this neuron. The slope p − y is where backpropagation (lesson 81) starts.
Is this sign an arrow? The trail club's sign camera describes each sign by two numbers from 0 to 1: how pointed its tip is and how wide it is. Arrows are pointed and narrow; tent-site boards are blunt and wide. Ten signs, five of each, trained like the loop above, now with two weights, so the score is one dot product per sign, X @ w + b, and each weight's slope is X.T @ (p - y) averaged:
import numpy as np
X = np.array([[0.8, 0.1], [0.0, 0.7], [0.5, 0.3], [0.5, 0.6], [0.9, 0.1],
[0.6, 0.6], [0.4, 0.3], [0.1, 0.9], [0.9, 0.2], [0.0, 0.6]])
y = np.array([1, 0, 0, 1, 1, 0, 1, 0, 1, 0])
w, b = np.zeros(2), 0.0for step inrange(2000):
p = 1 / (1 + np.exp(-(X @ w + b)))
w = w - 1.0 * X.T @ (p - y) / len(y)
b = b - 1.0 * np.mean(p - y)
p = 1 / (1 + np.exp(-(X @ w + b)))
loss = np.mean(-(y * np.log(p) + (1 - y) * np.log(1 - p)))
print(w.round(2).tolist(), round(b, 2), round(loss, 3))
print(p.round(2).tolist())
Pointed counts for an arrow (w₁ = 4.77) and wide counts against (w₂ = −4.42), with a bias of −0.37 and a mean loss of 0.359. The chances run from 0.97 for a sharp narrow arrow down to 0.02 for a wide blunt board. Two signs are hard: sign 3, a narrow board with a slanted end, gets 0.67, and sign 4, a wide arrow, only 0.35.
Choosing a threshold. To act, a threshold turns each chance into a yes or a no. At 0.5, sign 3 (0.67) is called an arrow though it's a board, and sign 4 (0.35) is called a board though it's an arrow: 8 of 10 right, with one mistake of each kind. Move the threshold and the count can stay the same while the mistakes change places. The threshold doesn't change what the model knows; it chooses which mistake is cheaper: a missed arrow, or a false one. For a rescue alert you'd lower it; for a spam filter that deletes mail, you'd raise it. Lesson 103 names the two kinds of mistake and scores each.
Quick check
What does this print?
import numpy as np
p = np.array([0.9, 0.6, 0.4, 0.2])
print((p >= 0.5).astype(int).tolist(), (p >= 0.3).astype(int).tolist())
[1, 1, 1, 0] [1, 1, 0, 0]
[1, 1, 0, 0] [1, 1, 1, 0]
[1, 1, 0, 0] [1, 1, 0, 0]
[0, 0, 1, 1] [0, 1, 1, 1]
Show the answer
[1, 1, 0, 0] [1, 1, 1, 0]
Lowering the threshold from 0.5 to 0.3 turns the 0.4 into a yes: more yes calls, the same chances.
Quick check
Raising a classifier's threshold from 0.5 to 0.9 usually does what?
Nothing, since the chances stay the same
Fewer yes calls: fewer false alarms, more misses
More yes calls
Changes the model's weights
Show the answer
Fewer yes calls: fewer false alarms, more misses
Only the surest cases pass 0.9, so it says yes less often: its yes calls are more often right (precision, from lesson 90), but it finds fewer of the real cases (recall).
In PyTorch. PyTorch's loss for this model is nn.BCEWithLogitsLoss: binary cross-entropy, the log loss, taken straight from the score (the logit), with the squeeze done inside in a form that never logs a 0. The cell loads the weights the NumPy cell printed. requires_grad_() asks PyTorch to track the scores, and backward() finds the loss's slope for each sign's score. The loss is a mean over 10 signs, so each slope arrives divided by 10:
import torch
import torch.nn as nn
X = torch.tensor([[0.8, 0.1], [0.0, 0.7], [0.5, 0.3], [0.5, 0.6], [0.9, 0.1],
[0.6, 0.6], [0.4, 0.3], [0.1, 0.9], [0.9, 0.2], [0.0, 0.6]])
y = torch.tensor([1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0])
z = X @ torch.tensor([4.77, -4.42]) - 0.37
z.requires_grad_()
loss = nn.BCEWithLogitsLoss()(z, y)
loss.backward()
print(round(loss.item(), 3))
slope = z.grad * len(y)
print(torch.allclose(slope, torch.sigmoid(z) - y))
print(round(slope[2].item(), 2), round(slope[3].item(), 2))
The loss is 0.359, the mean loss the NumPy cell printed. True says every slope is exactly p − y, the formula from the math part. The biggest pushes go to the two hard signs: +0.67 pushes board 3's score down, −0.65 pushes arrow 4's up.
Drill
Mistakes at three thresholds
The detector's ten chances are in p and the real answers in truth. For thresholds 0.3, 0.5 and 0.7, in that order, set accs to the accuracy, misses to the number of real arrows called no, and false_alarms to the number of boards called yes, each a list of three.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write