13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
Sooner or later every system that generates text also has to classify it. A fine-tuned encoder gets a classification head; a gateway’s usage policy is a linear head over the engine’s embeddings, a dot product and a sigmoid evaluated on every request. That head has to be fitted, and gradient descent with a learning rate to tune is the wrong tool for a convex problem with a few hundred weights. Newton’s method solves it in five or six steps, each step one linear system solved by LU.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- usage policy: an ordered list of rules that allow or deny inference requests by model, tenant, token cap, or classifier score. Read more: 25.6 Usage policy enforcement in AI Engineering
- linear head: a classifier followed by softmax, applied to a normalized embedding. Read more: 25.6 Usage policy enforcement in AI Engineering
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Likelihood: , the probability of the observed data as a function of the parameter. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- quadratic convergence: , so correct digits double each step. Read more: 7.2 Newton’s Method
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- Linear policy head: a logistic regression over unit embeddings, stored as a two-row softmax for the gateway. Read more: 12.5 Fine-tuning heads and the linear-head export in AI Engineering
- Log-likelihood: , the log probability of the observed counts under a distribution . Read more: 13.3 MLE, Laplace, absolute discounting
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
Once fitted, the head needs two numbers before anyone should trust it. Does it rank unsafe requests above safe ones? That is the area under the ROC curve, the AUC. And when it says 0.9, is it right 90% of the time, so that a threshold of 0.9 means what the operator thinks it means? That is the expected calibration error, the ECE. This section builds the fitter and both metrics, plus temperature scaling, the standard one-parameter fix for an overconfident model. The code is course/solutions/python/tinyllm/prob/metrics.py (logistic_regression_fit, logistic_predict_proba, roc_curve, roc_auc, reliability_bins, ece, fit_temperature); its contract is course/contracts/py/tinyllm/prob/metrics.pyi, and the head it fits follows formats/linear-head.schema.json.
This section reuses three earlier tools: lu and lu_solve from Gaussian elimination and LU with partial pivoting (one solve per Newton step), trapezoid from Definite Integrals: Trapezoid and Simpson (the area under the ROC curve), and newton from Newton’s Method (the temperature’s root). It also helps to have read Hypothesis tests: paired and two-sample permutation, McNemar, Holm, the other half of the evaluation toolkit.
Learning objectives
- Derive the logistic loss, its gradient , and its Hessian, and prove the loss is convex.
- Fit logistic regression by Newton’s method (IRLS) with an unpenalized intercept and a numerically stable sigmoid.
- Build the ROC curve with ties handled as diagonal steps, and explain why its area is a ranking probability.
- Compute reliability bins and the ECE, and explain why ranking and calibration are different questions.
- Fit a temperature by Newton’s method on a convex scalar loss and explain why the starting point matters.
Notation
Section titled “Notation”The section uses these symbols throughout.
| Symbol | Meaning | Type / shape |
|---|---|---|
| feature matrix, one row per example | float64[n, d] | |
| with a column of ones appended (the intercept column, last) | float64[n, d+1] | |
| labels | float64[n] | |
| weights; with an intercept, (the last) is the bias | float64[d+1] | |
| the logit (log-odds) of example | float64[n] | |
| the sigmoid | ||
| predicted | float64[n] | |
(l2) | ridge penalty on the feature weights | float |
| , | gradient and Hessian of the loss | [d+1], [d+1, d+1] |
[n, n] (never formed) | ||
| TPR, FPR | true and false positive rates at a threshold | |
(n_bins) | number of confidence bins | int |
The model and its loss
Section titled “The model and its loss”A linear score can be any real number, but a probability must lie in . The sigmoid maps one to the other, and its inverse is the log-odds: . So logistic regression says the log-odds are linear in the features; a unit step in feature multiplies the odds by . Fitting maximizes the likelihood , or equivalently minimizes
The derivative of the bracket with respect to is just (because ; question 7 of problem set D asks you to show it), so by the chain rule . Differentiating once more, . For any vector , : the loss is convex, and every stationary point is the global minimum (the proof is question 9 of the same set). With an intercept, the intercept row of reads : the fitted probabilities average to the base rate.
Fitting by Newton’s method
Section titled “Fitting by Newton’s method”Convexity tells you there is one minimum; Newton’s method tells you how to reach it fast. Newton’s Method found a root of by . Minimizing is finding a root of its gradient, so the step is : solve (one lu and one lu_solve) and subtract. Expanding shows each step is a weighted least-squares solve with weights that change every iteration, hence the name iteratively reweighted least squares (IRLS). Near the optimum Newton converges quadratically: the error is roughly squared each step, so becomes , then , then rounding. Five or six steps from are typical; the solution stops once a step is below relative. Without a penalty and with perfectly separable data there is no finite minimum (the weights grow forever), which is one reason the head is always fitted with .
The sigmoid itself needs care. overflows for , and is for . Computing , which is at most 1, and choosing the formula by the sign of is exact everywhere.
Regularization
Section titled “Regularization”The penalty pulls feature weights toward 0, and it adds to the Hessian diagonal, which also makes safely invertible. The intercept is not penalized: shrinking it toward 0 would bias every probability toward 0.5 instead of toward the base rate. With the features are switched off and becomes the fraction of positives. This is scikit-learn’s convention with .
The ROC curve
Section titled “The ROC curve”With a fitted model in hand, the next question is how to judge it, starting with ranking. A threshold turns scores into decisions: say 1 when score . Then TPR and FPR . Lowering from to below the smallest score walks from to : each positive passed is a step up, each negative a step right. That staircase is the ROC curve, with one corner per distinct score. Several examples with the same score cannot be separated by any threshold, so they enter together as a diagonal step. Stepping through them one at a time would make the curve depend on the order of the input.
AUC is a ranking probability
Section titled “AUC is a ranking probability”The area under the staircase, trapezoid(tpr, fpr), has a meaning. Each up-step at horizontal position FPR contributes the fraction of negatives already below that positive. Summed, the AUC is the fraction of (positive, negative) pairs in which the positive scores higher, with a tie counting (the diagonal step’s triangle). That is the Mann-Whitney statistic divided by . Several consequences follow: AUC ignores the scores’ scale (any increasing transform leaves it unchanged), flipping the labels gives , and random scores give 0.5.
Calibration and ECE
Section titled “Calibration and ECE”Ranking says nothing about whether the numbers mean what they say. A classifier is calibrated if, among the predictions made with confidence , a fraction is correct. Group the predictions into equal-width bins of confidence, , and compare each bin’s mean confidence with its accuracy; plotted, that comparison is the reliability diagram. The expected calibration error is the count-weighted mean gap:
For a binary probability the prediction is 1 when and the confidence is ; with class probabilities, it is the top class and its probability (the “top-label” ECE of Guo et al.). Even a perfectly calibrated classifier has an ECE of a few hundredths from sampling noise in each bin, which is why a sensible check compares calibrated against overconfident rather than against 0.
The two metrics answer different questions. Sharpening probabilities (pushing them toward 0 and 1) preserves their order, so it leaves the AUC unchanged, and it can wreck the ECE.
Temperature scaling
Section titled “Temperature scaling”That observation suggests a cheap fix for a model that ranks well but is overconfident (Guo et al. 2017): divide every logit row by one temperature fitted on held-out data. The argmax cannot change, so accuracy stays; only the confidences move. With and , the mean NLL is
So is convex in , and its minimum is the root of a scalar function whose derivative is known in closed form: exactly what newton(f, df, x0) solves. fit_temperature calls it with , , and . The start matters. At the softmax is uniform and the curvature is largest, so the steps climb to the root; from a peaked softmax has almost no curvature, and for a model three times too confident the first step lands thousands of units away. A root at means the logits rank the labels no better than chance, and there is no temperature to report.
Working it by hand
Section titled “Working it by hand”Each of the four ideas has a small example you can do on paper, and the tests check all of them.
One Newton step. Take one feature and no intercept: , , . At both , and the step works out as follows.
| Quantity | Computation | Value |
|---|---|---|
The optimum satisfies : , so ; one step already got within 0.008.
ROC and AUC. Take scores with labels , so and . Lowering the threshold through each score gives these corners.
| threshold | 0.9 | 0.7 | 0.6 | 0.4 | 0.3 | |
|---|---|---|---|---|---|---|
| (FPR, TPR) | (0, 0) | (0, 1/3) | (1/2, 1/3) | (1/2, 2/3) | (1/2, 1) | (1, 1) |
The area is . Check it by pairs: positive 0.9 beats both negatives, 0.6 beats only 0.3, and 0.4 beats only 0.3, which is 4 of 6 pairs.
ECE. Take probabilities , labels , and . The predictions are , the confidences , and the correctness (yes, no, yes, yes). Bin indices are . Bin 4 has confidence 0.9, accuracy 1, gap 0.1; bin 3 has confidence 0.75, accuracy 0.5, gap 0.25; bin 2 has confidence 0.6, accuracy 1, gap 0.4. So ECE .
Temperature. Take three items with logits and labels . Here , so : the calibrated confidence is the observed , , and . With logits the same confidence needs , so doubles.
Designing the interface
Section titled “Designing the interface”Seven functions cover fitting, prediction, ranking, calibration, and temperature.
def logistic_regression_fit(X: ArrayLike, y: ArrayLike, l2: float, iters: int, fit_intercept: bool = True) -> NDArray: ...def logistic_predict_proba(X: ArrayLike, w: ArrayLike, fit_intercept: bool = True) -> NDArray: ...def roc_curve(scores: ArrayLike, labels: ArrayLike) -> tuple[NDArray, NDArray, NDArray]: ... # fpr, tpr, thresholdsdef roc_auc(scores: ArrayLike, labels: ArrayLike) -> float: ...def reliability_bins(probs: ArrayLike, labels: ArrayLike, n_bins: int = 15) -> tuple[NDArray, NDArray, NDArray]: ...def ece(probs: ArrayLike, labels: ArrayLike, n_bins: int = 15) -> float: ...def fit_temperature(logits: ArrayLike, labels: ArrayLike, max_iter: int = 50) -> float: ... # T, by M01.2's newtonThe intercept is the last weight, which is the layout the linear-head export writes into the head’s b. roc_curve starts at with threshold and has one more point per distinct score; roc_auc is trapezoid(tpr, fpr). Bins are with index .
Building it step by step
Section titled “Building it step by step”The reasoning comes first, as a chain of eight decisions, and then the annotated code.
Start with a stable sigmoid: compute and return for , otherwise. Both branches are the exact sigmoid and neither can overflow. Next, append the intercept as the last column. Then the model is in all cases, and the last weight is the head’s b. Third, penalize features, not the intercept: a penalty vector pen equal to except 0 in the intercept slot enters the gradient as pen * w and the Hessian as diag(pen).
Fourth, each IRLS iteration is one Newton step. From : compute , , , solve with LU, and set . is applied by scaling the rows of , never formed as an matrix. Stop when the step is below relative, or after iters steps.
Fifth, for the ROC curve, sort descending, cumulate, and keep one point per distinct score. Cumulative sums of and give TP and FP at every cut; keeping only the last index of each run of equal scores makes ties enter together. Prepend with threshold . Sixth, the AUC is the trapezoid of that staircase. Vertical steps add no area, horizontal ones add their height, and diagonal (tie) steps add a trapezoid, which is the credit for tied pairs.
Seventh, reliability bins need a confidence and a correctness per example, then three bincounts. Binary: prediction , confidence . Multi-class: argmax and row max. The bin index is for right-closed bins, and the ECE weights each bin’s gap by its count. Eighth, the temperature is Newton on from . The derivative and curvature are the means of and of , computed from a max-shifted softmax; reject and return .
Here are the sigmoid and the fitter.
def _sigmoid(z: NDArray) -> NDArray: # exp of a non-positive number never overflows: use e^{-|z|} on both sides. e = np.exp(-np.abs(z)) return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))
def logistic_regression_fit(X, y, l2: float, iters: int, fit_intercept: bool = True) -> NDArray: Xa = _design(X, fit_intercept) # 2-D, finite; a column of ones appended last n, k = Xa.shape t = _binary(y, n) # labels as 0.0 / 1.0 # (l2 >= 0 and iters >= 1 checks elided) pen = np.full(k, l2) if fit_intercept: pen[-1] = 0.0 # the intercept is never shrunk toward 0 w = np.zeros(k) for _ in range(int(iters)): p = _sigmoid(Xa @ w) g = Xa.T @ (p - t) + pen * w # gradient of the loss (not the likelihood) # Hessian: X^T S X with S = diag(p (1 - p)), the Bernoulli variances. H = Xa.T @ (Xa * (p * (1.0 - p))[:, None]) + np.diag(pen) P, L, U = lu(H) # M03.2: one factorization per step delta = lu_solve(P, L, U, g) w = w - delta # Newton: w - H^{-1} g if np.max(np.abs(delta)) <= 1e-12 * max(1.0, float(np.max(np.abs(w)))): break # relative step test, as in M01.2 return wTrace the hand example’s step through it: (no intercept), , g = 1·(-1/2) + (-1)·(1/2) + 0 = -1, H = 1/4 + 1/4 + 1 = 3/2, delta = -2/3, so . Note that Xa * s[:, None] scales row by , so Xa.T @ (...) is in without an matrix.
Prediction is short, but it checks the weight layout.
def logistic_predict_proba(X, w, fit_intercept: bool = True) -> NDArray: Xa = _design(X, fit_intercept) wa = np.asarray(w, dtype=np.float64) if wa.shape != (Xa.shape[1],): # a weight vector from another layout fails loudly raise ValueError(f"w must have shape ({Xa.shape[1]},), got {wa.shape}") return _sigmoid(Xa @ wa)The ROC curve and its area come next.
def roc_curve(scores, labels) -> tuple[NDArray, NDArray, NDArray]: # (1-D, finite checks elided) t = _binary(labels, s.size) P = float(np.sum(t)) N = float(s.size) - P if P == 0 or N == 0: raise ValueError("ROC needs both classes among the labels") # a rate over 0 examples order = np.argsort(-s, kind="stable") # descending: the threshold walks down s, t = s[order], t[order] tp = np.cumsum(t) # positives at or above each cut fp = np.cumsum(1.0 - t) # negatives at or above each cut # One point per distinct score: the last index of each run of ties, so # tied scores enter together (a diagonal step). last = np.r_[np.nonzero(np.diff(s))[0], s.size - 1] fpr = np.r_[0.0, fp[last] / N] # start at (0, 0), threshold +inf tpr = np.r_[0.0, tp[last] / P] thresholds = np.r_[np.inf, s[last]] return fpr, tpr, thresholds
def roc_auc(scores, labels) -> float: fpr, tpr, _ = roc_curve(scores, labels) return trapezoid(tpr, fpr) # M01.4; ties get their triangle, i.e. 1/2 creditOn the hand example’s scores (already descending, all distinct), last is every index, and the cumulative counts give the six corners of the table. With two tied examples of opposite labels, last keeps only the second, so the curve goes straight from to and the area is 0.5 whichever comes first in the input.
Calibration is three bincounts.
def reliability_bins(probs, labels, n_bins: int = 15) -> tuple[NDArray, NDArray, NDArray]: # (shape, range, and label checks elided) if p.ndim == 1: # binary: p is P(y = 1) t = _binary(y, p.size) pred = (p >= 0.5).astype(np.float64) conf = np.maximum(p, 1.0 - p) # confidence in the predicted class correct = pred == t else: # [n, C]: top-label pred = np.argmax(p, axis=1) # first argmax on ties conf = np.max(p, axis=1) correct = pred == yf.astype(np.int64) # Right-closed bins (b/B, (b+1)/B]; 0 goes to bin 0, 1.0 to bin B - 1. idx = np.clip(np.ceil(conf * n_bins).astype(np.int64) - 1, 0, n_bins - 1) counts = np.bincount(idx, minlength=n_bins).astype(np.int64) csum = np.bincount(idx, weights=conf, minlength=n_bins) asum = np.bincount(idx, weights=correct.astype(np.float64), minlength=n_bins) safe = np.maximum(counts, 1) # empty bins report 0, not 0/0 return counts, csum / safe, asum / safe
def ece(probs, labels, n_bins: int = 15) -> float: counts, conf, acc = reliability_bins(probs, labels, n_bins) n = float(np.sum(counts)) return float(np.sum(counts / n * np.abs(acc - conf))) # count-weighted; empty bins weigh 0On the hand example, confidences map to bins ; the counts are , and the weighted gaps sum to .
Finally, the temperature.
def fit_temperature(logits, labels, max_iter: int = 50) -> float: # (shape, finiteness, and label checks elided: [n, C], C >= 2, classes in range) zy = z[np.arange(z.shape[0]), yf.astype(np.int64)] # the label's logit per row
def moments(beta: float) -> tuple[NDArray, NDArray]: a = beta * z p = np.exp(a - a.max(axis=1, keepdims=True)) # max-shifted softmax: no overflow p /= p.sum(axis=1, keepdims=True) mean = (p * z).sum(axis=1) # E_p[z] per row return mean, (p * z * z).sum(axis=1) - mean * mean # Var_p[z] per row
# NLL(beta) = mean(logsumexp(beta z) - beta z_y) is convex in beta = 1/T: # its derivative is the mean of E_p[z] - z_y, its second derivative the # mean variance of z under p. Newton (M01.2) finds the derivative's root. # It starts at beta = 0 (p uniform), where the variance is largest: from # beta = 1 a peaked softmax has almost no curvature and the first step # overshoots far past the root. beta, _ = newton( lambda b: float(np.mean(moments(b)[0] - zy)), lambda b: float(np.mean(moments(b)[1])), 0.0, tol=1e-12, max_iter=max_iter, ) if not beta > 0: raise ValueError(f"no positive temperature: the NLL is smallest at 1/T = {beta}") return 1.0 / beta # report T, not betaOn the hand example’s three items with logits , for every row and the mean is , so newton finds , , and the function returns .
The full solution is metrics.py. It calls lu.py, integrate.py, and newton.py.
Why this design
Section titled “Why this design”On cost: one IRLS step is to build plus for the LU, and five or six steps suffice. roc_curve is for the sort; reliability_bins is ; each Newton step of fit_temperature is .
Newton beats gradient descent here. For a convex problem with a few hundred weights the solve is cheap, there is no learning rate to tune, and quadratic convergence reaches rounding in a handful of steps. L-BFGS (scikit-learn’s default) avoids forming , which matters only when is in the many thousands.
Sort-and-cumulate beats pairwise AUC. Counting all pairs is ; the staircase gives the same number (ties included) in , plus the curve and thresholds for free.
Right-closed bins and top-label confidence match Guo et al. and the Go port, so a reported ECE means the same number everywhere; the floor rule would move edge values like 0.8 up a bin.
Two tradeoffs are accepted. Unpenalized fits on separable data have no finite optimum and stop at iters, so callers always pass . And ECE with equal-width bins is noisy for small and ignores where in a bin the confidences fall; it is a coarse but standard summary.
What can go wrong
Section titled “What can go wrong”The tests a correct solution must pass fall into a few groups. The hand examples come first: one Newton step gives and the converged satisfies , so everyone agrees on and ; the ROC gives the six corners and AUC ; the ECE example gives bins and ECE 0.25; and the temperature is for a logit gap of 1 and twice that for a gap of 2.
The fitter is checked against a golden reference and against its theory. IRLS must equal scipy’s BFGS minimizer on four datasets. At the result, the gradient must be below and the mean must equal the base rate. Errors must square per step, so 8 steps equal 50. The weight norm must fall as grows while the intercept stays free. The sigmoid must give exactly 1 and 0 at , never NaN, since embeddings can have large norms. And the intercept must be the last weight, as the linear-head format requires.
The ranking metrics are checked the same way. The ROC corners and thresholds must match a brute-force computation on continuous and tied scores, and the AUC must equal . It must be invariant to monotone transforms, give under a label flip, and give 1 and 0.5 in the obvious cases. Two tied examples must give 0.5 in either order, which matters because quantized scores tie often.
Calibration has golden checks for bins and ECE, binary and 3-class, and a statistical check that a calibrated model scores under 0.04 while a sharpened one scores above 0.1. Bin edges 0.5, 0.75, 1.0, and 0 must land in the right bins for cross-language agreement, and the multi-class top label uses the first argmax and the row-max confidence. Temperature scaling of logits three times too sharp must give near 3, a true NLL minimum, the same argmax, and half the ECE. Finally, bad arguments must raise: bad labels, shapes, penalties, a one-class ROC, bad probabilities, and, for the temperature, 1-D logits, bad classes, NaN, or logits worse than chance, so no negative temperature is ever reported.
The pitfalls below are the mistakes those checks catch, each paired with the line of the solution that avoids it.
Warning: Computing or without care gives NaN probabilities for large logits.
_sigmoiduses and picks the formula by sign.
Warning: Using the gradient of the likelihood instead of the loss makes Newton walk uphill and diverge. The solution computes
g = Xa.T @ (p - t) + pen * w.
In the fitter, penalizing the intercept pulls probabilities toward 0.5 and loses the base rate (the fix is pen[-1] = 0.0). A Hessian without the weights gives linear rather than quadratic convergence and wrong answers after a few steps (the rows are scaled by p * (1.0 - p)). Putting the intercept column first leaves a feature weight in the head’s b (_design appends the ones column last).
In the ROC code, stepping through tied scores one at a time makes the AUC depend on the input order (last keeps one point per distinct score). Sorting scores ascending reports (the solution uses np.argsort(-s, ...)). A curve that does not start at drops the first corner from plots and thresholds (hence np.r_[0.0, ...] and np.r_[np.inf, ...]).
In calibration, an unweighted mean over bins lets one stray prediction in an empty corner dominate the ECE (the solution weights by counts / n * np.abs(acc - conf)). Using binary confidence instead of counts confident negatives as unconfident (conf = np.maximum(p, 1.0 - p)). Floor-based bins move edge values one bin up and give a different number from Go and the paper (np.ceil(conf * n_bins) - 1, clipped).
In temperature scaling, returning instead of makes an overconfident model sharper, not softer (return 1.0 / beta), and computing without the label’s logit makes the root independent of the labels (moments(b)[0] - zy).
Where this leads
Section titled “Where this leads”Looking back, lu and lu_solve from Gaussian elimination and LU solve in each Newton step; trapezoid(tpr, fpr) from Definite Integrals: Trapezoid and Simpson is the AUC; and newton(f, df, 0.0) from Newton’s Method finds the root of for fit_temperature, while IRLS is the same method on a gradient vector.
Looking forward, Fine-tuning heads and the linear-head export in AI Engineering fits the usage-policy head on embeddings and exports it as linear-head.schema.json with its AUC and ECE. ELMo: biLM, ScalarMix, linear probes uses the same fitter for probing classifiers over frozen representations, and Bias and safety evals in AI Engineering puts the ROC and the reliability diagram in the safety report. Questions 5 to 9 of problem set D practise regression, odds, the loss gradient, AUC by hand, and the convexity proof.
Production libraries extend each piece. sklearn.linear_model.LogisticRegression (sklearn/linear_model/_logistic.py) adds L-BFGS and Newton-CG solvers that never form , L1 penalties, and multinomial fits. The statsmodels GLM (statsmodels/genmod/generalized_linear_model.py) runs the same IRLS for every exponential family, with standard errors from . sklearn.metrics.roc_curve and roc_auc_score (sklearn/metrics/_ranking.py) drop collinear corners and average multiclass one-vs-rest. Temperature scaling itself is Guo et al. (2017), section 4.2: one scalar fitted on held-out logits that fixes most overconfidence. And in place of a linear policy head, systems such as Llama Guard and OpenAI moderation use a classifier model with per-category thresholds (Inan et al., “Llama Guard”, 2023).
Further reading
Section titled “Further reading”- Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning (free), section 4.4 (logistic regression and IRLS).
- Fawcett, “An introduction to ROC analysis” (2006).
- Guo, Pleiss, Sun, and Weinberger, “On Calibration of Modern Neural Networks” (2017).
Key terms
Section titled “Key terms”- Logistic regression: a model in which the log-odds are linear in the features.
- IRLS: iteratively reweighted least squares, Newton’s method on the logistic loss, where each step is a weighted least-squares solve with weights .
- ROC curve: the staircase of (FPR, TPR) pairs traced as the decision threshold falls through every distinct score.
- AUC: the area under the ROC curve, equal to the probability that a random positive outscores a random negative, ties counting half.
- Calibration: the property that predictions made with confidence are correct a fraction of the time.
- ECE: expected calibration error, the count-weighted mean gap between accuracy and confidence over confidence bins.
- Temperature scaling: dividing logits by one fitted scalar to fix over- or underconfidence without changing the argmax.
Summary
Section titled “Summary”- Logistic regression models ; its loss is convex, so the minimum is where the gradient vanishes.
- Newton’s method on that loss is IRLS: each step is one linear solve with the Hessian , , and the digits double per step.
- The ROC curve sweeps every threshold; its area, the AUC, is the probability a random positive outscores a random negative, ties counting half.
- Calibration asks whether “0.8” means right 80% of the time; the ECE is the count-weighted gap between confidence and accuracy over bins.
- A ranking metric and a calibration metric answer different questions: sharpening probabilities leaves the AUC unchanged and wrecks the ECE, and temperature scaling fixes the ECE without touching the ranking.
Review questions
Section titled “Review questions”-
Why is the gradient and not ?
Answer
The function minimizes the negative log-likelihood; its derivative with respect to each logit is . is the gradient of the likelihood, and steps uphill: on the hand example it would give and move away from the optimum .
-
Why is the intercept’s penalty set to 0?
Answer
The intercept sets the base rate: at the optimum , so the mean prediction equals the fraction of positives. Shrinking it toward 0 pulls every probability toward , a bias unrelated to overfitting the features. As the unpenalized intercept still lets equal the base rate.
-
Why does
roc_curvekeep only the last index of each run of tied scores?Answer
No threshold can separate examples with the same score, so they must enter the curve together. Keeping intermediate points would create corners that depend on the input order: a positive listed before its tied negative gives AUC 1 for that pair, after it gives 0. Jumping to the end of the run gives a diagonal step whose trapezoid is the credit Mann-Whitney assigns to ties.
-
For a binary probability, why is the confidence and not ?
Answer
Calibration compares confidence in the predicted class with how often that prediction is right. A prediction predicts class 0 with confidence 0.9; filing it in the 0.1 bin would compare a confident correct negative against an accuracy that measures a different event and inflate the ECE.
-
Why does
fit_temperaturestart Newton at rather than at (no change)?Answer
is the mean variance of the logits under the softmax. At the softmax is uniform and that variance is largest, so the first step is moderate and the iterates climb toward the root. At an overconfident model’s softmax is nearly one-hot, the variance is almost 0, and the step is enormous, overshooting by thousands of units.
-
A colleague squares every predicted probability’s odds (pushing them toward 0 and 1). What happens to the AUC and to the ECE?
Answer
Squaring the odds is an increasing transform of the scores, so every pairwise comparison between a positive and a negative is unchanged and the AUC stays exactly the same. The confidences move toward 0 and 1 while the accuracies in each region stay put, so a model that was calibrated becomes overconfident and its ECE rises. That is the sense in which ranking and calibration are separate questions.