Linear models, loss functions and gradient descent
- Beginner
- 1 h
- Lesson 2 of 2 in ML foundations
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
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.
| Task | Output | Typical loss | Why this pairing |
|---|---|---|---|
| Regression | Linear, any real number | Squared error (MSE) | Maximum likelihood under Gaussian noise |
| Regression with outliers | Linear | Absolute error or Huber | A mistake grows linearly, not quadratically |
| Binary classification | Sigmoid, a probability | Binary cross-entropy (log loss) | Maximum likelihood for a Bernoulli label |
| Multiclass | Softmax, one probability per class | Cross-entropy | Maximum likelihood for a categorical label |
| Margin classifier (SVM) | Raw score | Hinge | Only 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.
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 , where each row of is an example and a column of ones carries the intercept. The loss is the mean squared error . 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:
The middle form says the residual is orthogonal to every column of : no feature can still explain what is left over.
Worked example: three points, solved exactly
Fit to , . With the column of ones, and . The determinant is , so and . The residuals are . They sum to 0 and , the orthogonality condition. The mean squared error is . 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 (scikit-learn, Linear models). Forming costs and solving it . With 200,000 features 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 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 rather than literally inverting . 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 , since training never falls when a feature is added under least squares with an intercept.
Logistic regression and the gradient
For a label we want a probability, so the linear score goes through the sigmoid:
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):
Derivation: why the gradient is (p - y) x
Apply the chain rule from to to , using and :
The sigmoid’s 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 , , , , learning rate . The score is 0, so and the error is . The gradient is for the weights and for the bias, so and . The new score is , , and the log loss falls from 0.693 to 0.554. With every sign flips (, ) and the loss falls by the same amount.
Why not squared error on a sigmoid?
Squared error on also has a gradient, but no longer cancels. For , compare the gradient with respect to the score :
| Cross-entropy gradient | Squared-error gradient | ||
|---|---|---|---|
| -6 | 0.00247 | -0.99753 | -0.00246 |
| -2 | 0.11920 | -0.88080 | -0.09248 |
| 0 | 0.50000 | -0.50000 | -0.12500 |
| 2 | 0.88080 | -0.11920 | -0.01252 |
At 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 is negative for (section 11 of the script), so the curve is not convex there. For the log loss the second derivative in is , which is positive because .
For logistic regression the log loss is convex in the weights (the Hessian is , 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, , so a one-unit rise in multiplies the odds by (2.01 for ). The decision boundary 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 , 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 that is 22 against 3. In a line fit, take and with the last label, 12, recorded as 40. Least squares gives (predicting at , truth 2) and least absolute deviations gives .
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 for and 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 and let be the raw score. The margin is positive when right and large when confidently right. scikit-learn defines the hinge as and the log loss as (scikit-learn, Stochastic gradient descent).
| Margin | Hinge | Log loss | Squared |
|---|---|---|---|
| -2 | 3 | 2.127 | 9 |
| -1 | 2 | 1.313 | 4 |
| 0 | 1 | 0.693 | 1 |
| 1 | 0 | 0.313 | 0 |
| 2 | 0 | 0.127 | 1 |
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 with learning rate , the most important hyperparameter. Take , gradient , start . Each step multiplies by :
| Learning rate | Path of over 5 steps | What happens |
|---|---|---|
| 0.1 | 0.8, 0.64, 0.512, 0.4096, 0.3277 | Converges, slowly |
| 0.5 | 0, 0, 0, 0, 0 | Lands on the minimum in one step (special to this curve) |
| 1.0 | -1, 1, -1, 1, -1 | Oscillates forever, never improves |
| 1.1 | -1.2, 1.44, -1.728, 2.0736, -2.4883 | Diverges, growing each step |
For a quadratic with curvature , steps converge only if ; exactly 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 , 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: , then (Dive into Deep Learning, Momentum). Gradients that agree add up; gradients that flip across the walls cancel. With it is plain descent. 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 () and its square () 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):
PyTorch’s defaults are learning rate 0.001, , , . Adam is momentum (the term) combined with the RMSProp idea of scaling each parameter by its recent squared gradients (the 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 , so every parameter moves about whatever its gradient (the script prints a step of about 0.001 for gradients of 0.001, 1 and 100 at ). 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 from , steps until , with the learning rate (and for momentum) searched on a grid:
| Method | Best setting on the grid | Steps |
|---|---|---|
| Gradient descent | 79 | |
| Momentum | , | 23 |
| Adam (learning rate only searched; , fixed) | 114 |
At plain descent does not converge: the steep factor is , exactly the limit , so it oscillates forever ( stays at 18). At 0.51 it diverges. Momentum with took 290, 126 and 122 steps at , slower than tuned plain descent, so momentum needs its tuned with . 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 , and their ratio is the condition number. With 200 rows, feature 1 in , feature 2 in , and the best fixed rate for each setting (more generous than real life), the median over 20 datasets of steps to get within of the minimum was:
| Features | Median condition number | Median steps (range) |
|---|---|---|
| Raw | 23,200 | 96,865 (82,653 to 117,022) |
| Centred only | 9,760 | 36,206.5 (30,977 to 40,429) |
| Standardised | 1.12 | 3 (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 or 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
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.
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 ), 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 . Then compute the squared-error gradient with respect to at 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 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: , exact, costs , unstable with collinear columns. Gradient descent scales and generalises.
- Log loss gradient is because the sigmoid’s 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 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
A short, interactive chapter that plots the narrow-valley problem and shows exactly how momentum changes the path.
Research papers
Adam: A Method for Stochastic Optimization (opens in a new tab)
The original Adam paper, for the bias-correction argument and the convergence analysis. Read it after you can write the update from memory.
Hands-on
Stochastic Gradient Descent (scikit-learn user guide) (opens in a new tab)
The practical-tips section is a good checklist: scaling, learning-rate schedules and when to stop.
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.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.