Lesson 2.1 — Classification & Loss Functions
From continuous values to class decisions
Regression
Predicts continuous quantities such as next-step position. Outputs can be any real number, and Mean Squared Error (MSE) measures the distance between prediction and target.
Classification
Predicts discrete categories such as Normal / Warning / Fault. Three mutually exclusive states correspond to three scores whose probabilities sum to 1; the predicted class is the index of the highest score.
Starting from the MLP in Lesson 1.8, only the final layer output dimension and the loss function
change. Do not treat class indices 0, 1, 2 as regression targets with physical
distance. Asymmetric misclassification costs are a separate modeling decision.
Logits are scores, not probabilities
In multi-class classification, logits can be arbitrarily positive or negative. Class indices are
integers (torch.long of shape (B,)), whereas one-hot vectors are
length-K indicator vectors of shape (B, K). PyTorch
CrossEntropyLoss also supports valid floating-point class probability targets of the
same shape; never pass integer one-hot tensors as class indices.
01 · Logits & Probability Inspector
Exponentiate → normalize → compete
Mathematically, every Softmax probability is strictly positive; under finite floating-point precision, extremely small probabilities can underflow to zero.
02 · Softmax Competition Animation
Outline = zero offset · Solid dot = current offset · Dashed line = zero
Measure how much probability the model assigns to the target
Suppose the observed state is Normal. Each bar shows a model's probabilities for the same observation. The widest segment determines the predicted label. The dark segment is the probability assigned to the observed label.

All three predictions count as correct. Moving from A to B improves the loss because the model assigns more probability to what happened. Moving from B to C redistributes probability between the two other classes. The loss for this observation stays exactly the same.
For logits , let be their softmax and the observed class. With a hard label the per-example loss is . Halving adds to the loss, regardless of where you started. The natural logarithm gives the result in nats.
A hard target puts all the weight on one class. A soft target can weight several classes, so redistributing probability between them can change the loss. Even with a hard target, every logit affects through the softmax denominator.
Keep the scores fixed and change which class was observed
03 · Cross Entropy Explorer
Likelihood, log-softmax and the stable loss
Computing exp(z) directly overflows easily; even a stabilized Softmax can fail when
log(p) encounters an underflowed zero probability. Computing
log_softmax via log-sum-exp keeps both forward values and gradients finite.
04 · Numerical Stability Lab
exp(z) overflows above ~709 in float64; underflowing softmax probabilities turn log(0) into Infinity. Log-sum-exp remains finite in both regimes.CrossEntropyLoss expects raw logits, whereas NLLLoss expects
log-probabilities. Never apply Softmax before calling CrossEntropyLoss during
training, or the optimization objective changes.
Why the gradient is probability minus target
When optimizing logits directly, gradient descent raises the target score and lowers competing
scores; with shared neural network parameters, a single update is not guaranteed to move every
individual sample monotonically. A batch-mean loss divides the gradient by B (no
class weights or ignore_index are used here).
05 · Softmax–CE Backpropagation
p_c - 1 ≤ 0 pushes its logit up; non-target gradients p_j ≥ 0 push competing logits down.Match the loss to the statistical task
| Task | Output | Target | PyTorch loss |
|---|---|---|---|
| Regression | Real values | Continuous | MSELoss |
| Binary / multi-label | Independent logits | Float 0/1, same shape | BCEWithLogitsLoss |
| Mutually exclusive classes | K logits | Long class index | CrossEntropyLoss |
| Same categorical model | K log-probabilities | Long class index | NLLLoss |
Binary classification can use either one sigmoid logit + BCE or two logits + CE; the two are linked by the logit difference. Multi-label tasks allow multiple simultaneous true classes and cannot use mutually exclusive Softmax. MSE can also be defined on probabilities, but its gradient mechanism differs—never compare raw loss magnitudes across different loss functions.
06 · Loss Function Comparison (Binary)
∂MSE/∂z vanishes via p(1-p), whereas ∂BCE/∂z = p - y stays near −1.Engineering lab · robot operating-state classification
Synthetic teaching rule: risk = 0.7v + 0.3t + 0.16 sin(2πt), with
risk < 0.32 as Normal, risk < 0.65 as Warning, and otherwise
Fault. The model receives only inputs and labels, never the formula. 240 training samples and 120
validation samples are generated deterministically; each epoch shuffles the training set for
mini-batch SGD. In real robotics, split by run or trajectory and hold out an independent test set.
07 · Live Multi-class Classification Training
In a confusion matrix (rows = true class, columns = predicted class), the diagonal gives correct classifications and row normalization gives per-class recall. High overall accuracy can still mask missed Fault detections.
Complete Python implementation (classifier0201.py)
import math
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(1)
# Match the browser's deterministic data, initialization and batch order.
def rng(seed):
state = seed
while True:
state = (1664525 * state + 1013904223) & 0xffffffff
yield state / 2**32
def dataset(N, seed):
r = rng(seed)
X = np.array([[next(r), next(r)] for _ in range(N)])
v, t = X.T
risk = 0.7 * v + 0.3 * t + 0.16 * np.sin(2 * np.pi * t)
y = np.where(risk < 0.32, 0, np.where(risk < 0.65, 1, 2))
return torch.tensor(X, dtype=torch.float64), torch.tensor(y, dtype=torch.long)
def order(N, epoch):
a, r = list(range(N)), rng(1000 + epoch)
for i in range(N - 1, 0, -1):
j = int(next(r) * (i + 1))
a[i], a[j] = a[j], a[i]
return a
def train(H=8, bs=24, lr=0.15, objective="ce", epochs=100):
X, y = dataset(240, 123)
V, v = dataset(120, 456)
model = nn.Sequential(nn.Linear(2, H), nn.Tanh(), nn.Linear(H, 3)).double()
r = rng(42)
with torch.no_grad():
model[0].weight.copy_(torch.tensor([(2 * next(r) - 1) / math.sqrt(2) for _ in range(2 * H)], dtype=X.dtype).reshape(H, 2))
model[0].bias.zero_()
model[2].weight.copy_(torch.tensor([(2 * next(r) - 1) / math.sqrt(H) for _ in range(3 * H)], dtype=X.dtype).reshape(3, H))
model[2].bias.zero_()
opt = torch.optim.SGD(model.parameters(), lr=lr)
# Check manual CE gradients on one batch, independent of training objective.
z = model(X[:bs])
z.retain_grad()
L = F.cross_entropy(z, y[:bs])
L.backward()
G = (z.detach().softmax(-1) - F.one_hot(y[:bs], 3)) / len(z)
assert torch.allclose(z.grad, G, atol=1e-12, rtol=0)
with torch.no_grad():
A = model[1](model[0](X[:bs]))
G1 = (G @ model[2].weight) * (1 - A * A)
for p, g in zip(model.parameters(), [G1.T @ X[:bs], G1.sum(0), G.T @ A, G.sum(0)]):
assert torch.allclose(p.grad, g, atol=1e-12, rtol=0)
opt.zero_grad()
@torch.no_grad()
def evaluate(inputs, targets):
logits = model(inputs)
pred = logits.argmax(1)
C = torch.bincount(targets * 3 + pred, minlength=9).reshape(3, 3)
return F.cross_entropy(logits, targets).item(), (pred == targets).double().mean().item(), C.tolist()
for e in range(epochs + 1):
if e % 20 == 0 or e == epochs:
tr, _, _ = evaluate(X, y)
va, acc, C = evaluate(V, v)
print(f"Epoch {e:3}: train CE={tr:.6f}, val CE={va:.6f}, val acc={acc:.3%}")
if e == epochs:
break
model.train()
ids = order(len(X), e)
for start in range(0, len(ids), bs):
i = ids[start:start + bs]
opt.zero_grad()
z = model(X[i])
loss = (
F.cross_entropy(z, y[i])
if objective == "ce"
else F.mse_loss(z.softmax(-1), F.one_hot(y[i], 3).to(z.dtype))
)
loss.backward()
opt.step()
print("Validation confusion (rows=true, cols=pred):", C)
return model, evaluate(V, v)
if __name__ == "__main__":
train()
The batch-averaged CE loss divides the sum of per-sample losses by B, so ∂L/∂z is (p - one_hot(y)) / B.