~/teaching · machine learning · session 2, wednesday 14 october 2026
Maximum likelihood, logistic regression and honest validation, step by step
Why the loss follows from the distribution, and how to measure a model without fooling yourself.
Abstract
This deck is the afternoon of session 2 of the Machine Learning course at Centrale Méditerranée (option DDEFI, 2026-2027). It answers a question left open by the morning on least squares: why squares? The answer is a recipe. Pick a probability distribution for the target, write the probability of the data you observed, take its logarithm, flip the sign, and you have the loss. A Gaussian target gives least squares; a 0/1 target gives the log-loss of logistic regression.
The deck then builds logistic regression piece by piece: the sigmoid and its inverse the logit, the gradient in three lines, the Hessian and the convexity that guarantees a single minimum, the softmax for several classes, and the reading of a coefficient as an odds ratio. The second part is about generalisation: the bias-variance decomposition, cross-validation, the two most common data leaks, and how many test rows a number needs before anyone should believe it.
The running example is a credit-default problem, the UCI dataset of 30,000 Taiwanese card holders (Yeh and Lien, 2009, data from 2005) with 22.1 % defaults. After reading, you can derive the logistic gradient by hand, explain a coefficient correctly in a report, and set up a validation that does not leak.
Plan of the deck
- From the distribution to the loss. Bernoulli likelihood, logarithm, log-loss, and the same recipe applied to a Gaussian target, which gives back least squares.
- The sigmoid and the logit. How a real score becomes a probability, the derivative to memorise, and why logistic regression is linear on the log-odds.
- Gradient, Hessian, convexity. The gradient is predicted minus observed, weighted by the features, and the loss has no false minimum.
- Softmax and cross-entropy. The same idea with K classes, and the binary case recovered as K = 2.
- Reading a coefficient. Odds, odds ratios, confidence intervals, and the classic error of reading an odds ratio as a change in risk.
- Bias-variance and leak-free validation. The three-term decomposition, cross-validation, leakage, time-ordered splits and Hoeffding's bound on the test set.
- Team project kick-off. SQL audit with DuckDB, datasheet, leakage map, frozen stratified split, two baselines and a first written decision.
From the Bernoulli likelihood to the log-loss
A good classifier gives a high probability to what actually happened, and the log-loss is simply the price it pays when it does not.
Each client either defaults () or does not (). Model that outcome as a biased coin whose bias depends on the client's features . This is a Bernoulli distribution. A neat trick with exponents writes the probability of the observed outcome without any case distinction, since equals when the client defaulted and when he did not.
Assuming clients are independent given their features, the probability of the whole dataset is the product of these terms. That product, seen as a function of the parameters , is the likelihood. Maximum likelihood estimation (MLE) chooses the that makes it largest.
Two practical reasons push us to the logarithm. A product of 30,000 numbers below 1 underflows in floating point, and a sum is easier to differentiate than a product. Because the logarithm is increasing, the maximiser does not move. Machine learning prefers to minimise, so we flip the sign and obtain the log-loss, also called binary cross-entropy.
For a client who really defaults, only remains. The table shows how harshly the loss treats confident mistakes (natural logarithm, so the unit is the nat).
| Predicted | Loss | Reading |
|---|---|---|
| 0.99 | 0.010 | confident and right: almost free |
| 0.80 | 0.223 | fairly sure, moderate cost |
| 0.50 | 0.693 | a coin toss, |
| 0.10 | 2.303 | wrong, and paying for it |
| 0.01 | 4.605 | confident and wrong: 460 times the first line |
Same recipe, Gaussian target: least squares
Least squares is not an arbitrary choice: it is what maximum likelihood gives when the noise around the prediction is Gaussian.
Run the recipe on a continuous target. Suppose the observed price is Gaussian around the linear prediction, . Each density is a constant times , where is the residual. Take the log of the product: the constants pile up into a term that does not depend on , and the exponents add up into a sum of squared residuals.
A positive factor and an additive constant do not move a minimum, so the Gaussian MLE is exactly the ordinary least squares estimator of the morning, with its normal equations. Had the noise been Laplace instead, the exponent would hold and the recipe would give least absolute deviations, the median rather than the mean.
Remark (One distribution, one loss). When someone asks why a model uses a given loss, the answer is the distribution assumed for the target, not a library default. Gaussian: squares. Bernoulli: log-loss. The rest is optimisation.
The floor every model must beat
Predict the base rate for every client. Its mean log-loss is the entropy of the target, about 0.528 nats. Any credit model that cannot go below this number on validation data has learnt nothing useful.
The deck also shows the form libraries actually compute, written with the score , namely the mean of . The function is the softplus, which can be evaluated without overflow even for very negative scores.
The sigmoid and the logit
The sigmoid squeezes any real score into a probability, and its inverse shows that logistic regression is a straight line on the log-odds scale.
A linear score ranges over the whole real line; a probability lives in . The sigmoid bridges the two. Since , the denominator exceeds 1 and the result stays strictly between 0 and 1: the model never predicts certainty, which also keeps the log-loss away from .
The derivative is the one formula worth memorising: it makes the gradient fall out in a few lines, and its maximum of one quarter at will later explain why gradients fade in deep sigmoid networks. Solving for gives the logit, the logarithm of the odds:
Check at a score of 2
- Exponential. , so the denominator is about 1.135.
- Probability. .
- Slope. , below the ceiling of 0.25.
- Back to the score. , so the logit undoes the sigmoid.
The gradient, the Hessian and convexity
The direction to move the coefficients is given by the gap between what the model predicted and what happened, and the loss has a single valley.
Each term of the log-likelihood depends on only through the score . Differentiate with respect to the score first: thanks to , every denominator cancels and what remains is , observed minus predicted. The chain rule then multiplies by , and stacking the clients gives a matrix product.
Compare with least squares, whose gradient is . Same shape, a different residual. The sigmoid is what prevents a closed-form solution, so the coefficients are found iteratively, by gradient descent or by Newton's method (known to statisticians as IRLS).
Differentiating once more gives the Hessian, a matrix with the same structure as but weighted by , numbers between 0 and one quarter. For any direction , the quadratic form is a weighted sum of squares, hence never negative. The log-loss is therefore convex: every local minimum is global, and it is unique when the columns of are linearly independent.
Worked example: five clients, one feature (months in arrears)
- Data. Arrears , outcomes , predicted probabilities (illustrative numbers).
- Gaps. , so the two defaulters are underestimated.
- Gradient. Weight each gap by and add: . Negative, so increasing the arrears coefficient lowers the loss.
- Hessian. , so the loss curves upwards.
- Newton step. Minus the gradient over the Hessian, , is how much the coefficient would rise in one step.
Remark (When the minimum does not exist). If a hyperplane separates defaulters from the others perfectly, the likelihood keeps rising as the coefficients grow without bound (Albert and Anderson, 1984). Scikit-learn hides this because it regularises by default; the remedy, regularisation, is the subject of the next session.
Softmax and cross-entropy for several classes
With more than two classes, each class gets a score, the softmax turns the scores into probabilities, and the gradient keeps the same predicted-minus-observed shape.
Give each of the classes its own linear score, exponentiate to make them positive, and divide by their sum. The target is a one-hot vector, so the cross-entropy keeps a single term: minus the log of the probability given to the true class. Differentiating through the log-sum-exp gives a strikingly simple result.
With scores the exponentials are about 7.389, 2.718 and 1, summing to 11.107; the probabilities are 0.665, 0.245 and 0.090. If the true class is the first, the loss is and the gradient raises the true score and lowers the others. It sums to zero, because adding the same constant to every score changes nothing.
With two classes, dividing top and bottom by gives . Binary logistic regression is the softmax with , and only the difference of the scores matters, which is why it needs a single coefficient vector. The same layer closes almost every classification network (see the note on attention).
Reading a coefficient as an odds ratio
A logistic coefficient multiplies the odds by a fixed factor, but the change in probability depends on where the client starts.
The odds are , so a client at 10 % has odds of 1 to 9, about 0.111. Since the logit is linear, raising by one unit, everything else fixed, adds to the log-odds and multiplies the odds by , the odds ratio. That factor is the same for every client, which is what makes it the right number to publish.
The interval is built on the coefficient, where the normal approximation holds, then exponentiated, so it is asymmetric around the odds ratio. The standard error comes from the inverse Hessian at the estimate.
| Client | Start | Odds | Odds after | End | Change |
|---|---|---|---|---|---|
| low risk | 0.10 | 0.111 | 0.202 | 0.168 | +6.8 points |
| even odds | 0.50 | 1.000 | 1.822 | 0.646 | +14.6 points |
Same odds ratio, twice the effect in probability. Writing "the risk rises by 82 %" is therefore wrong, and validators spot it at once. A sound report gives the odds ratio with its interval, plus the probability before and after for a typical client. When categorical variables are one-hot encoded, it also names the reference level.
Bias-variance and validation without leakage
Test error has three sources, only one of which you control, and measuring it honestly means no information from the test set may reach the model.
For and a model fitted on a random sample , the expected squared error at a point splits into irreducible noise, squared bias (the systematic gap of a family that is too simple) and variance (how much the fit moves when the sample is redrawn). The proof adds and subtracts the mean prediction twice, and both cross terms vanish.
| Polynomial degree | Bias² | Variance | Diagnosis | Measured error |
|---|---|---|---|---|
| 0 | 0.999 | 0.019 | underfits | 1.103 |
| 3 | 0.000 | 0.011 | about right | 0.102 |
| 9 | 0.000 | 0.055 | overfits | 0.145 |
In practice the three terms are never seen separately; what you see is a training error that keeps falling and a validation error that turns back up. Cross-validation estimates that second curve without touching the test set: split the remaining rows into stratified folds, train on , score the held-out fold, average. The mean is nearly unbiased for the procedure, but the displayed standard deviation is not a confidence interval, since the training sets overlap heavily (Bengio and Grandvalet, 2004).
Data leakage is any statistic of the test data that enters the model. The two classics: scaling features on the whole file before splitting (fix: a Pipeline fitted inside each fold), and target encoding computed on all rows, so each row sees its own label (fix: out-of-fold encoding). On dated data, shuffled folds let the model train on the future; a TimeSeriesSplit trains on the past and validates on what follows.
Finally, how far can a test score be trusted? Hoeffding's inequality bounds the gap between measured and true error for a loss in and independent rows, with no assumption on the model. Fixing the risk and solving gives the margin:
With and 1,000 test rows, , divided by 2,000 and square-rooted, gives about 0.043: two models at 81 % and 84 % cannot be told apart. The margin shrinks like , so halving it costs four times the rows; the project's 6,000 test rows give about 1.8 points. The guarantee only holds if the test set is looked at once.
The kick-off of the team project applies all of this to the credit data: a SQL audit with DuckDB, a datasheet stating exactly what the target means, a leakage map dating every column against the prediction date, a stratified 60/20/20 split frozen by a seed and a file hash, and two baselines (the constant model at 0.528 and a default logistic regression in a pipeline). The project page follows it further.
Key takeaways
- Choosing a distribution for the target chooses the loss: Gaussian noise gives least squares, a Bernoulli target gives the log-loss.
- The sigmoid maps a score to a probability, its derivative is , and its inverse, the logit, is linear in the features.
- The logistic gradient is , the same shape as for least squares; the Hessian makes the loss convex.
- A coefficient multiplies the odds by . Report the odds ratio with its interval and the probabilities before and after, never a percentage change in risk.
- Test error is noise plus squared bias plus variance; only the trade-off between the last two depends on your modelling choices.
- Any test-set statistic that reaches the model is a leak: fit scaling and encodings inside the folds, and respect time order on dated data.
- A test score has a margin of roughly , so a few hundred test rows cannot separate close models.
Glossary
- Likelihood
- The probability of the observed data, seen as a function of the model parameters.
- Maximum likelihood estimation (MLE)
- Choosing the parameters that make the observed data most probable.
- Log-loss (binary cross-entropy)
- Minus the mean log-likelihood of a 0/1 target; the loss minimised by logistic regression.
- Sigmoid
- The function that maps a real score to a probability strictly between 0 and 1.
- Logit (log-odds)
- The logarithm of , the inverse of the sigmoid; linear in the features in logistic regression.
- Odds ratio
- The factor by which the odds are multiplied when a feature rises by one unit.
- Hessian
- The matrix of second derivatives of the loss; positive semi-definite here, hence convexity.
- Softmax
- Turns K scores into K probabilities by exponentiating and normalising.
- Bias-variance trade-off
- Simpler models err systematically, flexible ones vary with the sample; the test error adds both to the noise.
- Cross-validation
- Averaging the error over k folds, each held out once, to estimate the error of a procedure.
- Data leakage
- Any information from the test data, or from the future, that enters the training of the model.
- Target encoding
- Replacing a category by the mean target of that category; leaks unless computed out of fold.
- Hoeffding's inequality
- A bound on the gap between measured and true error that needs only a bounded loss and independent rows.
The other notes of the course
One public summary per deck, in the order of the course.
Previous: Project framing and least squaresNext: Gradient descent, ridge and lasso
- IntroductionAI winters, jobs and method
- ToolsKaggle, GitHub, Python: the tools
- Session 1Project framing and least squares
- Session 2Maximum likelihood and logistic regression
- Session 3Gradient descent, ridge and lasso
- Session 4Decision threshold and reproducible ML
- HomeworkA defensible baseline model
- Session 5Kernels, SVM and decision trees
- Session 6Forests, boosting, honest comparison
- Session 7SHAP, fairness, PCA and clustering
- HomeworkA documented champion model
- Session 8Neural networks, drift, conformal prediction
- HomeworkA delivered machine learning project
- Session 9Defending a machine learning project
- ReferenceCredit default scoring project
- ReferenceAsset returns: XGBoost and sentiment
- ReferencePython code for every ML model
- ReferenceDeep learning essentials
- ReferenceOpen data ML projects by sector
- ReferenceData and AI engineer handbook
- ReferenceData engineering, SRE and cloud
- ReferencePanorama of machine learning models
About these notes
Written by the lecturer from the slides of the deck, as a public summary: the key ideas, the formulas and one worked example. The exercises, their solutions, the tests and the grading stay in the deck, for the students of the course.
Revision: .