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
- 11Supervised learning tasks and training objectiveRegression loss functionsStatistical functional elicited by a loss
- 02Least squaresNormal equationsOrthogonal projection
- 09Numerical least squaresConditioning of a problem
- 05Maximum likelihood estimator (MLE)
- 06Gradient descent dynamics on quadraticsStochastic gradient descent
- 04Univariate normal distribution
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. is linear in even if 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 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 .
What you already know, in one paragraph
Given and , the least-squares problem has as solutions those of the normal equations ; geometrically, is the orthogonal projection of onto , and residual is perpendicular to every column, . If the solution is unique; otherwise an affine subspace of solutions shares the same and the minimum-norm solution is . Numerically, solve with QR or SVD, never by forming the inverse of , whose condition number is the square of that of . With an additional statistical model for errors, the Gaussian linear model gives the distribution of , the Gauss–Markov theorem and diagnostic tools.
With observations and two columns this all fits in one figure: each observation is an axis of , vector is a point in space, and is a plane.
The last step shows the difference between the two objects least squares produces. The prediction is always unique, because projection onto a subspace is unique. The coefficients need not be: at spread 0, and any line through 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 moves the slope a great deal while barely moving . 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 , where columns are nearly dependent, and noise-free data whose exact solution is known:
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 raises the condition number from to and loses precision with it: the explicit inverse gives coefficients with 3.6% error and residual in a problem whose exact residual is 0; solving the system without inversion leaves coefficient error ; QR or SVD, which work on without squaring anything, give about . 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 and 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, 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 versus for the correct model.
Linear in parameters, not in variables. Nothing prevents the columns of from being , , , or the sine of a date: the model remains linear in 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 indicators sum exactly to the column of ones and 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 has finite second moments and is invertible (with the 1 included in ), the best linear predictor under squared error,
exists and is unique, and converges to it by the law of large numbers, because is the same formula with sample means. The proof is the same orthogonality as before in : for any , , because the cross term is by the definition of . None of this assumes that is linear, Gaussian noise, or constant variance: if the relationship is nonlinear, is the best linear approximation and approximation error adds to noise. By contrast, inference (standard errors, intervals, tests on ) requires the model to describe errors well: zero conditional mean, constant variance and independence for classical formulas, normality for exactness at small , 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 ,
that is, independent, homoscedastic Gaussian noise (with the same variance for every example). The density of the observations is the product of the densities, and its logarithm is
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 , is a constant minus , so the maximizing it minimizes and does not depend on . Point 3 uses a trace argument: with hat matrix , the residual is , and , because a projection’s trace is its rank. Fitting parameters “spends” noise dimensions, which lie inside and do not appear in the residual. Note that counts the intercept.
There is a way to see it all at once. Substituting the optimum for at each leaves the profile log-likelihood
a decreasing function of . Maximizing likelihood and minimizing the sum of squares are the same problem.
Two practical consequences. First, lets you make the model probabilistic, with predictions 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 and is negligible when , but not when approaches . In the lab, with 342 examples and 11 parameters, the ratio is .
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, , the log-likelihood is
and the maximum-likelihood estimator of minimizes the sum of absolute values: this is least absolute deviations (LAD) regression, with . 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 instead of the mean.
The difference is visible with outliers. Under squared loss, a point at distance from the line weighs ; under absolute loss, . 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.
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:
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 , where is the noise density, and the mean has , giving for Gaussian and for Laplace. Laplace convergence is slow (0.57 with and 0.53 with ) because its density has a peak at 0. The same ratio compares LAD and least-squares slopes in multivariable regression (Bassett and Koenker, 1978).
Three qualifications. LAD is robust to outliers in , not to points with extreme (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 , so is a sum of orthogonal subspaces, and projection onto it amounts to projecting separately onto each. The projection onto is . This is exactly what scikit-learn does: LinearRegression centers and , solves without an intercept, and computes at the end with this formula.
This transformation and its treatment of the intercept are centering, standardization, and the intercept. If you fit on the standardized scale, substituting gives the coefficients on the original scale:
reads as “how much changes per standard deviation of ,” allowing magnitude comparisons across variables with different units; is per unit of . If you also standardize , additionally multiply by and add .
Does standardization change the fit? For unpenalized least squares, no: the transformation is affine and invertible, so columns span the same subspace as , and the projection of , 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 . 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 , 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 . With centered data it does not even appear: it is .
- Measuring distances. In k-nearest neighbors or kernels, the largest-scale variable dominates distance.
- Reading magnitudes. The are comparable; the are not.
Gradient descent on squared loss
Solving the normal equations costs and requires keeping in memory. When 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 (the simply cleans up the derivative),
The Hessian is constant and the loss is exactly quadratic: . For error , the step becomes, using ,
In the eigenvector basis of , with eigenvalues , each component evolves separately: it is multiplied by at each step. Everything follows from this (the dynamics of GD on quadratics, now with from particular data):
- Maximum rate. Descent converges from any point if and only if for every , that is, . With , the highest-curvature component changes sign at each step (zigzag); with , it grows.
- Speed. Error shrinks as with . With the best fixed step, , , where is the condition number of . With , . In either case, reducing error by a factor takes on the order of steps.
- Without full rank. If , the null-space component never moves. Starting at , which has no null-space component, descent converges to the minimum-norm solution: the same one returned by
lstsq.
What determines ? With one variable of mean and standard deviation plus an intercept,
With and , and . As grows, grows and shrinks: explodes from both ends. The flat direction moves and in opposite directions without changing the prediction at , where the data lie: a long, narrow valley. Large has the same effect by another route.
Standardization makes and for all variables at once. With one variable, 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 give a matrix whose condition number grows without bound as , even though both variables have mean 0 and variance 1 (you will calculate this in an exercise). Standardization cannot fix that; ridge (which adds 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, : the maximum rate is and , and after 20,000 iterations the loss is still 0.9% above its minimum (relative suboptimality). Standardized, and 1,339 iterations suffice to reach . The remaining comes from the correlation of 0.894 between two cholesterol measures, and .
Stochastic descent and the LMS rule
The full gradient costs per step: it scans all the data to take one step. But is an average of per-example gradients, with , 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 multiplied by the input determines how much and in which direction each coefficient is corrected. Each step costs and requires 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 and best linear predictor , and the rate is constant. With and ,
Because depends only on previous examples, it is independent of , and because by definition of , taking expectations gives
The mean of LMS follows gradient descent on risk exactly, converging if and only if . 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 to , so if the step overshoots on that example. And can be much greater than : its mean is , the sum of all eigenvalues.
The rigorous approach studies the second moment , which evolves under a linear map depending on fourth-order moments of . In the scalar, noiseless case with , , because , and the condition is : one third of the mean bound. For zero-mean Gaussian inputs in dimension , the same calculation with and the determinant lemma gives the exact condition and , 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, with , where and the mean bound is :
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 , an individual trajectory for below a value between 1.0 and 1.1 (where the exponent changes sign), and mean squared error only for . 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 , not . Normalized LMS uses with , ensuring no step overshoots on its own example.
Constant rates, decreasing rates, and changing streams
With a constant rate, even a stable one, does not converge to : each example brings noise and injects it into the coefficients. Error stabilizes in a noise ball: if noise is independent of with variance , tends to a constant of order . To lowest order in , the stationary second moment satisfies , that is, and ; excess mean squared error, , 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:
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 is good for small rates but underestimates for large ones, where fourth moments matter. Convergence requires a decreasing rate satisfying the Robbins–Monro conditions (to reach anywhere) and (so accumulated noise is finite), such as . See learning-rate schedules in optimization for variants.
But a decreasing rate has a cost when data change. With and , 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 after steps: the filter remembers about examples and tracks changes. This is every adaptive system’s trade-off: long memory (less noise) versus fast reaction (less delay).
Minibatches interpolate between the extremes. A batch of size divides stochastic-gradient variance by (if examples are sampled independently), costs times more per step, and uses vector hardware better; one epoch has steps. With this is LMS; with , 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.
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 , as the centering theorem says. Coefficients converted back to the original scale match the direct fit to , and the intercept to : standardization does not change the model. versus , a 3% difference. The two coefficient rows tell different stories: per original unit, sex () and s5 () 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 () and s5 (). Test is modest: a linear model of these ten variables does not predict diabetes progression well.
Now gradient descent, with in both cases and suboptimality calculated exactly as :
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 per step. The standardized curve decreases geometrically, almost a straight line on a log scale, down to . That it still takes over a thousand steps reflects correlation between s1 and s2: is still large.
Finally, minibatches and LMS on standardized data. Each configuration runs 30 epochs (passes through the data); we measure training at the end of selected epochs:
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 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 and 57 with , 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 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, : 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 raises it to 4100.
With libraries: scikit-learn and statsmodels
| Tool | What it solves | Method |
|---|---|---|
sklearn.linear_model.LinearRegression | least squares with intercept | centers and and calls scipy.linalg.lstsq (LAPACK gelsd, via SVD); LSQR for sparse data |
statsmodels.api.OLS(y, X).fit() | least squares, without adding an intercept | pseudoinverse via SVD (method="pinv", default) or QR (method="qr"); returns standard errors, , log-likelihood |
sklearn.linear_model.SGDRegressor | squared loss (or others) with optional penalty | example-by-example SGD, shuffled epochs; by default L2 penalty with and rate |
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 : machine precision, , amplified by coefficient size and the conditioning of the unstandardized problem. ols.scale is , the unbiased estimate, while ols.llf evaluates log-likelihood using : 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 , 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:
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 multiplies a of : , far above 2, and coefficients explode to order with test of . With StandardScaler inside the pipeline (fitted only on fit data), the same algorithm gives 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 , 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 , 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
More than one answer may be correct.
Step 1 of 3. For fixed , is a parabola in . Where is its minimum?
Step 1 of 4. What is the log-likelihood of ?
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 and 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 , . 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.0Summary
- 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
lstsqgives minimum-norm coefficients. - Finite second moments suffice for prediction: 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 is biased by the factor . With Laplace noise, the optimum is median regression: robust to outliers in , less efficient if the noise was Gaussian.
- Centering separates the intercept, . 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 and takes on the order of steps per order of magnitude. Means far from zero and large scales drive up ; standardization fixes that except for the part due to correlations.
- LMS is example-by-example SGD: memory and streaming training. The bound applies only to its mean; an individual trajectory needs rates on the order of . A constant rate leaves a noise ball but tracks changes; a decreasing rate converges if nothing changes and becomes anchored if it does.