Training models

Gradient descent, and the models it fits

Lecture 4 Géron Ch. 4

How a model is fitted, when there is no formula for the answer

Applications of Machine Learning
BSc Mathematics of Artificial Intelligence · Third year
Worked example: the Titanic passenger manifest

Where we are

Lecture 3 solved least squares in closed form — the normal equation $\hat{\boldsymbol\theta} = (\mathbf{X}^{\intercal}\mathbf{X})^{-1}\mathbf{X}^{\intercal}y$, defined exactly when $\mathbf{X}$ has full column rank — and then measured a classifier properly: precision, recall, and a threshold chosen against a stated constraint. Both called .fit() and moved on. Today we open it, because the closed form runs out:

SituationWhat the normal equation does
Many featuresinverts an $(n{+}1)\times(n{+}1)$ matrix — cost grows like $n^{3}$
Many instancesforms $\mathbf{X}^{\intercal}\mathbf{X}$, so every row must be seen at once
Rank-deficient designthe inverse does not exist
A cost that is not squared errorthere is no closed form at all

The last row is the one that matters: the classifier we build today has no formula for its answer, so the answer has to be walked to.

Today

  1. The mathematics — gradient descent: the gradient, the update, choosing the step size, why the features must be scaled, and why one row at a time is legitimate
  2. The method — descent against the closed form, and polynomial features
  3. The worked example — logistic regression on 891 Titanic passengers: a probability, not a label; a design matrix that is rank-deficient; a degree sweep; and whether the probabilities are calibrated
  4. More than two classes: softmax regression
  5. Design exercise — a buy-now-pay-later app’s credit decision, in nine steps, with the pitfalls and how to address them

examinable The derivation, and logistic and softmax regression: the model, the log loss, coefficients as log-odds, and why a rank-deficient design leaves the fit without a unique answer. not examinable The Titanic feature engineering.

Open Lecture 4 in Colab

The question

You have a cost $J(\boldsymbol\theta)$ and no formula for its minimiser.

How do you find one, and how do you know you have?

Three things the answer must supply A direction to move in, a step size that does not overshoot, and a reason to believe the point you stop at is the minimum and not merely a place where you stopped.

Step 1 · The cost is a surface

$m$ instances, $n$ features; $\mathbf{X}$ is $m \times (n{+}1)$ with a leading column of ones, and $\boldsymbol\theta \in \mathbb{R}^{n+1}$ includes the bias. We derive on squared error, the one cost whose minimiser we can also compute in closed form — so the method can be checked:

$$J(\boldsymbol\theta) \;=\; \mathrm{MSE}(\boldsymbol\theta) \;=\; \frac{1}{m}\,\lVert \mathbf{X}\boldsymbol\theta - y \rVert_2^{\,2}$$
The algorithm, in one sentence Start anywhere. Step downhill, along $-\nabla J$. Repeat until the downhill direction is flat.

Why $-\nabla J$: along a unit direction $\mathbf{u}$ the cost changes at rate $\nabla J\cdot\mathbf{u}$, and by Cauchy–Schwarz that is most negative when $\mathbf{u}$ points along $-\nabla J$.

Step 2 · The gradient

$$\nabla J(\boldsymbol\theta) \;=\; \frac{2}{m}\,\mathbf{X}^{\intercal} \bigl(\mathbf{X}\boldsymbol\theta - y\bigr)$$

The gradient of the mean squared error

The chain rule on the square gives one partial derivative, $\partial J/\partial\theta_j = \frac{2}{m}\sum_i \bigl(\boldsymbol\theta^{\intercal}\mathbf{x}^{(i)} - y^{(i)}\bigr)x_j^{(i)}$ — error × feature, averaged. That sum is the $j$-th entry of $\mathbf{X}^{\intercal}\mathbf{r}$, with $\mathbf{r} = \mathbf{X}\boldsymbol\theta - y$ the residual vector.

One matrix product over the whole training set. Cost per evaluation: $O(mn)$ — linear in the rows, where the normal equation was cubic in the columns.

Step 3 · The update rule

$$\boldsymbol\theta^{(k+1)} \;=\; \boldsymbol\theta^{(k)} \;-\; \eta\,\nabla J\bigl(\boldsymbol\theta^{(k)}\bigr) \;=\; \boldsymbol\theta^{(k)} \;-\; \frac{2\eta}{m}\,\mathbf{X}^{\intercal}\bigl(\mathbf{X}\boldsymbol\theta^{(k)} - y\bigr)$$

Batch gradient descent

Batch, because every step uses the whole training set. Three lines of NumPy, and no matrix is ever inverted.

$\eta$ has units: it converts a gradient into a displacement in parameter space. That is why its right value depends on how the features are scaled — step 4.

How large a step?

Nothing in the update rule fixes $\eta$. It is a hyperparameter: you try a few values and watch the cost.

Learning rateWhat you see
too smallthe cost falls, slowly, and is still falling when you stop
about rightthe cost drops fast and flattens
too largeevery step overshoots the minimum: the cost rises, oscillates, and overflows to nan
Failure condition — divergence is silent until it is loud A diverging fit does not raise. It returns weights full of inf and a model that predicts one value everywhere. Plot the cost against the step number; it is the only cheap way to see which of the three rows you are in.
Animation

Step 4 · Why you must scale the features

Put one feature in thousands and another in units. The cost changes far faster along the first parameter than along the second, and the bowl of step 1 becomes a long, thin valley.

  • One $\eta$ serves every direction, so it must be small enough not to overshoot along the steep one
  • That same $\eta$ is far too small along the shallow one, where progress crawls
  • The path zig-zags across the valley instead of running down it

Standardising the columns is not cosmetic. It makes the bowl round, so one learning rate suits every direction and far fewer steps are needed.

Step 5 · One instance at a time

Each batch step costs $O(mn)$, which for large $m$ is unaffordable. Draw an index $i$ uniformly at random and use only that row:

$$\mathbf{g}^{(i)}(\boldsymbol\theta) \;=\; 2\bigl(\boldsymbol\theta^{\intercal}\mathbf{x}^{(i)} - y^{(i)}\bigr)\,\mathbf{x}^{(i)}$$

Take the expectation over the draw:

$$\mathbb{E}_i\bigl[\mathbf{g}^{(i)}\bigr] \;=\; \sum_{i=1}^{m}\frac{1}{m}\,2\bigl(\boldsymbol\theta^{\intercal}\mathbf{x}^{(i)} - y^{(i)}\bigr)\mathbf{x}^{(i)} \;=\; \nabla J(\boldsymbol\theta)$$

The one-instance gradient is an unbiased estimate of the batch gradient.

What the derivation buys you

The resultWhat it lets you do today
$\nabla J = \frac{2}{m}\mathbf{X}^{\intercal}(\mathbf{X}\boldsymbol\theta - y)$fit a linear model without inverting anything
$\eta$ is a hyperparameterread a rising cost curve as a step-size fault, not a bug
Unscaled features make a thin valleyknow that scaling is part of the algorithm, not tidiness
Unbiasedness of $\mathbf{g}^{(i)}$use mini-batches on data that does not fit in memory

And one more: only step 2 used the fact that the cost was squared error. Swap the cost, recompute the gradient, and the algorithm is unchanged — which is how the classifier later today is fitted.

Two routes to the same $\hat{\boldsymbol\theta}$

 Normal equation / SVDGradient descent
Cost in $m$linearlinear, per step
Cost in $n$$n^{2.4}$ to $n^{3}$linear
Out-of-coreno — needs all rowsyes, with mini-batches
Scaling requirednoyes
Hyperparametersnone$\eta$, batch size, schedule, stopping rule
Other costssquared error onlyany differentiable cost

When to prefer each. Few features and data that fits in memory: use the closed form, it has no knobs to get wrong. Many features, streaming data, or any cost that is not squared error: descent.

Curvature without leaving linearity

A straight line cannot fit a curve. Add the powers as columns:

$$\hat{y} \;=\; \theta_0 + \theta_1 x + \theta_2 x^{2} \quad\text{is linear in } \boldsymbol\theta,\ \text{not in } x$$

Everything derived above still applies unchanged — the gradient, the update, the case for scaling — because all of them were statements about $\boldsymbol\theta$.

PolynomialFeatures(degree=d) also generates every cross product, which is how a linear model represents an interaction such as “third class and travelling alone”. The count is $\binom{n+d}{d}$ — the number of monomials of degree at most $d$ — so “a bit more capacity” is never a small change.

The task

Marine safety planning unit “We are building an evacuation-assistance model from historical passenger manifests. We need to know, for each passenger profile, how likely that person is to get off unaided — and we need to be able to explain the assignment afterwards.”
What they asked forWhat that forces
“how likely”a probability, not a label
the number is used to allocateit must be calibrated
“explain the assignment”weights a human can read

“This passenger survives” is not checkable on its own. “This passenger survives with probability 0.31” is: take everyone the model puts near 0.31 and count. That is why requirement 1 is not a formatting preference.

The data


def load_titanic():
    tarball = Path("datasets/titanic.tgz")
    if not tarball.is_file():
        Path("datasets").mkdir(parents=True, exist_ok=True)
        url = "https://github.com/ageron/data/raw/main/titanic.tgz"
        urllib.request.urlretrieve(url, tarball)
        with tarfile.open(tarball) as t:
            t.extractall(path="datasets", filter="data")
    return pd.read_csv("datasets/titanic/train.csv")
  

891 passengers, 12 columns — the whole labelled corpus (the archive’s test.csv has no Survived column, so we hold out our own test set). To the class, sex, age, fare and family counts we add four engineered columns: Title from the name (Mr, Mrs, Miss, Master, Rare), FamilySize = SibSp + Parch + 1, IsAlone, and Deck — the cabin letter, or U where none was recorded.

The label

OutcomePassengersShare
Did not survive54961.6%
Survived34238.4%

Mildly imbalanced — nothing like the rare-event problem of the previous lecture, where the positive class was one row in ten. Accuracy will not be absurd here.

It will be something more dangerous than absurd: plausible.

Split first — still


X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

assert len(X_train) == 712 and len(X_test) == 179
print(f"train rate {y_train.mean():.4f}   test rate {y_test.mean():.4f}")
# train rate 0.3834   test rate 0.3855
  

Stratified on the label this time, not on a predictor: with 179 test rows an unstratified draw can shift the base rate by several points, and every downstream number moves with it.

712 training passengers. That is a small dataset, and by the end of the lecture the size is doing visible damage.

Before the model: what does nothing score?


p = y_train.mean()                                   # 0.3834

majority_accuracy = 1 - p                            # 0.617
constant_log_loss = -(p*np.log(p) + (1-p)*np.log(1-p))
  

0.666

The log loss of a model that has learned nothing except the base rate. It is the entropy of the label, in nats, and every number below it has to be compared against it.

Logistic regression: one function, and the whole difference

The logistic curve rising from 0 to 1, passing through 0.5 at t equals zero, flattening at both ends.

$\hat p = \sigma(\boldsymbol\theta^{\intercal}\mathbf{x})$, $\sigma(t) = 1/(1+e^{-t})$: the linear model of least squares, passed through one function. Monotone, so the ranking is the linear model’s; saturating, so beyond about $\lvert t\rvert = 5$ more evidence changes almost nothing.

What $\boldsymbol\theta^{\intercal}\mathbf{x}$ is

Invert $\sigma$:

$$t \;=\; \log\frac{\hat p}{1 - \hat p} \;=\; \boldsymbol\theta^{\intercal}\mathbf{x}$$

The linear model does not predict the probability. It predicts the log-odds, and the coefficients act on the odds.

Add 1 to $x_j$ and the odds are multiplied by $e^{\theta_j}$, wherever you started. The probability has no such rule — how far it moves depends on where you started.

What it minimises

$$J(\boldsymbol\theta) \;=\; -\frac{1}{m}\sum_{i=1}^{m} \Big[\, y^{(i)} \log \hat p^{(i)} + \bigl(1-y^{(i)}\bigr)\log\bigl(1-\hat p^{(i)}\bigr)\Big]$$

The log loss, in nats

  • Only the probability you gave the true class enters each term
  • Unbounded above: claim 0.001 for a passenger who survived and that term is $-\log 0.001 \approx 6.9$
  • It is the negative log-likelihood of the labels under the model, divided by $m$
  • Convex in $\boldsymbol\theta$: its Hessian, $\frac{1}{m}\sum_i \hat p^{(i)}(1-\hat p^{(i)})\,\mathbf{x}^{(i)}\mathbf{x}^{(i)\intercal}$, is positive semi-definite, so every stationary point is a global minimum
Animation

Why this loss and not something friendlier

A scoring rule is proper if the expected score is optimised by reporting your true belief.

  • Log loss — proper. Reporting anything other than the true $p$ is expected to score worse
  • Brier score, $\frac{1}{m}\sum(\hat p - y)^2$ — also proper, bounded, easier to read; we report it too
Failure condition — accuracy is not proper Under accuracy a model reporting 0.51 scores exactly the same as one reporting 0.99. So accuracy gives a model no reason at all to tell the truth about its uncertainty, and optimising it destroys calibration.

Fit it, and measure it honestly


# prep: impute; standardise the numbers (step 4); one-hot the categories
clf = LogisticRegression(C=1e6, max_iter=4000)   # C=1e6: a plain maximum-likelihood fit
model = Pipeline([("prep", prep), ("clf", clf)])

cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
scores = cross_validate(model, X_train, y_train, cv=cv,
                        scoring=["neg_log_loss", "accuracy", "neg_brier_score"],
                        return_train_score=True)
  

StratifiedKFold, not KFold: with 71 passengers per fold, an unstratified split can hand a fold a base rate several points from the truth.

C=1e6 makes this the plain maximum-likelihood fit, so the coefficients read next are the data’s own.

The first numbers

ModelLog lossAccuracy
Report the base rate to everyone0.66661.7%
Logistic regression, 10-fold cross-validated0.49681.5%

About a quarter below the anchor on log loss, and twenty points of accuracy above the majority class.

Cross-validated, not training. And the per-fold spread of the log loss is 0.22 — larger than any difference this lecture will compare. Read every later gap against it.

Three rows that cannot be right

  • Title_Miss at −2.81 — but 70.3% of them survived, against 38.4% overall
  • Title_Mrs at −2.02 — the highest-surviving group in the data
  • Deck_T is the largest weight in the model — and there is exactly one passenger on deck T

These are not weak effects or noisy estimates. They have the wrong sign, and the model’s predictions are nonetheless good.

Before reaching for a story about confounding, ask the cheaper question: what is the shape of the design matrix?

Count the columns, then count the rank


Z   = model[:-1].transform(X_train)
Z_b = np.c_[np.ones(len(Z)), Z]          # add the intercept column

print("columns:", Z_b.shape[1])          # 29
print("rank:   ", np.linalg.matrix_rank(Z_b))   # 23
print("cond:   ", np.linalg.cond(Z_b))          # about 1e16
  

Six columns of the design matrix are linear combinations of the others.

  • Five from the encoder. Each one-hot block sums to 1 in every row — and so does the intercept column
  • One from us. FamilySize = SibSp + Parch + 1 exactly, for every passenger: an identity, not a correlation

Two coefficient vectors, one model

Paired bars for intercept, Sex_female and Sex_male under two fits that differ by a shift of 2.5 along the null space, with a note that all predicted probabilities agree to 3e-16.

Add 2.5 to Sex_female and to Sex_male, subtract 2.5 from the intercept: the two columns sum to the intercept’s, so every prediction is unchanged. The minimiser is not unique, and the solver returns one point of a whole family of them. A coefficient that can be moved without changing any prediction is not a property of the data.

The repair: delete the redundancy


NUM = ["Age", "Fare", "SibSp", "Parch"]        # FamilySize removed

("cat", make_pipeline(SimpleImputer(strategy="most_frequent"),
                      OneHotEncoder(drop="first", min_frequency=2,
                                    handle_unknown="infrequent_if_exist")), CAT),
  
Design matrixColumnsRankCondition number
As first written2923~1e16
One level dropped, FamilySize removed232383.6

Fourteen orders of magnitude. IsAlone stays: it is an indicator, not a linear function of the counts.

Now the coefficients can be read

Horizontal bar chart of logistic regression coefficients with odds multipliers labelled, sorted from most negative to most positive.

Each bar is a log-odds. The label beside it is what the odds get multiplied by.

Reading one of them out loud

Pclass_3 = −1.169 “Holding every other recorded feature fixed, travelling third class multiplies the odds of survival by $e^{-1.169} = 0.31$, relative to first class.”
  • “Holding every other feature fixed” is doing real work — drop it and the sentence is false
  • Odds, not probability. Multiplying odds of 1 by 0.31 gives $p = 0.24$; doing it from $p = 0.9$ gives 0.74
  • Relative to the reference level — the level drop="first" removed, here first class — always

Unique is not the same as stable: Sex and Title still carry much of the same information, so how the effect is split between them moves with the sample. We only fixed uniqueness.

Push the capacity up, and record both curves

Polynomial features on the four numeric columns only, degrees 1 to 6, the same ten folds:

DegreeColumnsTraining log lossHeld-out log lossHeld-out accuracy
1220.3950.46881.5%
2320.3810.47182.2%
3520.3550.53979.8%
4870.3101.38077.1%
51430.2861.95275.1%
62270.2842.00976.0%

Degrees 1 and 2 differ by 0.003 in held-out log loss, and the smaller of their fold-to-fold spreads, 0.13, is 52 times that. Those two are a tie, and the curve turns after degree 2. Crowning either one — degree 1 has the lower mean — would be reporting noise.

At degree 6 the model has 227 weights to determine from 712 passengers — about three rows per weight.

The two curves

Left: training and held-out log loss against polynomial degree; training falls steadily while held-out rises sharply from degree three. Right: the same in accuracy, on a much smaller vertical scale.

The training curve never stops improving. The held-out curve is flat across degrees 1 and 2, turns after degree 2 and then falls off a cliff.

Log loss saw it first

From degree 2 to degree 5, held-out accuracy falls by 7.0 points. Held-out log loss is multiplied by more than four.

  • Accuracy only notices when a prediction crosses the cut-off
  • Log loss notices a confident prediction becoming a confidently wrong one
  • The failure is not that the model gets more passengers wrong — it is that it becomes certain about the ones it gets wrong

The requirement was for probabilities. The metric that matches the requirement is the metric that saw the damage.

What “calibrated” means, precisely

$$P\!\left(y = 1 \;\middle|\; \hat p(\mathbf{x}) = q\right) \;=\; q \qquad \text{for every } q \in (0,1)$$

Take every passenger the model scored near $q$. The fraction who actually survived should be about $q$.

This is a property of a set of predictions, not of any one prediction. You cannot check it on a single passenger, which is exactly why it is so easy to ship a model that fails it.

The reliability diagram

Reliability diagram comparing predicted probability against observed survival rate for training and held-out predictions, with marker area proportional to bin count.

Out of fold — every probability from a fit that never saw that passenger. Close to the diagonal in the bins that hold most of the passengers: the two ends, where the model is confident.

.predict() is .predict_proba() >= 0.5

Failure condition — a bare label hides a decision nobody made Calling .predict() silently applies a cut-off of 0.5, which is cost-optimal only when the two mistakes cost the same. Nothing in the code mentions 0.5. Nothing errors. The accuracy printed is true, and it answers a question the stakeholder did not ask.

Lecture 3 chose an operating point against a stated constraint and defended it. The same discipline applies here, with one addition: the model produces the probability, and the cut-off is a separate decision taken on top of it.

Softmax regression

One parameter vector per class. Score each class, then normalise:

$$s_k(\mathbf{x}) = \boldsymbol\theta_k^{\intercal}\mathbf{x}, \qquad \hat p_k = \frac{\exp\bigl(s_k(\mathbf{x})\bigr)}{\sum_{j=1}^{K}\exp\bigl(s_j(\mathbf{x})\bigr)}$$

Every $\hat p_k > 0$ and they sum to 1 by construction, so the output is a distribution over the $K$ classes without any further work.

Multiclass, not multilabel: softmax assigns one class per instance. Four objects in one photograph need $K$ separate binary classifiers, not this.

Its cost: cross-entropy

$$J(\boldsymbol\Theta) \;=\; -\frac{1}{m}\sum_{i=1}^{m}\sum_{k=1}^{K} y_k^{(i)}\log \hat p_k^{(i)}$$

$y_k^{(i)}$ is 1 if instance $i$ belongs to class $k$ and 0 otherwise, so the inner sum keeps exactly one term: the log of the probability given to the true class.

At $K = 2$ this is the log loss, term for term. Logistic regression is the two-class case of softmax, not a different model.

Animation

The notebook for this lecture

Open Lecture 4 in Colab

  • Runs on free CPU
  • Gradient descent implemented from the derivation, checked against the closed form to eight decimals, run at three learning rates — one too large, so the cost diverges — and the one-row gradient checked to be unbiased
  • Then the Titanic manifest as on the slides: the anchor, the first numbers, the rank computation and the shift that leaves every prediction unchanged, the repair, the coefficients, the degree sweep, the calibration bins, and softmax on three classes
What to change Lower ETA_DIVERGE in the learning-rate cell until the cost stops blowing up, and find roughly the largest learning rate that still converges.

Design exercise · in the manner of an ML system-design interview

The task: a buy-now-pay-later app’s credit decision

The brief A buy-now-pay-later company sits at online checkouts: when a shopper picks “pay in instalments”, the app must approve or decline in a second, from the probability that the shopper defaults. It earns a fee per approved order from the merchant and carries the loss on every default, so it measures the approval rate and the loss rate — and the credit regulator requires each decline explained from recorded features, on lawful grounds.
  • Given: past plans — order amount, merchant category, the shopper’s history with the app, a bureau band, declared income, device — and whether each was repaid
  • Scale: millions of plans; defaults of the order of a few in a hundred
  • Consumers of the output: the checkout, the limit engine, the decline notice, and the regulator’s audit

Nine steps follow, each with the pitfall that catches a first attempt and what to do about it. The model at the centre is today’s: logistic regression, fitted by descent on the log loss, its coefficients read as log-odds.

Step 1 — Frame it: a probability, scored by a proper rule

  • “How likely to default” is a probability, not a label; it sets the limit, so it must be calibrated; it must be explained, so the weights must be readable
  • The metric is the log loss, read beside its anchor: the log loss of reporting the base rate to everyone, the entropy of the label. The Brier score beside it, bounded and easy to read
  • Accuracy at the eventual cut-off is reported too, next to the majority-class accuracy of one minus the base rate — never as the headline
Pitfall — accuracy is not proper The model is selected on accuracy. Under accuracy a shopper scored just above the cut-off counts the same as one scored near certainty, so the model has no reason to tell the truth about its uncertainty, and the probabilities the limit engine lends on drift away from the default rates they claim. Select on log loss against the anchor, and keep accuracy as a side-note.

Step 2 — The label: what “default” means, and for whom it exists

  • Default is defined in writing — so many days in arrears, or sent to collections — and applies to plans that have run their term or reached that state
  • Only plans that were approved have an outcome. The shoppers the app declined have none, so the data describes the people past policies approved, and the hand-over says so
  • Mildly imbalanced, a few in a hundred: accuracy will not be absurd here, only plausible
Pitfall Plans still running are counted as repaid because they have not defaulted yet, so the youngest plans — those approved under the newest policy and merchants — are the cleanest-looking negatives, and the default rate the model learns is below the one finance books. Label only plans whose term has ended or that defaulted, and keep the open ones out of both sets.

Step 3 — Split first, by shopper and stratified, and measure the anchor

  • Hold out the test plans before anything is fitted, stratified on the outcome, each shopper on one side; StratifiedKFold inside the training set, grouped the same way
  • The anchor, on the training plans: base rate, majority-class accuracy and constant-model log loss, at the top of every table
  • The fold-to-fold spread of the log loss is recorded once, and every later gap is read against it
Pitfall A shopper with a dozen plans lands on both sides of a random split, and the device and address columns identify them: the held-out log loss rewards memory of that shopper, and on new customers — the ones merchants pay for — the model is worse than reported. Split and fold by shopper, stratify on the label, and assert the rates.

Step 4 — Features: what the model may use, and what it must not

  • Numbers: order amount, declared income, the instalment as a share of income — the credit team’s own ratio — plans completed, days since a late payment, the bureau band. Categories: merchant, device, country
  • Nothing the law forbids as a ground: no protected attribute enters the design matrix, and the hand-over lists what was excluded and why
  • Everything the model uses must be at the checkout, in the second it has
Pitfall — proxies for protected attributes The protected columns are removed, and the postcode, the first name on the order and the phone model put them back: a postcode can stand for ethnicity, a name for sex, a phone for age. The regulator will ask, and “we did not use it” is not an answer when the coefficient on the proxy says otherwise. Name the proxies, measure how well each predicts it, drop the ones that do, and report the approval rate and the default rate by group.

Step 5 — The model: log-odds, fitted by descent on scaled columns

  • $\hat p = \sigma(\boldsymbol\theta^{\intercal}\mathbf{x})$: the linear part predicts the log-odds, and each coefficient multiplies the odds by $e^{\theta_j}$ per unit of its column, holding the rest fixed
  • No closed form for the log loss, so the solver walks: the gradient, a step size, a stopping rule — and a cost curve to look at
  • Imputer, scaler and encoder inside the pipeline, fitted on the training plans of each fold
Pitfall — unscaled features The amount is in hundreds and plans completed in single digits, so the bowl is a long thin valley: one learning rate overshoots along the steep direction and crawls along the shallow one, the solver stops at its iteration limit with a warning nobody reads, and the coefficients handed to compliance are wherever the walk happened to be. Standardise the numeric columns inside the pipeline — part of the algorithm, not tidiness — and plot the cost against the step before believing a fit.

Step 6 — Log-odds a regulator can read: count the rank first

  • One level of every categorical block dropped, so the reference is stated: “relative to electronics, a fashion order multiplies the odds of default by so much, holding the rest fixed”
  • Rare levels folded into other, not ignored, or an unseen level is scored as the reference
  • Columns, rank and condition number of the design matrix printed before the coefficients are
Pitfall — rank deficiency Every one-hot block sums to the intercept column, and “basket total” is the exact sum of the item columns beside it. The minimiser is then a whole family of coefficient vectors that make identical predictions; the solver returns one, and the reason on a decline notice can be moved without changing a single probability: the regulator can show it is arbitrary. Drop one level per block, remove the sum, and check that the rank equals the column count.

Step 7 — Calibration: the reliability diagram, out of fold

  • Bin the shoppers by predicted probability; in each bin the share that defaulted should match the prediction. That is what “calibrated” means, and it is checkable only on a set
  • Every probability on it comes from a fit that never saw that shopper: cross_val_predict, not predict
  • Capacity is swept the same way — polynomial terms on the numeric columns — with both log losses recorded
Pitfall The reliability diagram is drawn on training predictions and hugs the diagonal; a higher-degree model is chosen because its accuracy barely moved, while its held-out log loss multiplied, because it became certain about the shoppers it gets wrong, whom the limit engine lends most to. Draw it out of fold, read the held-out log loss beside the training one, and stop adding capacity where the held-out curve turns.

Step 8 — In production: the probability, then a cut-off, then drift

  • The model produces the probability. The approve cut-off is a separate decision, set from the merchant fee on a plan that repays against the loss on one that defaults; the limit is set from the probability itself
  • Release to a share of checkouts first, against the old policy; the approval rate read now, the default rate at maturity; refit on a schedule with matured labels; the credit-risk team on call
  • Declined shoppers never get an outcome, so the data drifts towards those the model approves
Pitfall .predict() cuts .predict_proba() at one half, which is right only when the two mistakes cost the same; at a few defaults in a hundred it declines almost nobody, the approval rate looks splendid, and the losses arrive at maturity. State the costs, choose the cut-off from them on the out-of-fold probabilities, and re-choose it when the base rate moves.

Step 9 — Ship it: the pipeline, and the pitfalls in one table

Past plans → closed plans only, default defined in writing → split by shopper, the anchor on training plans → proxies named and dropped → imputer, scaler, encoder with a dropped level, in the pipeline → rank counted → logistic regression by descent → out-of-fold reliability diagram, capacity sweep → cut-off from the costs → staged release; anchor watched; refit on a schedule.

PitfallAddress it by
Selecting on accuracy, which is not properlog loss against the anchor; the Brier score beside it
Open plans counted as repaidclosed plans only, in both sets; selection stated
The same shopper on both sidessplit and folds by shopper, stratified; rates checked
Proxies for protected attributesnamed and measured; dropped if predictive; rates by group
Unscaled columns, a walk that stops shortstandardising inside the pipeline; the cost curve plotted
One-hot blocks and a summed columnone level dropped, the sum removed, the rank checked
A reliability diagram on training predictionsout-of-fold probabilities; held-out loss beside training
A cut-off at one half nobody chosecosts stated; chosen on out-of-fold probabilities; re-chosen

Summary

  • Descent steps along $-\nabla J$; on the MSE that gradient is $\frac{2}{m}\mathbf{X}^{\intercal}(\mathbf{X}\boldsymbol\theta - y)$ — error times feature — and no matrix is ever inverted
  • The learning rate is a hyperparameter, set by watching the cost curve; unscaled features turn the bowl into a thin valley and slow descent down — which is why you scale
  • One instance gives an unbiased gradient, which is what makes stochastic and mini-batch descent legitimate rather than merely cheap
  • Logistic regression predicts the log-odds linearly and is fitted on the log loss, a proper scoring rule; coefficients multiply the odds, always relative to a reference level
  • A rank-deficient design leaves the minimiser not unique: the predictions stand, the coefficients mean nothing — count the rank
  • A probability is checkable and a label is not — and .predict() is a cut-off nobody chose
  • Designed a buy-now-pay-later app’s credit decision in nine steps — log loss against the anchor, closed plans as the label, a split grouped by shopper, proxies for protected attributes named, scaling so that descent converges, a rank-checked encoding whose log-odds a regulator can read, an out-of-fold reliability diagram, and a cut-off chosen from the costs — each step named for the pitfall it avoids

Not presented — for afterwards

Exercises
Lecture 4

five, in the style of the written paper

Exercises — Lecture 4

  • Gradient descent on the same data, with the features unscaled, takes many more steps to converge than on scaled features. Explain why, in terms of the shape of the cost surface. [5]
  • On the Titanic manifest, your logistic regression on one-hot encoded columns produces coefficients that look wrong, and the design matrix has rank six less than its column count. State the cause and the standard repair. [5]
  • A model reaches 0.80 accuracy and is badly calibrated. Explain what that means, and name a decision it would make wrongly that accuracy cannot see. [4]

Solutions on Lecture 5’s deck.

Exercises — Lecture 4 (continued)

  • In a logistic regression with first class as the reference level, the coefficient on Pclass_3 is $-1.169$. State what it multiplies, by how much, and why no single change in the survival probability follows from it. [4]
  • State the update rule for batch gradient descent, and say what changes in it for stochastic gradient descent — and what does not. [4]

Solutions on Lecture 5’s deck.

The five set at the end of Lecture 3

Solutions
Lecture 3

not part of this lecture

Solutions — Lecture 3

1. The normal equation is $\hat\theta = (X^{\mathsf T}X)^{-1}X^{\mathsf T}y$. Your training matrix $X$ has a…

$X^{\mathsf T}X$ is singular; the pseudoinverse returns the minimum-norm least-squares solution.

  • A linear dependence among columns means $X$ does not have linearly independent columns, so $X^{\mathsf T}X$ does not have full rank and has no inverse
  • The fitted values are still unique — the projection onto the column space is — only the coefficients are not

2. A pipeline scales the features and then fits a model, and is passed whole to cross_val_score. Explain what…

The scaler would be fitted on every fold’s validation rows, so each fold’s score could be optimistic — by an amount the code cannot tell you.

  • A scaler is a fitted object: its mean and standard deviation are parameters learned from data
  • Fitting it before the split lets validation rows influence the transformation applied to themselves

Solutions — Lecture 3 (2)

3. On the MNIST 5-detector, a classifier that never fires scores $90.96\%$ accuracy on the training set. State…

The share of the data that is not a 5.

  • With no positive prediction, accuracy is exactly the negative class’s base rate
  • It measures the data, not the model — which is why it is the anchor every other number is read against

4. Prove or disprove: as the decision threshold is lowered, precision increases monotonically.

Disprove — precision is not monotone in the threshold.

  • Lowering the threshold admits one instance at a time; recall cannot fall, but precision rises or falls depending on whether that instance is a true or a false positive
  • A single false positive admitted at a high-precision point lowers it, and a later true positive can raise it again

Solutions — Lecture 3 (3)

5. Two models have the same ROC AUC. One is far better on a precision–recall curve. What does that tell…

The positive class is rare.

  • ROC uses the false-positive rate, whose denominator is the large negative class, so many false positives barely move it
  • PR uses precision, whose denominator is what the model predicted, so the same false positives dominate it

Next lecture

Ensembles and
random forests

A forest-cover map from cartographic columns: a decision tree a person can read, why one tree is unstable, and what averaging two hundred of them can and cannot do