Module contents
Lesson 2 of 24Review 75 min

Linear regression: least squares, likelihood and iterative training

A dense review of linear regression as the first supervised learner, bringing together least squares as projection (m02), stable numerical solutions (m09), and statistical inference (m05). Its machine-learning focus covers least squares as maximum likelihood under a noise model, centering and standardization, and iterative training with gradient descent and LMS when data do not fit in memory or arrive as a stream.

After this lesson you can

  • Formulate linear regression as empirical squared-error minimization and recall its normal-equation and projection solutions.
  • Prove that least squares is maximum likelihood under homoscedastic Gaussian noise, estimate σ², and derive the estimator for Laplace noise.
  • Center and standardize variables using training statistics and undo the transformation to interpret coefficients on the original scale.
  • Fit the model with gradient descent, minibatches, and the LMS rule, relating the maximum learning rate and convergence speed to the spectrum of XᵀX/n.
  • Reproduce the implementation using scikit-learn and statsmodels and identify the solver each uses.

Before you start

Motivation: the model beneath almost everything

Linear regression is the first supervised learner you study and the last one you leave behind. The world is not linear, but almost every model you will see builds something on top of this one:

  • Kernels and basis expansions. f(x)=w⊤ϕ(x)+bf(\vb{x}) = \vb{w}\T\phi(\vb{x}) + b is linear in w\vb{w} even if ϕ\phi is arbitrarily nonlinear. Everything in this lesson applies directly to polynomials, splines, and the kernel trick.
  • Generalized linear models. Logistic and Poisson regression pass a linear predictor w⊤x+b\vb{w}\T\vb{x} + b through a link function (GLM); logistic regression appears four lessons from now.
  • A network’s last layer. A network predicting a number with squared error ends in a linear layer over features learned by earlier layers: exactly this model, trained with the same stochastic descent (the output-layer and loss pairing makes it explicit).
  • Quantitative finance. CAPM and factor models are estimated by regressing an asset’s returns on portfolio returns.
  • The baseline. A complicated model is not justified until it beats well-executed linear regression (properly encoded and scaled features, honest validation). Otherwise the complexity is not paying off.

You already have almost all the pieces from other topics. This lesson’s distinctive contribution is the machine-learning perspective: why squares (least squares is maximum likelihood under one particular noise model; another noise model yields another estimator), what to do about scales (center and standardize without leaking information from the test set, then undo the transformation to read coefficients), and how to train when the problem cannot be solved all at once: gradient descent, minibatches and the LMS rule, whose maximum rate and speed depend on the spectrum of X⊤X/n\mat{X}\T\mat{X}/n.

What you already know, in one paragraph

Given X∈Rn×p\mat{X} \in \R^{n\times p} and y∈Rn\vb{y} \in \R^n, the least-squares problem min⁡β∥y−Xβ∥2\min_{\vb{\beta}} \norm{\vb{y} - \mat{X}\vb{\beta}}^2 has as solutions those of the normal equations X⊤Xβ=X⊤y\mat{X}\T\mat{X}\vb{\beta} = \mat{X}\T\vb{y}; geometrically, y^=Xβ^\hat{\vb{y}} = \mat{X}\hat{\vb{\beta}} is the orthogonal projection of y\vb{y} onto col⁡(X)\col(\mat{X}), and residual r=y−y^\vb{r} = \vb{y} - \hat{\vb{y}} is perpendicular to every column, X⊤r=0\mat{X}\T\vb{r} = \vb{0}. If rank⁡X=p\rank\mat{X} = p the solution is unique; otherwise an affine subspace of solutions shares the same y^\hat{\vb{y}} and the minimum-norm solution is X+y\mat{X}\pinv\vb{y}. Numerically, solve with QR or SVD, never by forming the inverse of X⊤X\mat{X}\T\mat{X}, whose condition number is the square of that of X\mat{X}. With an additional statistical model for errors, the Gaussian linear model gives the distribution of β^\hat{\vb{\beta}}, the Gauss–Markov theorem and diagnostic tools.

With n=3n = 3 observations and two columns this all fits in one figure: each observation is an axis of R3\R^3, vector y\vb{y} is a point in space, and col⁡(X)\col(\mat{X}) is a plane.

InteractiveRegression as projection
  • y\vb{y}
  • y^=Xβ^\hat{\vb{y}} = \mat{X}\hat{\beta}
  • residual r\vb{r}
  • column 1\vb{1}
  • column x\vb{x}
  • col⁡(X)\operatorname{col}(\mat{X})
The same three observations as points (xi,yi)(x_i, y_i) and the fitted line
123
Responses y\vb{y}
0.30
2.80
1.60
1.00
x\vb{x}(−1.00, 0.50, 2.00)
β^=(b,w)\hat{\beta} = (b, w)(1.350, 0.433)
y^\hat{\vb{y}}(0.92, 1.57, 2.22)
X⊤r\mat{X}\T\vb{r}(0.0000, 0.0000)
∥r∥2\norm{\vb{r}}^22.282
κ(X⊤X)\kappa(\mat{X}\T\mat{X})2.7
The residual is perpendicular to the plane: X⊤r=0\mat{X}\T\vb{r} = \vb{0} (the normal equations).
Above, R3\R^3 with one axis per observation: X=[1  x]\mat{X} = [\vb{1}\;\vb{x}] spans the shaded plane, y^\hat{\vb{y}} is the foot of the perpendicular from y\vb{y}, and the residual (dashed) meets the plane at a right angle. Below, the same three observations as points (xi,yi)(x_i, y_i): the three vertical segments are the components of r\vb{r}. Drag y\vb{y} and check that X⊤r\mat{X}\T\vb{r} remains zero. Then reduce the spread of xx: the columns become almost parallel, κ(X⊤X)\kappa(\mat{X}\T\mat{X}) shoots up and the slope becomes unstable; at spread 0 the plane collapses to a line, y^\hat{\vb{y}} remains unique, and an entire family of equally good lines appears.

The last step shows the difference between the two objects least squares produces. The prediction y^\hat{\vb{y}} is always unique, because projection onto a subspace is unique. The coefficients need not be: at spread 0, x=0.5⋅1\vb{x} = 0.5\cdot\vb{1} and any line through (0.5,yˉ)(0.5, \bar y) gives the same fitted values. np.linalg.lstsq then returns the minimum-norm solution, which the figure draws. Near that case, with almost parallel columns, the solution exists and is unique but ill-conditioned: a small change in y\vb{y} moves the slope a great deal while barely moving y^\hat{\vb{y}}. If coefficients are your concern, this is a statistical problem (their variance explodes) as well as a numerical one; if you only care about prediction, much less so.

A cell illustrates the numerical warning. Consider a degree-10 polynomial fit on [0,1][0, 1], where columns 1,x,…,x101, x, \dots, x^{10} are nearly dependent, and noise-free data whose exact solution is known:

[ ]Why XᵀX is not invertedBrowser
import numpy as np

rng = np.random.default_rng(0)
x = np.linspace(0, 1, 200)
X = np.vander(x, 11, increasing=True)            # columnas 1, x, ..., x^10
beta = rng.normal(size=11)
y = X @ beta                                     # sin ruido: la solución exacta es beta

def error(b):
    return np.linalg.norm(b - beta) / np.linalg.norm(beta)

b_inv = np.linalg.inv(X.T @ X) @ (X.T @ y)       # lo que no hay que hacer
b_solve = np.linalg.solve(X.T @ X, X.T @ y)      # ecuaciones normales sin inversa explícita
Q, R = np.linalg.qr(X)
b_qr = np.linalg.solve(R, Q.T @ y)               # QR: R es triangular
b_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]   # SVD (LAPACK gelsd)

print(f"kappa(X) = {np.linalg.cond(X):.1e}   kappa(XᵀX) = {np.linalg.cond(X.T @ X):.1e}")
for nombre, b in [("inv(XᵀX) Xᵀy", b_inv), ("solve(XᵀX, Xᵀy)", b_solve), ("QR", b_qr), ("lstsq", b_lstsq)]:
    print(f"{nombre:17s} error relativo en beta = {error(b):.1e}   norma del residuo = {np.linalg.norm(X @ b - y):.1e}")

Forming X⊤X\mat{X}\T\mat{X} raises the condition number from 2.2×1072.2\times 10^{7} to 4.8×10144.8\times 10^{14} and loses precision with it: the explicit inverse gives coefficients with 3.6% error and residual 4×10−34\times 10^{-3} in a problem whose exact residual is 0; solving the system without inversion leaves coefficient error 2×10−32\times 10^{-3}; QR or SVD, which work on X\mat{X} without squaring anything, give about 10−1110^{-11}. With well-conditioned data the difference is invisible, which is why this mistake survives in so much code.

The model and design matrix

When no distinction is needed, we write X\mat{X} and β\vb{\beta} with the intercept included. Three observations about the definition:

The intercept is not optional. Without it, the line is forced through the origin, and there is almost never a reason for that. Moreover, R2R^2 for a fit without an intercept is computed relative to zero rather than the mean, so it can be very high for a poor model: you will see this with statsmodels in the lab, where forgetting add_constant gives R2=0.90R^2 = 0.90 versus 0.550.55 for the correct model.

Linear in parameters, not in variables. Nothing prevents the columns of X\mat{X} from being x2x^2, log⁡x\log x, x1x2x_1 x_2, or the sine of a date: the model remains linear in β\vb{\beta} and everything below applies unchanged. This freedom is the basis expansion of the next lesson. Categorical variables enter through one-hot encoding: one indicator column per category. With an intercept, remove one (the reference category), because the KK indicators sum exactly to the column of ones and X\mat{X} loses rank: this is the collinear case in the figure, with infinitely many coefficients and one prediction.

Prediction does not require the same assumptions as inference. Very little is needed to use the model as a predictor. If (x,y)(\vb{x}, y) has finite second moments and R=E[xx⊤]\mat{R} = \E[\vb{x}\vb{x}\T] is invertible (with the 1 included in x\vb{x}), the best linear predictor under squared error,

β⋆=arg min⁡βE[(y−β⊤x)2]=R−1E[x y],\vb{\beta}^\star = \argmin_{\vb{\beta}} \E\big[(y - \vb{\beta}\T\vb{x})^2\big] = \mat{R}\inv\E[\vb{x}\,y],

exists and is unique, and β^\hat{\vb{\beta}} converges to it by the law of large numbers, because β^=(1nX⊤X)−11nX⊤y\hat{\vb{\beta}} = (\tfrac1n\mat{X}\T\mat{X})\inv\tfrac1n\mat{X}\T\vb{y} is the same formula with sample means. The proof is the same orthogonality as before in L2L^2: for any β\vb{\beta}, E[(y−β⊤x)2]=E[(y−β⋆Tx)2]+(β−β⋆)⊤R(β−β⋆)\E[(y - \vb{\beta}\T\vb{x})^2] = \E[(y - \vb{\beta}^{\star\mathsf{T}}\vb{x})^2] + (\vb{\beta} - \vb{\beta}^\star)\T\mat{R}(\vb{\beta} - \vb{\beta}^\star), because the cross term is 2(β⋆−β)⊤E[x(y−x⊤β⋆)]=02(\vb{\beta}^\star - \vb{\beta})\T\E[\vb{x}(y - \vb{x}\T\vb{\beta}^\star)] = 0 by the definition of β⋆\vb{\beta}^\star. None of this assumes that E[y∣x]\E[y \given \vb{x}] is linear, Gaussian noise, or constant variance: if the relationship is nonlinear, β⋆\vb{\beta}^\star is the best linear approximation and approximation error adds to noise. By contrast, inference (standard errors, intervals, tests on βj\beta_j) requires the model to describe errors well: zero conditional mean, constant variance and independence for classical formulas, normality for exactness at small nn, or robust standard errors when variance is not constant. Causal interpretation of a coefficient requires still more; we return to it at the end.

Least squares as maximum likelihood

Why squares? In the previous lesson the answer was that squared error is minimized by the conditional mean, which is what we want to estimate. The probabilistic view gives the same answer from the other side: squared error results from assuming Gaussian noise and applying maximum likelihood.

Suppose that, conditional on X\mat{X},

yi=β⊤xi+εi,ε1,…,εn∼iidN(0,σ2),y_i = \vb{\beta}\T\vb{x}_i + \varepsilon_i, \qquad \varepsilon_1, \dots, \varepsilon_n \iid \Normal(0, \sigma^2),

that is, independent, homoscedastic Gaussian noise (with the same variance for every example). The density of the observations is the product of the εi\varepsilon_i densities, and its logarithm is

ℓ(β,σ2)=−n2log⁡(2πσ2)−12σ2∥y−Xβ∥2⏟RSS(β).\ell(\vb{\beta}, \sigma^2) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\underbrace{\norm{\vb{y} - \mat{X}\vb{\beta}}^2}_{\mathrm{RSS}(\vb{\beta})}.

This equivalence is least squares as Gaussian maximum likelihood. You will prove points 1 and 2 step by step in a guided exercise; the idea is that for each fixed σ2\sigma^2, ℓ\ell is a constant minus RSS(β)/(2σ2)\mathrm{RSS}(\vb{\beta})/(2\sigma^2), so the β\vb{\beta} maximizing it minimizes RSS\mathrm{RSS} and does not depend on σ2\sigma^2. Point 3 uses a trace argument: with hat matrix H=X(X⊤X)−1X⊤\mat{H} = \mat{X}(\mat{X}\T\mat{X})\inv\mat{X}\T, the residual is (I−H)y=(I−H)ε(\mat{I} - \mat{H})\vb{y} = (\mat{I} - \mat{H})\vb{\varepsilon}, and E[ε⊤(I−H)ε]=σ2tr⁡(I−H)=σ2(n−p)\E[\vb{\varepsilon}\T(\mat{I} - \mat{H})\vb{\varepsilon}] = \sigma^2\tr(\mat{I} - \mat{H}) = \sigma^2(n - p), because a projection’s trace is its rank. Fitting pp parameters “spends” pp noise dimensions, which lie inside col⁡(X)\col(\mat{X}) and do not appear in the residual. Note that pp counts the intercept.

There is a way to see it all at once. Substituting the optimum RSS(β)/n\mathrm{RSS}(\vb{\beta})/n for σ2\sigma^2 at each β\vb{\beta} leaves the profile log-likelihood

ℓp(β)=max⁡σ2ℓ(β,σ2)=−n2log⁡2π RSS(β)n−n2,\ell_p(\vb{\beta}) = \max_{\sigma^2}\ell(\vb{\beta}, \sigma^2) = -\frac{n}{2}\log\frac{2\pi\,\mathrm{RSS}(\vb{\beta})}{n} - \frac{n}{2},

a decreasing function of RSS(β)\mathrm{RSS}(\vb{\beta}). Maximizing likelihood and minimizing the sum of squares are the same problem.

Two practical consequences. First, σ^2\hat\sigma^2 lets you make the model probabilistic, with predictions y∣x∼N(β^⊤x,σ^2)y \given \vb{x} \sim \Normal(\hat{\vb{\beta}}\T\vb{x}, \hat\sigma^2) and test-set log-likelihood for comparing models; allowing a network to predict variance as well gives the heteroscedastic Gaussian loss. Second, the difference between nn and n−pn - p is negligible when p≪np \ll n, but not when pp approaches nn. In the lab, with 342 examples and 11 parameters, the ratio is 0.9680.968.

Different noise, different estimator

The noise model is not a technical detail: it determines which estimator is optimal. If instead of Gaussian noise we have a Laplace distribution, p(ε)=12be−∣ε∣/bp(\varepsilon) = \frac{1}{2b}e^{-\abs{\varepsilon}/b}, the log-likelihood is

ℓ(β,b)=−nlog⁡(2b)−1b∑i=1n∣yi−β⊤xi∣,\ell(\vb{\beta}, b) = -n\log(2b) - \frac{1}{b}\sum_{i=1}^n \abs{y_i - \vb{\beta}\T\vb{x}_i},

and the maximum-likelihood estimator of β\vb{\beta} minimizes the sum of absolute values: this is least absolute deviations (LAD) regression, with b^=1n∑i∣ri∣\hat b = \frac1n\sum_i\abs{r_i}. Since absolute loss is minimized by the median (as you saw when studying what each loss estimates), LAD is median regression: it estimates the conditional median of yy instead of the mean.

The difference is visible with outliers. Under squared loss, a point at distance rr from the line weighs r2r^2; under absolute loss, ∣r∣\abs{r}. An outlier 4 units away weighs 16 times as much as a point 1 unit away with squares, and only 4 times as much with absolute values. The thin-tailed Gaussian therefore “believes” a large residual is nearly impossible and shifts the line to reduce it; the Laplace distribution, with exponential tails, accepts it as rare but possible.

InteractiveThe noise model determines the line
  • proposed line (b,a)(b, a)
  • least squares
  • least absolute deviations
  • noise density at each xix_i
Each point’s contribution to negative log-likelihood, −log⁡p(ri)-\log p(r_i) (the two on the right are outliers)
3.73.8
Noise
1.12
0.333
Profile log-likelihood−24.16
Maximum with this noise−24.16
σ^=RSS/n\hat\sigma = \sqrt{\text{RSS}/n}1.359
Outlier weight in ∑ri2\sum r_i^273 %
At the maximum: this is the least-squares line.
Twelve points generated with y=1+0.5x+0.35 εy = 1 + 0.5x + 0.35\,\varepsilon, ε∼N(0,1)\varepsilon \sim \Normal(0, 1), and two red outliers you can drag. Around each point, the noise density is drawn sideways, centered on the line's prediction, with scale at its maximum-likelihood estimate given the line; the thick horizontal stroke marks the density at the point. Below is each point's contribution −log⁡p(ri)-\log p(r_i). With Gaussian noise the two outliers account for 73% of the sum of squares and the optimal line (least squares) bends toward them; switch to Laplace and press “Go to optimum”: the least-absolute-deviations line barely moves. Then drag one outlier toward the cloud and another farther away.

Which should you use? It depends on the actual noise, and efficiency tells us. To estimate a location (the simplest case, an intercept-only model), least squares gives the mean and LAD the median. The cell compares their variances by Monte Carlo under both noise models, normalized to variance 1:

[ ]Mean versus median: the winner depends on noiseBrowser
import numpy as np

rng = np.random.default_rng(1)
R = 10000                                        # repeticiones de Monte Carlo
for n in [101, 401]:
    for nombre, ruido in [("gaussiano", rng.normal(size=(R, n))),
                          ("Laplace", rng.laplace(scale=1 / np.sqrt(2), size=(R, n)))]:   # varianza 1 en los dos
        cociente = np.median(ruido, axis=1).var() / ruido.mean(axis=1).var()
        print(f"n = {n}, ruido {nombre:9s}: Var(mediana) / Var(media) = {cociente:.3f}")
print(f"límite cuando n crece: gaussiano pi/2 = {np.pi / 2:.3f}, Laplace 1/2")

With Gaussian noise, the median has over 50% more variance than the mean: the price of robustness when it was unnecessary. With Laplace noise the reverse holds: the mean has almost twice the variance. The limits follow asymptotic theory: the median has asymptotic variance 1/(4f(0)2n)1/(4f(0)^2 n), where ff is the noise density, and the mean has σ2/n\sigma^2/n, giving π/2\pi/2 for Gaussian and 1/21/2 for Laplace. Laplace convergence is slow (0.57 with n=101n = 101 and 0.53 with n=401n = 401) because its density has a peak at 0. The same ratio 1/(4f(0)2σ2)1/(4f(0)^2\sigma^2) compares LAD and least-squares slopes in multivariable regression (Bassett and Koenker, 1978).

Three qualifications. LAD is robust to outliers in yy, not to points with extreme x\vb{x} (high leverage): a single one can pull the line. LAD has no closed-form solution; it is a linear program, and its solution is not always unique. Between the extremes lies the Huber estimator, quadratic near 0 and linear in the tails, which is maximum likelihood for a density with a Gaussian center and Laplace tails (Huber, 1964). All follow the same pattern: choose a noise model, and its negative log-likelihood is your loss.

Centering, standardization, and the intercept

Real variables come in arbitrary units: years, kilograms, mg/dl. For unpenalized least squares that does not matter in a precise sense, but it matters greatly for training, regularization, and interpretation. Start with the intercept.

You will prove this in a guided exercise. The geometric idea: centered columns are orthogonal to 1\vb{1}, so col⁡(X)=span⁡{1}⊕col⁡(Xc)\col(\mat{X}) = \spn\{\vb{1}\} \oplus \col(\mat{X}_c) is a sum of orthogonal subspaces, and projection onto it amounts to projecting separately onto each. The projection onto 1\vb{1} is yˉ1\bar y\vb{1}. This is exactly what scikit-learn does: LinearRegression centers X\mat{X} and y\vb{y}, solves without an intercept, and computes b^\hat b at the end with this formula.

This transformation and its treatment of the intercept are centering, standardization, and the intercept. If you fit y^=b~+w~⊤z\hat y = \tilde b + \tilde{\vb{w}}\T\vb{z} on the standardized scale, substituting zjz_j gives the coefficients on the original scale:

y^=b~+∑jw~j xj−μjsj⟹wj=w~jsj,b=b~−∑jwj μj.\hat y = \tilde b + \sum_j \tilde w_j\,\frac{x_j - \mu_j}{s_j} \quad\Longrightarrow\quad w_j = \frac{\tilde w_j}{s_j}, \qquad b = \tilde b - \sum_j w_j\,\mu_j.

w~j\tilde w_j reads as “how much y^\hat y changes per standard deviation of xjx_j,” allowing magnitude comparisons across variables with different units; wjw_j is per unit of xjx_j. If you also standardize y\vb{y}, additionally multiply by sys_y and add yˉ\bar y.

Does standardization change the fit? For unpenalized least squares, no: the transformation x↦z\vb{x} \mapsto \vb{z} is affine and invertible, so columns 1,z1,…,zd\vb{1}, z_1, \dots, z_d span the same subspace as 1,x1,…,xd\vb{1}, x_1, \dots, x_d, and the projection of y\vb{y}, hence the predictions, is unchanged. The coefficients change according to the formula above, and nothing else. In the lab you will verify that coefficients converted back to the original scale match those of the direct fit to 10−1210^{-12}. Why standardize, then? For four things beyond exact least squares:

  • Training with gradients. Descent speed depends on variable scales and how far their means are from zero. This is the next section.
  • Penalizing coefficients. Ridge and lasso penalize ∥w∥\norm{\vb{w}}, and coefficients in kilograms and grams are not comparable: without standardization, the penalty depends on units. The intercept is left out of the penalty: penalizing it would make predictions depend on the chosen origin for measuring yy. With centered data it does not even appear: it is yˉ\bar y.
  • Measuring distances. In k-nearest neighbors or kernels, the largest-scale variable dominates distance.
  • Reading magnitudes. The w~j\tilde w_j are comparable; the wjw_j are not.

Gradient descent on squared loss

Solving the normal equations costs O(np2+p3)\bigO(np^2 + p^3) and requires keeping X\mat{X} in memory. When pp is huge, the data do not fit, or the loss is not quadratic (almost everything that follows), train with gradients. Linear regression is the case where descent can be understood exactly, and what you learn here explains much of what happens when training networks.

With loss L(β)=12n∥y−Xβ∥2L(\vb{\beta}) = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 (the 12\frac12 simply cleans up the derivative),

∇L(β)=−1nX⊤(y−Xβ)=R^β−1nX⊤y,∇2L=R^=1nX⊤X.\grad L(\vb{\beta}) = -\frac1n\mat{X}\T(\vb{y} - \mat{X}\vb{\beta}) = \hat{\mat{R}}\vb{\beta} - \frac1n\mat{X}\T\vb{y}, \qquad \hess L = \hat{\mat{R}} = \frac1n\mat{X}\T\mat{X}.

The Hessian is constant and the loss is exactly quadratic: L(β)=L(β^)+12(β−β^)⊤R^(β−β^)L(\vb{\beta}) = L(\hat{\vb{\beta}}) + \frac12(\vb{\beta} - \hat{\vb{\beta}})\T\hat{\mat{R}}(\vb{\beta} - \hat{\vb{\beta}}). For error et=βt−β^\vb{e}_t = \vb{\beta}_t - \hat{\vb{\beta}}, the step βt+1=βt−η∇L(βt)\vb{\beta}_{t+1} = \vb{\beta}_t - \eta\grad L(\vb{\beta}_t) becomes, using ∇L(β^)=0\grad L(\hat{\vb{\beta}}) = \vb{0},

et+1=(I−ηR^) et,luegoet=(I−ηR^)te0.\vb{e}_{t+1} = (\mat{I} - \eta\hat{\mat{R}})\,\vb{e}_t, \qquad\text{luego}\qquad \vb{e}_t = (\mat{I} - \eta\hat{\mat{R}})^t\vb{e}_0.

In the eigenvector basis of R^\hat{\mat{R}}, with eigenvalues λ1≥⋯≥λp>0\lambda_1 \ge \dots \ge \lambda_p > 0, each component evolves separately: it is multiplied by 1−ηλi1 - \eta\lambda_i at each step. Everything follows from this (the dynamics of GD on quadratics, now with R^\hat{\mat{R}} from particular data):

  • Maximum rate. Descent converges from any point if and only if ∣1−ηλi∣<1\abs{1 - \eta\lambda_i} < 1 for every ii, that is, 0<η<2/λmax⁡(X⊤X/n)0 < \eta < 2/\lambda_{\max}(\mat{X}\T\mat{X}/n). With ηλmax⁡>1\eta\lambda_{\max} > 1, the highest-curvature component changes sign at each step (zigzag); with ηλmax⁡>2\eta\lambda_{\max} > 2, it grows.
  • Speed. Error shrinks as ρt\rho^t with ρ=max⁡i∣1−ηλi∣\rho = \max_i\abs{1 - \eta\lambda_i}. With the best fixed step, η⋆=2/(λmax⁡+λmin⁡)\eta^\star = 2/(\lambda_{\max} + \lambda_{\min}), ρ=(κ−1)/(κ+1)\rho = (\kappa - 1)/(\kappa + 1), where κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} is the condition number of R^\hat{\mat{R}}. With η=1/λmax⁡\eta = 1/\lambda_{\max}, ρ=1−1/κ\rho = 1 - 1/\kappa. In either case, reducing error by a factor ϵ\epsilon takes on the order of κlog⁡(1/ϵ)\kappa\log(1/\epsilon) steps.
  • Without full rank. If λmin⁡=0\lambda_{\min} = 0, the null-space component never moves. Starting at β0=0\vb{\beta}_0 = \vb{0}, which has no null-space component, descent converges to the minimum-norm solution: the same one returned by lstsq.

What determines κ\kappa? With one variable of mean mm and standard deviation ss plus an intercept,

R^=[1mmm2+s2],λmax⁡λmin⁡=det⁡R^=s2,λmax⁡+λmin⁡=1+m2+s2.\hat{\mat{R}} = \begin{bmatrix} 1 & m \\ m & m^2 + s^2 \end{bmatrix}, \qquad \lambda_{\max}\lambda_{\min} = \det\hat{\mat{R}} = s^2, \qquad \lambda_{\max} + \lambda_{\min} = 1 + m^2 + s^2.

With m=0m = 0 and s=1s = 1, R^=I\hat{\mat{R}} = \mat{I} and κ=1\kappa = 1. As mm grows, λmax⁡≈1+m2+s2\lambda_{\max} \approx 1 + m^2 + s^2 grows and λmin⁡=s2/λmax⁡\lambda_{\min} = s^2/\lambda_{\max} shrinks: κ≈(1+m2+s2)2/s2\kappa \approx (1 + m^2 + s^2)^2/s^2 explodes from both ends. The flat direction moves bb and ww in opposite directions without changing the prediction at x=mx = m, where the data lie: a long, narrow valley. Large ss has the same effect by another route.

InteractiveGradient descent, conditioning, and standardization
  • contours of L(β0,β1)L(\beta_0, \beta_1)
  • GD on xx
  • start and β^\hat\beta
Relative suboptimality (L−L⋆)/(L0−L⋆)(L - L^\star)/(L_0 - L^\star), log scale
3.0
1.00
0.90
λmax⁡,λmin⁡\lambda_{\max}, \lambda_{\min} of X⊤X/n\mat{X}\T\mat{X}/n10.908, 0.0917
κ\kappa unstandardized119.0
η\eta and per-step factor0.1650 and 0.9849
Iterations to 10−610^{-6}, unstandardized306
Very elongated ellipses: the flat valley direction determines speed, advancing only by a factor 1−ηλmin⁡1 - \eta\lambda_{\min} per step.
Contours of L(β0,β1)L(\beta_0, \beta_1) for y=1+0.8x+0.5εy = 1 + 0.8x + 0.5\varepsilon with 40 values of x=m+s ux = m + s\,u (standardized uu), and the descent trajectory with step η=c⋅2/λmax⁡\eta = c\cdot 2/\lambda_{\max} from the hollow circle. With m=3m = 3 the ellipses are needle-shaped (κ≈119\kappa \approx 119): the path jumps from side to side of the valley then crawls along its floor for hundreds of steps. Move mm to 0 and ss to 1 and watch them round out; raise cc above 1. Enable “Standardize”: descent runs on z=(x−m)/sz = (x - m)/s, whose Hessian is the identity, and its path converted back to (β0,β1)(\beta_0, \beta_1) points directly at β^\hat\beta: with c=0.9c = 0.9 it bounces along that line because each step multiplies error by 1−2c=−0.81 - 2c = -0.8, and with c=0.5c = 0.5 it arrives in one step. Below, relative suboptimality on a log scale: its slope is 2log⁡ρ2\log\rho.

Standardization makes m=0m = 0 and s=1s = 1 for all variables at once. With one variable, R^\hat{\mat{R}} becomes the identity. With several, it becomes their correlation matrix (with a 1 added for the decoupled intercept): standardization removes poor conditioning from scales and means, not from correlations. Two standardized variables with correlation ρ\rho give a matrix [1ρρ1]\begin{bmatrix} 1 & \rho \\ \rho & 1 \end{bmatrix} whose condition number grows without bound as ∣ρ∣→1\abs{\rho} \to 1, even though both variables have mean 0 and variance 1 (you will calculate this in an exercise). Standardization cannot fix that; ridge (which adds λ\lambda to every eigenvalue) and second-order methods can.

In the lab’s diabetes dataset the difference spans several orders of magnitude. Without standardization, with variables such as total cholesterol around 189 or blood pressure around 95, λmax⁡(R^)=7.3×104\lambda_{\max}(\hat{\mat{R}}) = 7.3\times 10^4: the maximum rate is 2.7×10−52.7\times 10^{-5} and κ=5.5×107\kappa = 5.5\times 10^{7}, and after 20,000 iterations the loss is still 0.9% above its minimum (relative suboptimality). Standardized, κ=500\kappa = 500 and 1,339 iterations suffice to reach 10−610^{-6}. The remaining κ=500\kappa = 500 comes from the correlation of 0.894 between two cholesterol measures, s1s_1 and s2s_2.

Stochastic descent and the LMS rule

The full gradient costs O(np)\bigO(np) per step: it scans all the data to take one step. But ∇L\grad L is an average of per-example gradients, ∇L(β)=1n∑igi(β)\grad L(\vb{\beta}) = \frac1n\sum_i \vb{g}_i(\vb{\beta}) with gi(β)=−(yi−β⊤xi) xi\vb{g}_i(\vb{\beta}) = -(y_i - \vb{\beta}\T\vb{x}_i)\,\vb{x}_i, and a minibatch average is an unbiased estimator of it. This is stochastic gradient descent, which has its own name for a linear model with squared loss.

This is the LMS rule and stochastic descent for linear models. The interpretation is immediate: prediction error yt−y^ty_t - \hat y_t multiplied by the input determines how much and in which direction each coefficient is corrected. Each step costs O(p)\bigO(p) and requires O(p)\bigO(p) memory, without storing any example: training can use an endless stream or a dataset that does not fit in memory by reading it in chunks.

How high a rate: three thresholds

Suppose examples arrive independently and identically distributed, with invertible R=E[xx⊤]\mat{R} = \E[\vb{x}\vb{x}\T] and best linear predictor β⋆=R−1E[xy]\vb{\beta}^\star = \mat{R}\inv\E[\vb{x}y], and the rate is constant. With et=βt−β⋆\vb{e}_t = \vb{\beta}_t - \vb{\beta}^\star and εt=yt−β⋆Txt\varepsilon_t = y_t - \vb{\beta}^{\star\mathsf{T}}\vb{x}_t,

et+1=(I−η xtxt⊤) et+η εtxt.\vb{e}_{t+1} = (\mat{I} - \eta\,\vb{x}_t\vb{x}_t\T)\,\vb{e}_t + \eta\,\varepsilon_t\vb{x}_t.

Because et\vb{e}_t depends only on previous examples, it is independent of (xt,yt)(\vb{x}_t, y_t), and because E[εtxt]=0\E[\varepsilon_t\vb{x}_t] = \vb{0} by definition of β⋆\vb{\beta}^\star, taking expectations gives

E[et+1]=(I−ηR) E[et].\E[\vb{e}_{t+1}] = (\mat{I} - \eta\mat{R})\,\E[\vb{e}_t].

The mean of LMS follows gradient descent on risk exactly, converging if and only if η<2/λmax⁡(R)\eta < 2/\lambda_{\max}(\mat{R}). It is tempting to stop there, but that bound is too optimistic for an individual trajectory. Consider a single-example step: that example’s residual changes from yt−βt⊤xty_t - \vb{\beta}_t\T\vb{x}_t to (1−η∥xt∥2)(yt−βt⊤xt)(1 - \eta\norm{\vb{x}_t}^2)(y_t - \vb{\beta}_t\T\vb{x}_t), so if η∥xt∥2>2\eta\norm{\vb{x}_t}^2 > 2 the step overshoots on that example. And ∥xt∥2\norm{\vb{x}_t}^2 can be much greater than λmax⁡(R)\lambda_{\max}(\mat{R}): its mean is tr⁡R\tr\mat{R}, the sum of all eigenvalues.

The rigorous approach studies the second moment Kt=E[etet⊤]\mat{K}_t = \E[\vb{e}_t\vb{e}_t\T], which evolves under a linear map depending on fourth-order moments of x\vb{x}. In the scalar, noiseless case with x∼N(0,r)x \sim \Normal(0, r), E[et+12]=E[(1−ηx2)2] E[et2]=(1−2ηr+3η2r2) E[et2]\E[e_{t+1}^2] = \E[(1 - \eta x^2)^2]\,\E[e_t^2] = (1 - 2\eta r + 3\eta^2r^2)\,\E[e_t^2], because E[x4]=3r2\E[x^4] = 3r^2, and the condition is η<2/(3r)\eta < 2/(3r): one third of the mean bound. For zero-mean Gaussian inputs in dimension dd, the same calculation with E[xx⊤Kxx⊤]=2RKR+tr⁡(RK) R\E[\vb{x}\vb{x}\T\mat{K}\vb{x}\vb{x}\T] = 2\mat{R}\mat{K}\mat{R} + \tr(\mat{R}\mat{K})\,\mat{R} and the determinant lemma gives the exact condition ηλmax⁡<1\eta\lambda_{\max} < 1 and ∑iηλi1−ηλi<2\sum_i \frac{\eta\lambda_i}{1 - \eta\lambda_i} < 2, depending on all eigenvalues (the general analysis of LMS with Gaussian inputs is due to Feuer and Weinstein, 1985). There is a third threshold, the one an individual run actually sees: the trajectory is a product of random matrices and diverges almost surely when its Lyapunov exponent is positive. The cell computes all three for the interactive’s model below, x=(1,x)\vb{x} = (1, x) with x∼N(0,1)x \sim \Normal(0, 1), where R=I\mat{R} = \mat{I} and the mean bound is η<2\eta < 2:

[ ]Three thresholds for the LMS rateBrowser
import numpy as np

# x = (1, u) con u ~ N(0, 1): R = I. Segundo momento K -> E[(I - eta x xᵀ) K (I - eta x xᵀ)]
# sobre (k11, k22, k12), con E[u^2] = 1 y E[u^4] = 3.
def operador_mc(eta):
    a = (1 - eta) ** 2
    return np.array([[a, eta**2, 0],
                     [eta**2, a + 2 * eta**2, 0],
                     [0, 0, 1 - 2 * eta + 2 * eta**2]])

def radio(eta):
    return max(abs(np.linalg.eigvals(operador_mc(eta))))

lo, hi = 0.01, 1.99
for _ in range(60):                              # bisección del umbral en media cuadrática
    mid = (lo + hi) / 2
    lo, hi = (mid, hi) if radio(mid) < 1 else (lo, mid)
print(f"umbral de la media: 2/lambda_max = 2.0")
print(f"umbral en media cuadrática: {lo:.4f}   (fórmula cerrada 2 - sqrt(2) = {2 - np.sqrt(2):.4f})")

rng = np.random.default_rng(0)
def lyapunov(eta, cadenas=2000, pasos=300):
    """Tasa de crecimiento casi segura de ‖e_t‖ sin ruido, con muchas cadenas en paralelo."""
    v = np.tile([1.0, 0.0], (cadenas, 1))
    s = np.zeros(cadenas)
    for _ in range(pasos):
        u = rng.normal(size=cadenas)
        proy = v[:, 0] + u * v[:, 1]             # xᵀv con x = (1, u)
        v = v - eta * np.column_stack([proy, u * proy])
        nv = np.linalg.norm(v, axis=1)
        s += np.log(nv)
        v /= nv[:, None]
    return s.mean() / pasos

for eta in [0.5, 0.8, 1.0, 1.1, 1.2, 1.5, 1.9]:
    print(f"eta = {eta:.1f}: exponente de Lyapunov {lyapunov(eta):+.3f}   radio en media cuadrática {radio(eta):.3f}")

The three thresholds differ greatly: the mean converges for η<2\eta < 2, an individual trajectory for η\eta below a value between 1.0 and 1.1 (where the exponent changes sign), and mean squared error only for η<2−2≈0.586\eta < 2 - \sqrt 2 \approx 0.586. Between the latter two, the trajectory does not diverge, but with noise its fluctuations have such heavy tails that variance is infinite: enormous sporadic spikes appear. The resulting rule of thumb is that the natural scale of the LMS rate is 1/tr⁡R=1/E∥x∥21/\tr\mat{R} = 1/\E\norm{\vb{x}}^2, not 1/λmax⁡1/\lambda_{\max}. Normalized LMS uses ηt=μ/∥xt∥2\eta_t = \mu/\norm{\vb{x}_t}^2 with 0<μ<20 < \mu < 2, ensuring no step overshoots on its own example.

Constant rates, decreasing rates, and changing streams

With a constant rate, even a stable one, βt\vb{\beta}_t does not converge to β⋆\vb{\beta}^\star: each example brings noise εt\varepsilon_t and injects it into the coefficients. Error stabilizes in a noise ball: if noise εt\varepsilon_t is independent of xt\vb{x}_t with variance σ2\sigma^2, E∥βt−β⋆∥2\E\norm{\vb{\beta}_t - \vb{\beta}^\star}^2 tends to a constant of order η\eta. To lowest order in η\eta, the stationary second moment satisfies RK+KR≈ησ2R\mat{R}\mat{K} + \mat{K}\mat{R} \approx \eta\sigma^2\mat{R}, that is, K≈ησ22I\mat{K} \approx \frac{\eta\sigma^2}{2}\mat{I} and E∥βt−β⋆∥2≈ησ2p/2\E\norm{\vb{\beta}_t - \vb{\beta}^\star}^2 \approx \eta\sigma^2 p/2; excess mean squared error, tr⁡(RK)≈ησ22tr⁡R\tr(\mat{R}\mat{K}) \approx \frac{\eta\sigma^2}{2}\tr\mat{R}, is called misadjustment in adaptive filtering. The exact version for the interactive model follows from the same second-moment operator with the noise term, and the cell compares it with a simulation:

[ ]The constant-rate noise ballBrowser
import numpy as np

rng = np.random.default_rng(2)
sigma, cadenas, pasos = 0.5, 2000, 1500
B = np.array([[1.0, 1.0], [1.0, 3.0]])           # parte diagonal de E[(xᵀKx) x xᵀ] con x = (1, u)
for eta in [0.02, 0.05, 0.2]:
    e = np.zeros((cadenas, 2))                    # e = beta - beta*, empezando en el óptimo
    for _ in range(pasos):
        u = rng.normal(size=cadenas)
        err = sigma * rng.normal(size=cadenas) - (e[:, 0] + u * e[:, 1])   # y - betaᵀx
        e = e + eta * err[:, None] * np.column_stack([np.ones(cadenas), u])
    # estacionario: (2 eta I - eta^2 B) k = eta^2 sigma^2 (1, 1)
    exacto = (eta * sigma**2 * np.linalg.solve(2 * np.eye(2) - eta * B, np.ones(2))).sum()
    print(f"eta = {eta:<4}: E‖β - β*‖² simulado {np.mean((e**2).sum(1)):.5f}   exacto {exacto:.5f}"
          f"   aproximación eta·sigma²·p/2 = {eta * sigma**2:.5f}")

The simulation with 2,000 chains reproduces the exact value, and the linear approximation in η\eta is good for small rates but underestimates for large ones, where fourth moments matter. Convergence requires a decreasing rate satisfying the Robbins–Monro conditions ∑tηt=∞\sum_t\eta_t = \infty (to reach anywhere) and ∑tηt2<∞\sum_t\eta_t^2 < \infty (so accumulated noise is finite), such as ηt∝1/t\eta_t \propto 1/t. See learning-rate schedules in optimization for variants.

But a decreasing rate has a cost when data change. With ηt=η/(1+ηt)\eta_t = \eta/(1 + \eta t) and R=I\mat{R} = \mat{I}, LMS behaves like an average of the entire history: an example today weighs as much as one a thousand steps ago. With a constant rate, an example’s influence instead decays as (1−ηλ)k(1 - \eta\lambda)^k after kk steps: the filter remembers about 1/(ηλ)1/(\eta\lambda) examples and tracks changes. This is every adaptive system’s trade-off: long memory (less noise) versus fast reaction (less delay).

InteractiveLMS on a data stream
  • LMS
  • current true relationship
  • least squares on all observed data
  • last 40 points
Error ∥wt−wverdad∥\norm{\vb{w}_t - \vb{w}_{\text{verdad}}} for both schedules (same data)
  • constant rate
  • decreasing rate
0.050
Schedule
ηt\eta_t and ηt λmax⁡(R^)\eta_t\,\lambda_{\max}(\hat{\mat{R}})0.0500 and 0.247
LMS (b,a)(b, a)(0.00, 0.00)
current truth(0.50, 1.00)
least squares on observed data·
Step 0 of 600.
Points arrive one at a time, with x∼N(0,1)x \sim \Normal(0, 1) and y=0.5+x+0.5εy = 0.5 + x + 0.5\varepsilon, and the LMS rule moves the line (orange) after each. At t=300t = 300 the relationship changes to y=−0.5−0.6x+0.5εy = -0.5 - 0.6x + 0.5\varepsilon. With the initial constant rate η=0.05\eta = 0.05, the line converges, oscillates around the true line, and follows it after the change; least squares on all observations so far (magenta) stays halfway. Switch to the decreasing schedule: after the change, the line remains anchored. Increase the rate: from η≈0.5\eta \approx 0.5 increasingly large spikes appear (with these data, ∥(b,a)∥\norm{(b, a)} reaches 8 at η=0.5\eta = 0.5 and 570 at η=0.9\eta = 0.9); at η=1\eta = 1 a spike reaches 2×1052\times 10^5, and from η≈1.05\eta \approx 1.05 coefficients exceed 10610^6 and the figure treats the line as lost, although the mean bound is η<2\eta < 2. Near 1.05 this may still be a heavy-tail spike, because the Lyapunov exponent in the previous cell changes sign between 1.0 and 1.1; above that, divergence is almost sure. Below, the error of both schedules on the same data.

Minibatches interpolate between the extremes. A batch of size BB divides stochastic-gradient variance by BB (if examples are sampled independently), costs BB times more per step, and uses vector hardware better; one epoch has n/Bn/B steps. With B=1B = 1 this is LMS; with B=nB = n, full-batch descent. Minibatch gradient variance quantifies this; in the lab you will see its effect on loss epoch by epoch.

Lab: linear regression from scratch

You will fit the same model four ways (closed form, full-batch descent, minibatches, and LMS) on scikit-learn’s diabetes dataset: 442 patients, 10 clinical variables in their original units (age, sex, body mass index, blood pressure, and six blood measurements), and disease progression one year later. We split 342 patients for training and 100 for testing, and everything estimated (means, deviations, coefficients) comes only from the 342.

[ ]Custom standardizer and closed formBrowser
import numpy as np
from sklearn.datasets import load_diabetes

X, y = load_diabetes(return_X_y=True, scaled=False)    # unidades originales
nombres = load_diabetes().feature_names
rng = np.random.default_rng(0)
perm = rng.permutation(len(y))
tr, te = perm[:342], perm[342:]
Xtr, Xte, ytr, yte = X[tr], X[te], y[tr], y[te]
print("medias de entrenamiento:", dict(zip(nombres, Xtr.mean(0).round(1))))

class Estandarizador:
    def fit(self, X):
        self.media = X.mean(axis=0)
        self.escala = X.std(axis=0)
        self.escala[self.escala == 0] = 1.0              # variables constantes
        return self
    def transform(self, X):
        return (X - self.media) / self.escala

def con_unos(X):
    return np.column_stack([np.ones(len(X)), X])

def ajustar_mc(X, y):
    beta, *_ = np.linalg.lstsq(con_unos(X), y, rcond=None)
    return beta[0], beta[1:]

est = Estandarizador().fit(Xtr)                          # estadísticos SOLO de entrenamiento
Ztr, Zte = est.transform(Xtr), est.transform(Xte)
b_z, w_z = ajustar_mc(Ztr, ytr)
w = w_z / est.escala                                     # de vuelta a la escala original
b = b_z - w @ est.media
b_dir, w_dir = ajustar_mc(Xtr, ytr)                      # ajuste directo, sin estandarizar
print(f"\nb en escala z = {b_z:.6f}   media de y = {ytr.mean():.6f}")
print(f"max |w devuelto - w directo| = {np.abs(w - w_dir).max():.1e}   |b - b directo| = {abs(b - b_dir):.1e}")

res = ytr - b - Xtr @ w
rss, n, p = res @ res, len(ytr), X.shape[1] + 1
print(f"\nsigma2 EMV = RSS/n = {rss / n:.1f}   insesgado RSS/(n-p) = {rss / (n - p):.1f}   cociente (n-p)/n = {(n - p) / n:.4f}")
ll = -n / 2 * (np.log(2 * np.pi * rss / n) + 1)
print(f"log-verosimilitud gaussiana en el óptimo = {ll:.2f}")

pred = b + Xte @ w
print(f"prueba: ECM = {np.mean((yte - pred) ** 2):.1f}   R2 = {1 - np.sum((yte - pred) ** 2) / np.sum((yte - yte.mean()) ** 2):.3f}")
print("\ncoeficiente por desviación típica:", dict(zip(nombres, w_z.round(1))))
print("coeficiente por unidad original:  ", dict(zip(nombres, w.round(3))))

What to read in the output: the intercept on the standardized scale is exactly the mean of yy, as the centering theorem says. Coefficients converted back to the original scale match the direct fit to 4×10−134\times 10^{-13}, and the intercept to 2×10−122\times 10^{-12}: standardization does not change the model. σ^MV2=2783.0\hat\sigma^2_{\text{MV}} = 2783.0 versus s2=2875.5s^2 = 2875.5, a 3% difference. The two coefficient rows tell different stories: per original unit, sex (−22.2-22.2) and s5 (55.655.6) seem enormous, but those variables barely vary (sex is 1 or 2, s5 is a logarithm with deviation 0.5); per standard deviation, the most influential are bmi (29.429.4) and s5 (29.029.0). Test R2=0.353R^2 = 0.353 is modest: a linear model of these ten variables does not predict diabetes progression well.

Now gradient descent, with η=1/λmax⁡\eta = 1/\lambda_{\max} in both cases and suboptimality calculated exactly as 12e⊤R^e\frac12\vb{e}\T\hat{\mat{R}}\vb{e}:

[ ]Gradient descent with and without standardizationBrowser
import numpy as np
import matplotlib.pyplot as plt

def descenso(A, y, eta, max_iter, tol=1e-6):
    n = len(y)
    R = A.T @ A / n                                     # hessiana
    g0 = A.T @ y / n
    beta_opt = np.linalg.lstsq(A, y, rcond=None)[0]
    beta = np.zeros(A.shape[1])
    e0 = beta - beta_opt
    q0 = e0 @ R @ e0
    hist = []
    for _ in range(max_iter):
        beta = beta - eta * (R @ beta - g0)             # gradiente = R beta - Xᵀy/n
        e = beta - beta_opt
        hist.append(e @ R @ e / q0)                     # (L - L*) / (L0 - L*)
        if hist[-1] < tol:
            break
    return np.array(hist)

for nombre, A in [("sin estandarizar", con_unos(Xtr)), ("estandarizado", con_unos(Ztr))]:
    lam = np.linalg.eigvalsh(A.T @ A / len(ytr))
    h = descenso(A, ytr, 1 / lam[-1], 20000)
    print(f"{nombre:17s} lambda_max = {lam[-1]:.3g}  lambda_min = {lam[0]:.3g}  kappa = {lam[-1] / lam[0]:.3g}"
          f"  tasa máxima = {2 / lam[-1]:.2g}  iteraciones = {len(h)}  suboptimalidad final = {h[-1]:.1e}")
    plt.semilogy(h, label=nombre)

C = np.corrcoef(Xtr, rowvar=False)
i, j = np.unravel_index(np.argmax(np.abs(C - np.eye(10))), C.shape)
print(f"mayor correlación entre variables: {nombres[i]} y {nombres[j]}, {C[i, j]:.3f}")
plt.xlabel("iteración"); plt.ylabel("(L - L*) / (L0 - L*)"); plt.legend(); plt.show()

The unstandardized curve drops quickly at first (high-curvature directions are resolved in a few steps) and then nearly flattens: that is the valley direction, advancing by a factor of 1−1/κ≈1−2×10−81 - 1/\kappa \approx 1 - 2\times 10^{-8} per step. The standardized curve decreases geometrically, almost a straight line on a log scale, down to 10−610^{-6}. That it still takes over a thousand steps reflects correlation between s1 and s2: κ=500\kappa = 500 is still large.

Finally, minibatches and LMS on standardized data. Each configuration runs 30 epochs (passes through the data); we measure training L−L⋆L - L^\star at the end of selected epochs:

[ ]Minibatches, LMS, and rate schedulesBrowser
import numpy as np
import matplotlib.pyplot as plt

A = con_unos(Ztr)
L_opt = 0.5 * np.mean((ytr - A @ np.r_[b_z, w_z]) ** 2)

def sgd(eta0, epocas, lote, tau=None, seed=0):
    """Minilotes barajados por época; tau=None es tasa constante, si no eta_t = eta0 / (1 + t/tau)."""
    rng = np.random.default_rng(seed)
    n, d = Ztr.shape
    b, w, t = 0.0, np.zeros(d), 0
    curva = []
    for _ in range(epocas):
        for idx in np.array_split(rng.permutation(n), n // lote):
            eta = eta0 if tau is None else eta0 / (1 + t / tau)
            e = ytr[idx] - b - Ztr[idx] @ w             # errores del minilote
            b += eta * e.mean()
            w += eta * Ztr[idx].T @ e / len(idx)
            t += 1
        curva.append(0.5 * np.mean((ytr - b - Ztr @ w) ** 2) - L_opt)
    return np.array(curva), b, w

lam_max = np.linalg.eigvalsh(A.T @ A / len(ytr))[-1]
configs = [("GD completo, eta = 1/lambda_max", 1 / lam_max, 342, None),
           ("minilotes de 32, eta = 0.05", 0.05, 32, None),
           ("LMS, eta = 0.02 constante", 0.02, 1, None),
           ("LMS, eta = 0.005 constante", 0.005, 1, None),
           ("LMS, eta = 0.02 / (1 + t/684)", 0.02, 1, 684)]
for nombre, eta0, lote, tau in configs:
    curva, bb, ww = sgd(eta0, 30, lote, tau)
    ecm = np.mean((yte - bb - Zte @ ww) ** 2)
    print(f"{nombre:32s} pasos/época {342 // lote:3d}   L - L* tras 1, 5 y 30 épocas: "
          f"{curva[0]:7.1f} {curva[4]:6.1f} {curva[-1]:6.2f}   ECM de prueba {ecm:.1f}")
    plt.semilogy(np.arange(1, 31), curva, label=nombre)
print(f"L* = {L_opt:.1f}")
plt.xlabel("época"); plt.ylabel("L - L*"); plt.legend(fontsize=8); plt.show()

The output summarizes the preceding section with real numbers. Per epoch, LMS takes 342 steps and full-batch descent one: after a single epoch, LMS with η=0.02\eta = 0.02 is 185 from the optimum and full-batch descent 7118. But at a constant rate LMS stalls in its noise ball: after 30 epochs it is still 250 away with η=0.02\eta = 0.02 and 57 with η=0.005\eta = 0.005, whose ball is smaller but takes longer to reach (values at a particular epoch fluctuate because they sample the ball). The decreasing schedule starts like the large rate and ends at 3.8, better than either constant. Noise-free full-batch descent starts very slowly and reaches 2.6 after 30 epochs: what remains is mainly the κ=500\kappa = 500 valley direction, which contributes little to loss. Minibatches of 32, at 6.8, lie in between and are the common practical operating point because each step uses vector operations. For scale, L⋆≈1391L^\star \approx 1391: configurations ending within a few units of optimum give test MSE between 3311 and 3360, close to the exact solution’s 3255, while the LMS noise ball with η=0.02\eta = 0.02 raises it to 4100.

With libraries: scikit-learn and statsmodels

ToolWhat it solvesMethod
sklearn.linear_model.LinearRegressionleast squares with interceptcenters X\mat{X} and y\vb{y} and calls scipy.linalg.lstsq (LAPACK gelsd, via SVD); LSQR for sparse data
statsmodels.api.OLS(y, X).fit()least squares, without adding an interceptpseudoinverse via SVD (method="pinv", default) or QR (method="qr"); returns standard errors, s2s^2, log-likelihood
sklearn.linear_model.SGDRegressorsquared loss (or others) with optional penaltyexample-by-example SGD, shuffled epochs; by default L2 penalty with α=10−4\alpha = 10^{-4} and rate ηt=0.01/t0.25\eta_t = 0.01/t^{0.25}
[ ]LinearRegression and statsmodels versus our implementationBrowser
import numpy as np
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression

beta_propio = np.r_[b, w]                                   # de la celda del estandarizador
lr = LinearRegression().fit(Xtr, ytr)
print(f"LinearRegression: max |diferencia| con lo propio = {max(np.abs(lr.coef_ - w).max(), abs(lr.intercept_ - b)):.1e}"
      f"   R2 prueba = {lr.score(Xte, yte):.3f}")

ols = sm.OLS(ytr, sm.add_constant(Xtr)).fit()               # pinv por defecto
ols_qr = sm.OLS(ytr, sm.add_constant(Xtr)).fit(method="qr")
print(f"statsmodels OLS:  max |diferencia| con lo propio = {np.abs(ols.params - beta_propio).max():.1e}"
      f"   pinv frente a qr = {np.abs(ols.params - ols_qr.params).max():.1e}")
print(f"  scale = {ols.scale:.1f} (es RSS/(n-p))   llf = {ols.llf:.2f} (usa RSS/n)   R2 entrenamiento = {ols.rsquared:.3f}")

sin_cte = sm.OLS(ytr, Xtr).fit()                            # el error típico: olvidar add_constant
print(f"\nsin add_constant: R2 = {sin_cte.rsquared:.3f} (no centrado)   coeficiente de s5 = {sin_cte.params[8]:.2f} en lugar de {w[8]:.2f}")

All three implementations agree to 10−1210^{-12}: machine precision, 2×10−162\times 10^{-16}, amplified by coefficient size and the conditioning of the unstandardized problem. ols.scale is s2s^2, the unbiased estimate, while ols.llf evaluates log-likelihood using σ^MV2=RSS/n\hat\sigma^2_{\text{MV}} = \mathrm{RSS}/n: exactly the two numbers from our cell. The last line shows the classic statsmodels mistake: OLS does not add a constant, the model is forced through the origin, and its R2R^2, calculated relative to zero, is 0.902 for a model worse than the correct one.

SGDRegressor is genuine stochastic descent, so it inherits everything you have seen about scales:

[ ]SGDRegressor with and without StandardScalerBrowser
import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

for nombre, modelo in [("sin escalar", SGDRegressor(penalty=None, tol=1e-6, random_state=0)),
                       ("con StandardScaler", make_pipeline(StandardScaler(), SGDRegressor(penalty=None, tol=1e-6, random_state=0)))]:
    modelo.fit(Xtr, ytr)
    sgd_ = modelo if nombre == "sin escalar" else modelo[-1]
    print(f"{nombre:19s} épocas = {sgd_.n_iter_:3d}   R2 prueba = {modelo.score(Xte, yte):.4g}   primeros coeficientes = {np.round(sgd_.coef_[:3], 2)}")

pipe = make_pipeline(StandardScaler(), SGDRegressor(penalty=None, tol=1e-6, random_state=0)).fit(Xtr, ytr)
esc, sgd_ = pipe[0], pipe[-1]
w_sgd = sgd_.coef_ / esc.scale_                              # misma vuelta a la escala original
print(f"\ncoeficientes por desviación típica, SGD:  {np.round(sgd_.coef_, 1)}")
print(f"coeficientes por desviación típica, MC:   {np.round(w_z, 1)}")
print(f"max |w_SGD - w_MC| en escala original = {np.abs(w_sgd - w).max():.2f}")

Without scaling, the default initial rate 0.010.01 multiplies a λmax⁡\lambda_{\max} of 7.3×1047.3\times 10^4: ηλmax⁡≈730\eta\lambda_{\max} \approx 730, far above 2, and coefficients explode to order 101010^{10} with test R2R^2 of −5×1023-5\times 10^{23}. With StandardScaler inside the pipeline (fitted only on fit data), the same algorithm gives R2=0.343R^2 = 0.343 versus 0.353 for the exact solution. It does not match exactly: SGD stops when loss fails to improve by more than tol for 5 epochs, and ill-conditioned directions (those of s1 and s2) are last to fit, precisely where the largest coefficient differences appear.

The scope of this lesson

This lesson treats linear regression as a predictor. Other topics have their own place:

  • Inference: distribution of β^\hat{\vb{\beta}}, intervals and tests, Gauss–Markov, leverage and influence, in the linear model in statistics.
  • Causality: a regression coefficient measures conditional association, not the effect of intervening on a variable. Reading it as a causal effect requires identification assumptions (absence of endogeneity, good controls), studied in causal regression.
  • Bayesian uncertainty: with a prior on β\vb{\beta}, Bayesian linear regression gives predictive distributions rather than a point.
  • Capacity and regularization: what happens when you add many columns appears in polynomial regression and ridge.

Common mistakes

Exercises

QuizA duplicated column
You add to X\mat{X} an exact copy of one of its columns. What happens to the least-squares problem?
QuizLaplace noise
In the model yi=β⊤xi+εiy_i = \vb{\beta}\T\vb{x}_i + \varepsilon_i with independent Laplace εi\varepsilon_i of known scale bb, which estimator of β\vb{\beta} is maximum likelihood?
NumericMaximum rate with two correlated variables
Two standardized variables (no intercept, centered y\vb{y}) have correlation 0.90.9, so X⊤X/n=[10.90.91]\mat{X}\T\mat{X}/n = \begin{bmatrix} 1 & 0.9 \\ 0.9 & 1 \end{bmatrix}. What is the largest rate η\eta (the supremum) for which fixed-step gradient descent on 12n∥y−Xw∥2\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 converges from any starting point?
NumericThe conditioning standardization cannot fix
For the same matrix [10.90.91]\begin{bmatrix} 1 & 0.9 \\ 0.9 & 1 \end{bmatrix}, what is its condition number κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}?
NumericA variable in its natural scale
A regression has an intercept and one variable with mean m=100m = 100 and standard deviation s=10s = 10 (for example, blood pressure in mmHg). What is the largest constant rate η\eta for which gradient descent on 12n∥y−Xβ∥2\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 converges? Give three significant figures.
NumericUndo standardization
You fit a regression on z=(x−20)/4z = (x - 20)/4, using the training mean and deviation, and obtain y^=10+3z\hat y = 10 + 3z. What is the intercept bb of the same model written as y^=b+w x\hat y = b + w\,x?
NumericFrom RSS/n to unbiased variance
You fit by least squares a model with an intercept and 5 variables on n=50n = 50 examples and obtain σ^MV2=RSS/n=4.4\hat\sigma^2_{\text{MV}} = \mathrm{RSS}/n = 4.4. What is the unbiased estimator s2s^2?
QuizWhat changes with standardization?
You fit unpenalized least squares with an intercept on the original variables and then on variables standardized using training statistics. Which statements are true?

More than one answer may be correct.

QuizA changing stream
You train a linear model with LMS on a transaction stream whose relationship between variables and response changes slowly over time. Which learning-rate schedule would you choose?
ProofCentering separates the intercept
Prove: With means xˉ\bar{\vb{x}}, yˉ\bar y and Xc=X0−1xˉ⊤\mat{X}_c = \mat{X}_0 - \vb{1}\bar{\vb{x}}\T, yc=y−yˉ1\vb{y}_c = \vb{y} - \bar y\vb{1}, the pair (b^,w^)(\hat b, \hat{\vb{w}}) minimizes F(b,w)=∥y−b1−X0w∥2F(b, \vb{w}) = \norm{\vb{y} - b\vb{1} - \mat{X}_0\vb{w}}^2 if and only if w^\hat{\vb{w}} minimizes ∥yc−Xcw∥2\norm{\vb{y}_c - \mat{X}_c\vb{w}}^2 and b^=yˉ−w^⊤xˉ\hat b = \bar y - \hat{\vb{w}}\T\bar{\vb{x}}.
0
First fix w\vb{w} and minimize over bb; then substitute.

Step 1 of 3. For fixed w\vb{w}, FF is a parabola in bb. Where is its minimum?

ProofMaximum likelihood under Gaussian noise
Prove: If y=Xβ+ε\vb{y} = \mat{X}\vb{\beta} + \vb{\varepsilon} with ε∼N(0,σ2I)\vb{\varepsilon} \sim \Normal(\vb{0}, \sigma^2\mat{I}), rank⁡X=p\rank\mat{X} = p and RSS(β^)>0\mathrm{RSS}(\hat{\vb{\beta}}) > 0, the maximum-likelihood estimator of β\vb{\beta} is least squares and that of σ2\sigma^2 is RSS(β^)/n\mathrm{RSS}(\hat{\vb{\beta}})/n.
0
Write the log-likelihood and maximize first over β\vb{\beta} and then over v=σ2>0v = \sigma^2 > 0.

Step 1 of 4. What is the log-likelihood of (β,v)(\vb{\beta}, v)?

CodeSGD with custom standardization
Implement sgd_linear_regression(X, y, lr, epochs, batch_size, seed). It receives training data only: standardize each column with its mean and standard deviation (with ddof=0; if a deviation is 0, use 1), train b~\tilde b and w~\tilde{\vb{w}} from zero using minibatches shuffled each epoch with np.random.default_rng(seed).permutation (one generator for all training; batches are consecutive slices of the permutation and the last may be shorter) and updates b~←b~+η e‾\tilde b \leftarrow \tilde b + \eta\,\overline{e}, w~←w~+η ZB⊤eB/∣B∣\tilde{\vb{w}} \leftarrow \tilde{\vb{w}} + \eta\,\mat{Z}_B\T\vb{e}_B/\abs{B}. Return (w, b) on the original scale. Do not modify X.
import numpy as np

def sgd_linear_regression(X, y, lr=0.05, epochs=100, batch_size=16, seed=0):
  """Devuelve (w, b) en la escala original de X."""
  X = np.asarray(X, dtype=float)
  y = np.asarray(y, dtype=float)
  n, d = X.shape
  # tu código: estandarizar, entrenar por minilotes y deshacer la estandarización
  return np.zeros(d), 0.0
Shift+Enter to run

Summary

Key idea
Linear regression projects y\vb{y} onto the column space; choosing squares corresponds to assuming Gaussian noise, and training by gradients optimizes a quadratic whose Hessian X⊤X/n\mat{X}\T\mat{X}/n determines maximum rate and speed, which is why we standardize.
  • f(x)=w⊤x+bf(\vb{x}) = \vb{w}\T\vb{x} + b is linear in parameters; the design matrix with a column of ones absorbs the intercept. Predictions are always unique; coefficients only with full rank, otherwise lstsq gives minimum-norm coefficients.
  • Finite second moments suffice for prediction: β^\hat{\vb{\beta}} estimates the best linear predictor even if the relationship is nonlinear. Inference or causal interpretation requires additional assumptions.
  • Under homoscedastic Gaussian noise, least squares is maximum likelihood and σ^2=RSS/n\hat\sigma^2 = \mathrm{RSS}/n is biased by the factor (n−p)/n(n - p)/n. With Laplace noise, the optimum is median regression: robust to outliers in yy, less efficient if the noise was Gaussian.
  • Centering separates the intercept, b^=yˉ−w^⊤xˉ\hat b = \bar y - \hat{\vb{w}}\T\bar{\vb{x}}. Standardizing with training statistics does not change the least-squares fit, but does change gradient geometry, the effect of penalties, and coefficient interpretation.
  • Descent converges if η<2/λmax⁡(X⊤X/n)\eta < 2/\lambda_{\max}(\mat{X}\T\mat{X}/n) and takes on the order of κ\kappa steps per order of magnitude. Means far from zero and large scales drive up κ\kappa; standardization fixes that except for the part due to correlations.
  • LMS is example-by-example SGD: O(p)\bigO(p) memory and streaming training. The bound 2/λmax⁡2/\lambda_{\max} applies only to its mean; an individual trajectory needs rates on the order of 1/E∥x∥21/\E\norm{\vb{x}}^2. A constant rate leaves a noise ball but tracks changes; a decreasing rate converges if nothing changes and becomes anchored if it does.