Linear models, loss functions and gradient descent

  • Beginner
  • 1 h
  • Lesson 2 of 2 in ML foundations
  • Last verified

Open slides(28 slides)

Before you start

You will be able to

  • Derive the gradient (p - y) x of the log loss for logistic regression, and explain why cross-entropy rather than squared error is paired with a sigmoid.
  • Solve linear regression with the normal equation and with gradient descent, and say when each is the right tool and what collinear features do.
  • Choose a loss for a task (squared error, absolute error, Huber, cross-entropy, hinge) by what it penalises, and predict how each reacts to an outlier or a confident mistake.
  • Explain how the learning rate, batch size, momentum, Adam and feature scaling change a gradient descent run, and diagnose a run that diverges, crawls or oscillates.

Concept

Almost every model in this course is the same three pieces: a function, a loss and an optimizer. The function turns inputs into a prediction, the loss scores how wrong it is, and the optimizer changes the parameters to make the loss smaller. Swap one piece and you get a different algorithm. Linear regression is a linear function, squared error and (optionally) a closed-form solver. Logistic regression is a linear function inside a sigmoid, cross-entropy and gradient descent. A neural network keeps the same loop with a bigger function.

The previous lesson said what we minimise (a penalised average loss) and deferred the details of the losses and the optimizer. This lesson fills them in on the two simplest models, small enough to do by hand.

TaskOutputTypical lossWhy this pairing
RegressionLinear, any real numberSquared error (MSE)Maximum likelihood under Gaussian noise
Regression with outliersLinearAbsolute error or HuberA mistake grows linearly, not quadratically
Binary classificationSigmoid, a probabilityBinary cross-entropy (log loss)Maximum likelihood for a Bernoulli label
MulticlassSoftmax, one probability per classCross-entropyMaximum likelihood for a categorical label
Margin classifier (SVM)Raw scoreHingeOnly examples near or past the boundary matter

Ranking, contrastive and class-imbalance losses (pairwise, triplet, focal and weighted cross-entropy) fill more rows of this table. They are outside this lesson.

Diagram: Logistic regression computes a linear score, squashes it to a probability, measures the log loss against the true label, and takes the...

Features x

Score z = w.x + b

Sigmoid: p = 1/(1+e^-z)

Log loss
-[y log p + (1-y) log(1-p)]

Gradient
(p - y) x

Update
w = w - lr * gradient

Diagram summary: Logistic regression computes a linear score, squashes it to a probability, measures the log loss against the true label, and takes the gradient, which simplifies to (p minus y) times x. The optimizer subtracts a learning-rate multiple of that gradient and the loop repeats.

Why It Matters

A model you cannot train is not a model. Much debugging time goes to optimisation: the loss does not move, becomes NaN, oscillates, or crawls because one feature is measured in thousands. The machinery tells you where to look, and it is the base for what follows: the gradient of cross-entropy with respect to the score is prediction minus target in a deep network’s last layer too. These models are also baselines to beat before reaching for something heavier, and a common interview topic (common industry pattern).

Mental Model

Picture the loss as a landscape and training as walking downhill in fog. The gradient is the slope at your feet and the learning rate is your stride: too long and you step over the valley, too short and the walk takes all day. Momentum adds inertia, Adam rescales the stride per direction, and feature scaling turns a long thin canyon into a round bowl.

Linear regression and the normal equation

The model predicts y^=Xw\hat y = Xw, where each row of XX is an example and a column of ones carries the intercept. The loss is the mean squared error J(w)=1n∥Xw−y∥2J(w) = \tfrac1n\lVert Xw - y\rVert^2. Why squared? If each label is the linear prediction plus Gaussian noise, maximising the likelihood is the same as minimising the squared error (Dive into Deep Learning, Linear regression). That is a modelling assumption, and it is also why squared error is sensitive to outliers, which are very unlikely under a Gaussian.

Setting the gradient to zero gives the normal equation:

∇wJ=2nX⊤(Xw−y)=0⇒X⊤X w=X⊤y⇒w=(X⊤X)−1X⊤y\nabla_w J = \tfrac2n X^{\top}(Xw - y) = 0 \quad\Rightarrow\quad X^{\top}X\,w = X^{\top}y \quad\Rightarrow\quad w = (X^{\top}X)^{-1}X^{\top}y

The middle form says the residual y−Xwy - Xw is orthogonal to every column of XX: no feature can still explain what is left over.

Worked example: three points, solved exactly

Fit y=b+wxy = b + wx to x=[1,2,3]x = [1,2,3], y=[2,4,5]y = [2,4,5]. With the column of ones, X⊤X=(36614)X^{\top}X = \begin{pmatrix}3 & 6\\ 6 & 14\end{pmatrix} and X⊤y=(11,25)X^{\top}y = (11, 25). The determinant is 3⋅14−6⋅6=63\cdot14 - 6\cdot6 = 6, so b=2/3b = 2/3 and w=3/2w = 3/2. The residuals are −1/6, 1/3, −1/6-1/6,\ 1/3,\ -1/6. They sum to 0 and ∑xiri=0\sum x_i r_i = 0, the orthogonality condition. The mean squared error is 1/181/18. The script in the Code section prints each of these.

When the closed form is the wrong tool

The closed form is exact and needs no learning rate, so use it when the problem is small. Its limits:

  • Cost. scikit-learn’s least squares (via the singular value decomposition) costs O(nsamples nfeatures2)O(n_{\text{samples}}\, n_{\text{features}}^2) (scikit-learn, Linear models). Forming X⊤XX^{\top}X costs O(nd2)O(nd^2) and solving it O(d3)O(d^3). With 200,000 features X⊤XX^{\top}X alone has 40 billion entries, and streaming data never fits at once, so mini-batch gradient descent is the tool.
  • Nearly dependent columns. The solution is unique only if the columns are linearly independent (Dive into Deep Learning). Otherwise the estimate “becomes highly sensitive to random errors in the observed target, producing a large variance” (scikit-learn, Linear models): predictions stay stable but coefficients swing and can flip sign. Ridge (previous lesson) adds λI\lambda I and fixes this; gradient descent does not escape it, it just crawls along the flat direction.
  • No closed form exists for most models, including logistic regression.

Libraries decompose XX rather than literally inverting X⊤XX^{\top}X. Check the assumptions behind inference (linearity, independent errors, normal residuals, equal variance: LINE) with a residual plot, measure collinearity with the variance inflation factor (VIF), and judge new features by validation error or adjusted R2R^2, since training R2R^2 never falls when a feature is added under least squares with an intercept.

Logistic regression and the gradient

For a label y∈{0,1}y \in \{0,1\} we want a probability, so the linear score goes through the sigmoid:

p=σ(z)=11+e−z,z=w⊤x+bp = \sigma(z) = \frac{1}{1+e^{-z}}, \qquad z = w^{\top}x + b

The loss is the log loss (binary cross-entropy), the negative log-likelihood of a Bernoulli label, so minimising it is maximum likelihood. It is the cost scikit-learn’s LogisticRegression minimises, plus a penalty (scikit-learn, Linear models):

ℓ=−[ ylog⁡p+(1−y)log⁡(1−p) ]\ell = -\big[\,y\log p + (1-y)\log(1-p)\,\big]

Derivation: why the gradient is (p - y) x

Apply the chain rule from pp to zz to ww, using σ′(z)=p(1−p)\sigma'(z) = p(1-p) and ∂z/∂w=x\partial z/\partial w = x:

∂ℓ∂p=−yp+1−y1−p∂ℓ∂z=(−yp+1−y1−p) p(1−p)=−y(1−p)+(1−y)p=p−y\frac{\partial \ell}{\partial p} = -\frac{y}{p} + \frac{1-y}{1-p} \qquad \frac{\partial \ell}{\partial z} = \Big(-\frac{y}{p} + \frac{1-y}{1-p}\Big)\,p(1-p) = -y(1-p) + (1-y)p = p - y ∇wℓ=(p−y) x∂ℓ∂b=p−y\nabla_w \ell = (p - y)\,x \qquad \frac{\partial \ell}{\partial b} = p - y

The sigmoid’s p(1−p)p(1-p) cancels the denominators of the log, which is why log loss is the natural partner of the sigmoid. The same form holds for softmax with cross-entropy: the gradient on the logits is the softmax output minus the one-hot label (Dive into Deep Learning, Softmax regression).

Worked example: one step by hand

One example x=[1,2]x = [1,2], y=1y = 1, w=[0,0]w=[0,0], b=0b=0, learning rate 0.10.1. The score is 0, so p=0.5p = 0.5 and the error is −0.5-0.5. The gradient is −0.5⋅[1,2]=[−0.5,−1]-0.5\cdot[1,2] = [-0.5,-1] for the weights and −0.5-0.5 for the bias, so w=[0.05,0.10]w = [0.05, 0.10] and b=0.05b = 0.05. The new score is 0.300.30, p=0.574p = 0.574, and the log loss falls from 0.693 to 0.554. With y=0y = 0 every sign flips (w=[−0.05,−0.10]w=[-0.05,-0.10], p=0.426p = 0.426) and the loss falls by the same amount.

Why not squared error on a sigmoid?

Squared error on pp also has a gradient, but p(1−p)p(1-p) no longer cancels. For y=1y = 1, compare the gradient with respect to the score zz:

zzppCross-entropy gradient p−1p-1Squared-error gradient (p−1) p(1−p)(p-1)\,p(1-p)
-60.00247-0.99753-0.00246
-20.11920-0.88080-0.09248
00.50000-0.50000-0.12500
20.88080-0.11920-0.01252

At z=−6z=-6 the model is confidently wrong (it says 0.25% when the label is 1). Cross-entropy pushes back with a gradient near 1; squared error with 0.00246, about 400 times weaker, so learning nearly stalls exactly when it should be fastest. The shape is worse too: the second derivative of the squared-error loss in zz is negative for z=−6,−4,−2z=-6,-4,-2 (section 11 of the script), so the curve is not convex there. For the log loss the second derivative in zz is p(1−p)p(1-p), which is positive because 0<p<10<p<1.

For logistic regression the log loss is convex in the weights (the Hessian is ∑ipi(1−pi) xixi⊤\sum_i p_i(1-p_i)\,x_ix_i^{\top}, a sum of positive semi-definite matrices), so every local minimum is a global one. The minimum is unique only when the loss is strictly convex: with an L2 penalty, or with full-rank, non-separable data. Collinear columns leave a flat direction (many equally good weight vectors), and separable data has no finite minimiser at all.

Reading the weights, and a trap

The model is linear in the log-odds, log⁡p1−p=w⊤x+b\log\frac{p}{1-p} = w^{\top}x + b, so a one-unit rise in xjx_j multiplies the odds by ewje^{w_j} (2.01 for wj=0.7w_j = 0.7). The decision boundary w⊤x+b=0w^{\top}x+b=0 is linear, though transformed or interaction features make it non-linear in the original inputs. The 0.5 threshold is a default: set it from the costs of each mistake. Compare weights only on comparable scales, and do not read them causally.

The trap: perfectly separable data. If a line separates the classes, the loss approaches 0 as the weights grow, so there is no finite minimiser. On x=[−2,−1,1,2]x = [-2,-1,1,2], y=[0,0,1,1]y=[0,0,1,1] with learning rate 0.5 the weight is 1.557 after 10 steps, 3.376 after 100, 5.548 after 1,000 and 10.127 after 100,000. An L2 penalty of 0.1 settles it at 1.458 by step 100, so a penalty is common practice.

Choosing a loss

A loss is a statement about which mistakes are expensive. Compare them by how the penalty grows with the error.

Squared error versus absolute error

For a constant prediction, squared error is minimised by the mean and absolute error by the median: on [1,2,3,4,100][1,2,3,4,100] that is 22 against 3. In a line fit, take x=1,…,6x = 1,\dots,6 and y=2xy = 2x with the last label, 12, recorded as 40. Least squares gives y=−9.333+6xy = -9.333 + 6x (predicting −3.333-3.333 at x=1x=1, truth 2) and least absolute deviations gives y=2xy = 2x.

Huber loss is quadratic for small errors and linear for large ones. scikit-learn’s HuberRegressor “applies a linear loss to samples that are defined as outliers” and “does not ignore the effect of the outliers but gives a lesser weight to them” (scikit-learn, Linear models). In the form 12r2\tfrac12 r^2 for ∣r∣≤1|r|\le1 and ∣r∣−12|r|-\tfrac12 beyond, an error of 10 costs 9.5 rather than 50 (scikit-learn’s form is twice this). Before choosing a robust loss, ask why the outliers exist: a corrupted label is a data problem, and a real extreme value may be what the business needs forecast.

Losses for classification, by margin

Encode the label as y∈{−1,+1}y\in\{-1,+1\} and let f(x)f(x) be the raw score. The margin m=y f(x)m = y\,f(x) is positive when right and large when confidently right. scikit-learn defines the hinge as max⁡(0,1−m)\max(0, 1-m) and the log loss as log⁡(1+e−m)\log(1+e^{-m}) (scikit-learn, Stochastic gradient descent).

Margin mmHingeLog lossSquared (1−m)2(1-m)^2
-232.1279
-121.3134
010.6931
100.3130
200.1271

Below a margin of 1 both the hinge and the log loss charge a roughly linear penalty. Past 1 the hinge is exactly zero, so well-classified points stop mattering, while the log loss keeps a shrinking penalty. A squared loss on the margin is the wrong shape: it charges 1 at a margin of 2. The hinge (support vector machines) gives a score, not a probability. The log loss gives a probability, so use it when you threshold by cost or rank by risk. They sit behind SGDClassifier(loss="hinge") and loss="log_loss" (scikit-learn, Stochastic gradient descent).

Gradient descent and the learning rate

The update is w←w−η ∇wJ(w)w \leftarrow w - \eta\,\nabla_w J(w) with learning rate η\eta, the most important hyperparameter. Take J(w)=w2J(w)=w^2, gradient 2w2w, start w=1w=1. Each step multiplies ww by (1−2η)(1-2\eta):

Learning ratePath of ww over 5 stepsWhat happens
0.10.8, 0.64, 0.512, 0.4096, 0.3277Converges, slowly
0.50, 0, 0, 0, 0Lands on the minimum in one step (special to this curve)
1.0-1, 1, -1, 1, -1Oscillates forever, never improves
1.1-1.2, 1.44, -1.728, 2.0736, -2.4883Diverges, growing each step

For a quadratic with curvature hh, steps converge only if η<2/h\eta \lt 2/h; exactly 2/h2/h oscillates. The symptoms carry over to real losses: a loss that rises or turns NaN means the rate is too high (or inputs are huge, or a log of zero; gradient clipping from the deep learning lessons is another guard), one that barely moves means too low, and one that bounces at a plateau means the steps are too big to settle. Plot loss against steps.

Batch size. Full-batch descent is exact but slow per step, one row at a time (SGD) is cheap and noisy, and mini-batches are the default, with 32 to 256 cited as typical (Dive into Deep Learning). Noisy steps need a smaller or decaying rate, so batch size and learning rate are tuned together; scikit-learn’s SGD estimators default to decaying schedules (scikit-learn, Stochastic gradient descent). Step decay, cosine decay and warmup come with the deep learning lessons.

Momentum and Adam

On a long, narrow valley, plain gradient descent zigzags across the steep walls while crawling along the flat floor. In the textbook example 0.1x12+2x220.1x_1^2 + 2x_2^2, a small rate is safe in the steep direction but slow in the flat one, and a large rate speeds up the flat direction but diverges in the steep one (Dive into Deep Learning, Momentum).

Momentum keeps a velocity, a leaky sum of past gradients: v←βv+gv \leftarrow \beta v + g, then w←w−ηvw \leftarrow w - \eta v (Dive into Deep Learning, Momentum). Gradients that agree add up; gradients that flip across the walls cancel. With β=0\beta=0 it is plain descent. β\beta is a hyperparameter (0.9 is a common choice; PyTorch’s SGD defaults to momentum 0), and libraries differ on where the learning rate enters, so settings may not transfer (PyTorch, SGD).

Adam keeps running averages of the gradient (mm) and its square (vv) per parameter, and divides one by the root of the other, with bias correction for the early steps (PyTorch, Adam, introduced in Kingma and Ba, 2015):

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,w←w−η mt/(1−β1t)vt/(1−β2t)+ϵm_t = \beta_1 m_{t-1} + (1-\beta_1) g_t,\quad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2,\quad w \leftarrow w - \eta\,\frac{m_t/(1-\beta_1^t)}{\sqrt{v_t/(1-\beta_2^t)} + \epsilon}

PyTorch’s defaults are learning rate 0.001, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, ϵ=10−8\epsilon=10^{-8}. Adam is momentum (the mm term) combined with the RMSProp idea of scaling each parameter by its recent squared gradients (the vv term); AdamW, which applies weight decay separately from the gradient update, comes with the deep learning lessons. On the first step the corrected ratio is about ±1\pm1, so every parameter moves about η\eta whatever its gradient (the script prints a step of about 0.001 for gradients of 0.001, 1 and 100 at η=0.001\eta=0.001). That makes Adam forgiving of gradient scale, and it is widely used for neural networks, where gradients differ by orders of magnitude between layers (common practice, not a theorem).

What the numbers say

The valley f(w)=0.1w12+2w22f(w) = 0.1w_1^2 + 2w_2^2 from (5,3)(5,3), steps until f<10−6f \lt 10^{-6}, with the learning rate (and β\beta for momentum) searched on a grid:

MethodBest setting on the gridSteps
Gradient descentη=0.45\eta=0.4579
Momentumη=0.5\eta=0.5, β=0.5\beta=0.523
Adam (learning rate only searched; β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999 fixed)η=0.7\eta=0.7114

At η=0.5\eta=0.5 plain descent does not converge: the steep factor is 1−0.5⋅4=−11-0.5\cdot4=-1, exactly the limit 2/42/4, so it oscillates forever (ff stays at 18). At 0.51 it diverges. Momentum with β=0.9\beta=0.9 took 290, 126 and 122 steps at η=0.01,0.05,0.3\eta=0.01, 0.05, 0.3, slower than tuned plain descent, so momentum needs its β\beta tuned with η\eta. The Adam row is not tuned Adam, since its betas were not searched, and it did not beat tuned descent on this clean problem. Treat the optimizer as a hyperparameter.

Feature scaling

Gradient descent is slow when one direction is much steeper than another, and unscaled features create that. Steepness is set by the eigenvalues of X⊤X/nX^{\top}X/n, and their ratio is the condition number. With 200 rows, feature 1 in [0,1][0,1], feature 2 in [0,100][0,100], and the best fixed rate for each setting (more generous than real life), the median over 20 datasets of steps to get within 10−610^{-6} of the minimum was:

FeaturesMedian condition numberMedian steps (range)
Raw23,20096,865 (82,653 to 117,022)
Centred only9,76036,206.5 (30,977 to 40,429)
Standardised1.123 (2 to 4)

Gradient descent, penalties and distance-based methods need scaling. scikit-learn says SGD “is sensitive to feature scaling” and recommends scaling to [0,1][0,1] or [−1,1][-1,1] or standardising; features with an intrinsic scale may not need it (scikit-learn, Stochastic gradient descent). Trees split on thresholds, so order-preserving rescaling does not change their possible splits, and unpenalised closed-form least squares gives the same predictions either way. Fit the scaler on training data only, inside a pipeline, as in the previous lesson.

Debugging a run

Diagram: First split on whether the loss blows up or is NaN, which points to a too-high learning rate, unscaled inputs or a numerical bug such as...

yes

no

yes

no

Loss is not going down

NaN or exploding?

Lower the learning rate, scale inputs,
check log(0), clip gradients

Flat from the first step?

Rate too low, bug in the loss or labels,
unscaled features

Falls, then plateaus:
decay the rate, add features or capacity

Diagram summary: First split on whether the loss blows up or is NaN, which points to a too-high learning rate, unscaled inputs or a numerical bug such as log of zero, with gradient clipping as a guard. If it is flat from the start, suspect a too-low rate, a bug in the loss or labels, or unscaled features. If it falls and then levels off, the limit is the learning-rate schedule or the model.

A fast sanity check: try to drive the loss to about zero on a tiny batch of ten rows. If you cannot, there is a bug, not a tuning problem.

Code

This standard-library script produced every number in the lesson, using Fraction for exact parts and fixed seeds for random ones (Python 3.14; another version may draw different data in sections 7 and 12, moving exact step counts but not their orders of magnitude). It runs in about a second.

Python

import itertools
import math
import random
import statistics
from fractions import Fraction as Fr


def sigmoid(z):
    if z >= 0:
        return 1 / (1 + math.exp(-z))
    e = math.exp(z)
    return e / (1 + e)


# 1. Normal equation, exact: fit y = b + w*x to three points
xs, ys = [Fr(1), Fr(2), Fr(3)], [Fr(2), Fr(4), Fr(5)]
n, sx, sxx = len(xs), sum(xs), sum(x * x for x in xs)
sy, sxy = sum(ys), sum(x * y for x, y in zip(xs, ys))
det = n * sxx - sx * sx
b, w = (sxx * sy - sx * sxy) / det, (n * sxy - sx * sy) / det
res = [y - (b + w * x) for x, y in zip(xs, ys)]
print("1. normal equation: b =", b, "w =", w, "residuals =", [str(r) for r in res],
      "sum =", sum(res), "sum x*r =", sum(x * r for x, r in zip(xs, res)),
      "mse =", sum(r * r for r in res) / n)


# 2. Outliers: mean versus median, and OLS versus least absolute deviations
data = [1, 2, 3, 4, 100]
print("2a. mean", statistics.fmean(data), "median", statistics.median(data))
X6 = [Fr(i) for i in range(1, 7)]
Y6 = [Fr(2 * i) for i in range(1, 7)]
Y6[5] = Fr(40)                                   # one corrupted label: 12 became 40


def ols(xs, ys):
    n, sx, sy = len(xs), sum(xs), sum(ys)
    sxx, sxy = sum(x * x for x in xs), sum(x * y for x, y in zip(xs, ys))
    d = n * sxx - sx * sx
    return (sxx * sy - sx * sxy) / d, (n * sxy - sx * sy) / d


def lad(xs, ys):
    """Least absolute deviations: an optimum passes through two data points."""
    best = None
    for i, j in itertools.combinations(range(len(xs)), 2):
        w = (ys[j] - ys[i]) / (xs[j] - xs[i])
        b = ys[i] - w * xs[i]
        cost = sum(abs(y - (b + w * x)) for x, y in zip(xs, ys))
        if best is None or cost < best[0]:
            best = (cost, b, w)
    return best


b_o, w_o = ols(X6, Y6)
cost, b_l, w_l = lad(X6, Y6)
print("2b. OLS: intercept %.3f slope %s, prediction at x=1 is %.3f" % (b_o, w_o, b_o + w_o))
print("2c. LAD: intercept %s slope %s, total absolute error %s" % (b_l, w_l, cost))


# 3. One logistic gradient step by hand, for y = 1 and y = 0
for y in (1, 0):
    x, w, b, lr = [1, 2], [0.0, 0.0], 0.0, 0.1
    p = sigmoid(sum(a * c for a, c in zip(w, x)) + b)
    w = [a - lr * (p - y) * c for a, c in zip(w, x)]
    b -= lr * (p - y)
    z2 = sum(a * c for a, c in zip(w, x)) + b
    loss = lambda q: -(y * math.log(q) + (1 - y) * math.log(1 - q))
    print("3. y=%d: p=0.5 -> w=%s b=%.2f z=%.2f p=%.3f, loss 0.693 -> %.3f"
          % (y, [round(a, 2) for a in w], b, z2, sigmoid(z2), loss(sigmoid(z2))))


# 4. Why not squared error on a sigmoid: gradient with respect to the logit z, label y = 1
print("4. z, p, cross-entropy gradient, squared-error gradient")
for z in (-6, -2, 0, 2):
    p = sigmoid(z)
    print("  ", z, round(p, 5), round(p - 1, 5), round((p - 1) * p * (1 - p), 5))


# 5. Losses as a function of the margin m = y * f(x), y in {-1, +1}
print("5. margin, hinge, log loss, squared")
for m in (-2, -1, 0, 1, 2):
    print("  ", m, max(0, 1 - m), round(math.log(1 + math.exp(-m)), 3), (1 - m) ** 2)

# 6. Learning rate on J(w) = w^2, gradient 2w, start at w = 1
print("6. learning rate: w after 0..5 steps")
for lr in (0.1, 0.5, 1.0, 1.1):
    w, trace = 1.0, [1.0]
    for _ in range(5):
        w -= lr * 2 * w
        trace.append(round(w, 4))
    print("  ", lr, trace)


# 7. Feature scaling: steps of gradient descent on least squares (quadratic, so exact)
def make(seed, n=200):
    r = random.Random(seed)
    X = [[r.random(), r.random() * 100] for _ in range(n)]
    y = [3 * a + 0.05 * c + r.gauss(0, 0.1) for a, c in X]
    return X, y


def moments(X, y):
    n = len(X)
    H = [[sum(r[i] * r[j] for r in X) / n for j in range(2)] for i in range(2)]
    c = [sum(r[i] * t for r, t in zip(X, y)) / n for i in range(2)]
    return H, c


def steps_to_converge(H, c, tol=1e-6, cap=10**7):
    a, bb, d = H[0][0], H[0][1], H[1][1]
    mid, rad = (a + d) / 2, math.sqrt(((a - d) / 2) ** 2 + bb * bb)
    lo, hi = mid - rad, mid + rad                  # eigenvalues of X'X/n
    lr = 1 / (lo + hi)                             # best fixed step for this quadratic
    det = a * d - bb * bb
    star = [(d * c[0] - bb * c[1]) / det, (a * c[1] - bb * c[0]) / det]
    w = [0.0, 0.0]
    for k in range(cap):
        e = [w[0] - star[0], w[1] - star[1]]
        gap = e[0] * (a * e[0] + bb * e[1]) + e[1] * (bb * e[0] + d * e[1])
        if gap < tol:
            return k, hi / lo
        w = [w[0] - lr * 2 * (a * e[0] + bb * e[1]), w[1] - lr * 2 * (bb * e[0] + d * e[1])]
    return None, hi / lo


def center(X):
    mu = [statistics.fmean(col) for col in zip(*X)]
    return [[v - m for v, m in zip(r, mu)] for r in X]


def standardize(X):
    cols = list(zip(*X))
    mu = [statistics.fmean(c) for c in cols]
    sd = [statistics.pstdev(c) for c in cols]
    return [[(v - m) / s for v, m, s in zip(r, mu, sd)] for r in X]


results = {"raw": [], "centred": [], "standardised": []}
for seed in range(20):
    X, y = make(seed)
    yc = [t - statistics.fmean(y) for t in y]
    for name, Z, t in (("raw", X, y), ("centred", center(X), yc), ("standardised", standardize(X), yc)):
        results[name].append(steps_to_converge(*moments(Z, t)))
print("7. median steps and condition number over 20 seeds (range of steps)")
for name, rows in results.items():
    ks = [k for k, _ in rows]
    print("  ", name, statistics.median(ks), "cond %.3g" % statistics.median(c for _, c in rows),
          "range", min(ks), max(ks))


# 8. Plain GD, momentum and Adam on f(w) = 0.1*w1^2 + 2*w2^2, start (5, 3)
def f(w):
    return 0.1 * w[0] ** 2 + 2 * w[1] ** 2


def grad(w):
    return [0.2 * w[0], 4 * w[1]]


def run(step, cap=20000, tol=1e-6):
    w, st = [5.0, 3.0], {}
    for k in range(cap):
        if f(w) < tol:
            return k
        w = step(w, st)
        if not f(w) < 1e12:
            return None
    return None


def gd(lr):
    return lambda w, st: [a - lr * g for a, g in zip(w, grad(w))]


def momentum(lr, beta):
    def step(w, st):
        v = st.get("v", [0.0, 0.0])
        st["v"] = [beta * vi + g for vi, g in zip(v, grad(w))]
        return [a - lr * vi for a, vi in zip(w, st["v"])]
    return step


def adam(lr, b1=0.9, b2=0.999, eps=1e-8):
    def step(w, st):
        t = st["t"] = st.get("t", 0) + 1
        g = grad(w)
        m = st["m"] = [b1 * a + (1 - b1) * gi for a, gi in zip(st.get("m", [0, 0]), g)]
        v = st["v"] = [b2 * a + (1 - b2) * gi * gi for a, gi in zip(st.get("v", [0, 0]), g)]
        return [wi - lr * (mi / (1 - b1 ** t)) / (math.sqrt(vi / (1 - b2 ** t)) + eps)
                for wi, mi, vi in zip(w, m, v)]
    return step


LRS = (0.01, 0.03, 0.05, 0.1, 0.2, 0.3, 0.45, 0.5, 0.7, 1.0)


def best(make_step, settings):
    """Fewest steps over a grid of settings, skipping runs that diverge or stall."""
    runs = [(run(make_step(*s)), s) for s in settings]
    return min((k, s) for k, s in runs if k is not None)


print("8. fewest steps until f < 1e-6 over a grid of learning rates (and betas)")
print("   GD:", best(gd, [(lr,) for lr in LRS]))
print("   momentum:", best(momentum, [(lr, b) for lr in LRS for b in (0.5, 0.8, 0.9, 0.95)]))
print("   Adam:", best(adam, [(lr,) for lr in LRS]))
print("   momentum, beta 0.9, across lr:", {lr: run(momentum(lr, 0.9)) for lr in (0.01, 0.05, 0.3)})


def final_loss(step, n=200):
    w, st = [5.0, 3.0], {}
    for _ in range(n):
        w = step(w, st)
    return f(w)


print("   f after 200 steps of GD: eta=0.5 ->", final_loss(gd(0.5)), " eta=0.51 ->", "%.3g" % final_loss(gd(0.51)))
print("   (the steep factor is 1 - 4*eta: -1 at 0.5, so it oscillates; -1.04 at 0.51, so it diverges)")
print("   only the learning rate was searched for Adam; its betas stayed at 0.9 and 0.999")

# 9. Adam's first step is about lr whatever the gradient scale (b1 = 0.9, b2 = 0.999)
print("9. Adam first step at lr=0.001")
for g in (0.001, 1.0, 100.0):
    m_hat = (0.1 * g) / (1 - 0.9)
    v_hat = (0.001 * g * g) / (1 - 0.999)
    print("  ", g, 0.001 * m_hat / (math.sqrt(v_hat) + 1e-8))

# 10. Separable data: the weight never stops growing without a penalty
X1, Y1 = [-2, -1, 1, 2], [0, 0, 1, 1]
for lam in (0.0, 0.1):
    w, seen = 0.0, {}
    for t in range(1, 100001):
        g = sum((sigmoid(w * x) - y) * x for x, y in zip(X1, Y1)) / 4 + lam * w
        w -= 0.5 * g
        if t in (10, 100, 1000, 10000, 100000):
            seen[t] = round(w, 3)
    print("10. L2 =", lam, seen)
print("odds ratio for w = 0.7:", round(math.exp(0.7), 2))


# 11. Curvature (second difference) of each loss in the logit z, label y = 1
def curvature(F, z, h=1e-3):
    return (F(z + h) - 2 * F(z) + F(z - h)) / h ** 2


print("11. curvature in z: squared error on a sigmoid, cross-entropy")
for z in (-6, -4, -2, 0, 2):
    print("  ", z, round(curvature(lambda t: 0.5 * (1 - sigmoid(t)) ** 2, z), 5),
          round(curvature(lambda t: -math.log(sigmoid(t)), z), 5))


# 12. Two strongly correlated features: the coefficients move, the prediction does not
def fit2(seed, n=50):
    r = random.Random(seed)
    x1 = [r.uniform(50, 150) for _ in range(n)]
    x2 = [0.9 * a + r.gauss(0, 1) for a in x1]            # a second measure of nearly the same thing
    y = [3 * a + r.gauss(0, 5) for a in x1]               # only x1 truly matters
    cols = [[1.0] * n, x1, x2]
    A = [[sum(p * q for p, q in zip(u, v)) for v in cols] for u in cols]
    rhs = [sum(p * t for p, t in zip(u, y)) for u in cols]
    for c in range(3):                                    # Gaussian elimination, floats
        p = max(range(c, 3), key=lambda i: abs(A[i][c]))
        A[c], A[p], rhs[c], rhs[p] = A[p], A[c], rhs[p], rhs[c]
        for i in range(c + 1, 3):
            m = A[i][c] / A[c][c]
            A[i] = [u - m * v for u, v in zip(A[i], A[c])]
            rhs[i] -= m * rhs[c]
    w = [0.0] * 3
    for i in (2, 1, 0):
        w[i] = (rhs[i] - sum(A[i][k] * w[k] for k in range(i + 1, 3))) / A[i][i]
    return w


print("12. coefficients (intercept, x1, x2) and prediction at x1=100, x2=90")
for seed in (1, 2, 3):
    w = fit2(seed)
    print("  ", seed, [round(v, 2) for v in w], round(w[0] + 100 * w[1] + 90 * w[2], 1))

What to look for: section 4 (squared-error gradient collapsing at z=−6z=-6), section 7 (steps for raw, centred, standardised features), section 8 (tuned momentum beats tuned descent, Adam does not), section 12 (correlated features swing their coefficients while the prediction stays near 300). The scikit-learn equivalents are LinearRegression, LogisticRegression, HuberRegressor and SGDClassifier inside make_pipeline(StandardScaler(), ...).

Real-World Application

A sound tabular default is to scale the features, fit a regularised logistic or linear regression, and read the validation metric: it trains in seconds and sets the bar a heavier model must beat. Choose the loss from the cost of mistakes and the quality of the data, and when a run misbehaves use the debugging flow before changing the model.

Interview Perspective

Expect “derive the gradient of logistic regression”, “why log loss and not MSE”, “closed form versus gradient descent”, “what happens on separable data”, “explain momentum and Adam” and “your loss is NaN, what do you do”. A strong answer states the setup, derives with the chain rule and names the cancellation, then adds a limit or production caveat. A weak answer says “Adam is better” without saying what it changes.

Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.

Practice Questions

  • Basic: Write the logistic regression loss and its gradient with respect to the weights.
  • Intermediate: A linear regression on 50,000 rows and 20 features. Normal equation or gradient descent? What changes at 50 million rows and 20,000 features?
  • Advanced: Why does an unpenalised logistic regression on separable data not converge, and what are two fixes?
  • Product-Company (Generated practice): Training loss goes to NaN after 200 steps with Adam at learning rate 0.1. List what you check, in order.

Activity

Repeat the one-step example by hand with learning rate 0.5 and y=1y=1. Then compute the squared-error gradient with respect to zz at z=−4z=-4 and compare it with the cross-entropy gradient. Finally, change the script’s section 6 to try learning rates 0.9 and 1.05 on w2w^2 and say which converge.

Homework

Implement logistic regression from scratch: a stable sigmoid, the log loss, the gradient and a gradient descent loop with an optional L2 penalty. The code is in homework/; run the tests until they pass.

Quick Revision

  • Model, loss, optimizer: change one piece and you have a different algorithm.
  • Normal equation: w=(X⊤X)−1X⊤yw=(X^{\top}X)^{-1}X^{\top}y, exact, costs O(nd2)O(nd^2), unstable with collinear columns. Gradient descent scales and generalises.
  • Log loss gradient is (p−y)x(p-y)x because the sigmoid’s p(1−p)p(1-p) cancels. Squared error on a sigmoid stalls when confidently wrong and is not convex.
  • Squared error follows the mean and hates outliers; absolute error follows the median; Huber is between. Hinge ignores points past margin 1; log loss gives probabilities.
  • Learning rate: too high diverges, exactly at the limit oscillates, too low crawls. Momentum and Adam need tuning.
  • Standardise features before gradient descent or penalties, fitted on training data only.

Check yourself

  • Walk-through: Without notes, derive ∂ℓ/∂z=p−y\partial\ell/\partial z = p-y for the log loss.
  • Variation: Your regression labels contain a few wildly wrong values. Which loss would you try, and what would you check before trusting it?
  • Common misconception: “Adam always converges faster than SGD”, and “momentum 0.9 is always an improvement”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Further reading

Research papers

Hands-on

More for this module: ML foundations resources

Practice

Test what you just read. Quizzes and cards are grouped by module: ML foundations.

Check yourself13 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 13 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveDerive the gradient (p - y) x of the log loss for logistic regression, and explain why cross-entropy rather than squared error is paired with a sigmoid.

  1. Question 1 of 13A logistic regression predicts p = 0.9 for a training example whose true label is y = 0 and whose features are x = [2, -1]. What is the log-loss gradient with respect to the weights for this one example?

    Choose one answer.

  2. Question 2 of 13A teammate trains a binary classifier by passing the sigmoid output through mean squared error instead of log loss. Early in training many examples are confidently wrong (p near 0 when y = 1). What do you expect to see?

    Choose one answer.

  3. Question 3 of 13Which of these statements about logistic regression are true? Select all that apply.

    Choose all that apply.

ObjectiveSolve linear regression with the normal equation and with gradient descent, and say when each is the right tool and what collinear features do.

  1. Question 4 of 13You want a linear regression on 5 million rows and 200,000 sparse bag-of-words features. A colleague proposes the normal equation because it is exact and needs no learning rate. What is the best response?

    Choose one answer.

  2. Question 5 of 13Two features describe a home: x1 is floor area and x2 is living area, about 0.9 times x1 plus a little noise. Three fits on fresh samples of 50 homes give (x1, x2) coefficients of (3.36, -0.39), (4.28, -1.39) and (2.91, 0.13), yet predictions at x1 = 100, x2 = 90 are 300.3, 300.6 and 299.0. What explains this?

    Choose one answer.

  3. Question 6 of 13Fit y = b + w x by least squares to the points x = [1, 2, 3, 4] and y = [1, 3, 2, 4]. Here the sums are sum x = 10, sum x^2 = 30, sum y = 10 and sum xy = 29. What is the slope w?

    Choose one answer.

ObjectiveChoose a loss for a task (squared error, absolute error, Huber, cross-entropy, hinge) by what it penalises, and predict how each reacts to an outlier or a confident mistake.

  1. Question 7 of 13A lender needs an estimated probability of default for each applicant, so it can set a decision threshold from the cost of a bad loan. A data scientist proposes training a linear classifier with hinge loss because it gives a clean margin. What is the problem?

    Choose one answer.

  2. Question 8 of 13You must report one typical value for the daily order counts [10, 12, 11, 13, 500], where 500 is a real but rare promotion day. Which pair gives the value that minimises squared error and the value that minimises absolute error?

    Choose one answer.

  3. Question 9 of 13Which statements about Huber loss are true? Select all that apply.

    Choose all that apply.

ObjectiveExplain how the learning rate, batch size, momentum, Adam and feature scaling change a gradient descent run, and diagnose a run that diverges, crawls or oscillates.

  1. Question 10 of 13You train linear regression with gradient descent on a table with house area in square feet (about 1,000 to 4,000) and number of bedrooms (1 to 5). The loss goes 0.7, 0.4, 3.1, 40, 5,000, then NaN. Which response addresses the cause?

    Choose one answer.

  2. Question 11 of 13Adam is run at learning rate 0.001 on two parameters. On the first step one gradient is 0.002 and the other is 200. About how far does each parameter move?

    Choose one answer.

  3. Question 12 of 13A teammate has tuned plain gradient descent on a narrow valley (best: 79 steps at learning rate 0.45). They add momentum with beta 0.9 and expect faster convergence. In the lesson's grid, beta 0.9 took 122 to 290 steps. What conclusion fits?

    Choose one answer.

  4. Question 13 of 13A mini-batch run with a constant learning rate of 0.1 falls quickly, then the loss bounces within a band and does not settle, even after many epochs. What is the most sensible next step?

    Choose one answer.