Key ideas
Model1. : with features the model learns weights plus one bias (2 features → 3 parameters). Training changes and , never the features. Appending a constant feature 1 to every folds the bias into as its last weight; without a bias the fit is forced through the origin.
Least squares1. Each residual is squared — so errors above and below the line cannot cancel — and the squares are added up; the best minimizes that sum. Setting the gradient to zero gives the normal equations, with a unique solution when the design matrix has full column rank. The loss is a convex quadratic, so gradient descent with a small enough step reaches the global minimum from any start (even all-zero weights); the closed form and gradient descent differ in cost, not in the model.
Probabilistic view1. If with Gaussian , maximum likelihood is exactly least squares, whatever the noise variance. Laplace noise instead gives the absolute loss . For a single constant, squared loss is minimized by the mean and absolute loss by the median — which is why squared loss is sensitive to outliers1. The absolute loss has a gradient of constant size, so SGD with a fixed step keeps bouncing around the optimum; the Huber loss (quadratic near 0, linear beyond a threshold) combines the two.
Reading a fit4. The slope is the predicted change in per unit of , in the units of both (price in $1000 and a slope of per year of age: about $1,250 less per year); the intercept is the prediction at . With an intercept, the least-squares line passes through and the residuals sum to zero; for one feature, , so near means a good straight-line fit4. Regression on observational data shows association, not causation. A coefficient's size depends on its feature's units and on correlated features, so compare coefficients only for standardized features — and even then correlated features blur the comparison.
Basis functions. Adding powers or products gives polynomial regression: nonlinear in , still linear in , so the same least-squares machinery applies. The degree is the complexity knob — too low underfits, too high overfits — and with more features than examples a linear model can fit its training data almost perfectly yet generalize badly2.
- Ridge (weight decay, ): adds . Weights shrink toward 0 but stay non-zero; the solution is unique and stable even with collinear features; correlated or duplicated features share the weight evenly.
- Lasso (): adds and sets some coefficients exactly to zero, so it selects features3. Among correlated features it tends to keep one; elastic net mixes both penalties and tends to keep the group3,6. counts the non-zero weights directly.
- A larger means a simpler model: more bias, less variance, a training error that can only stay the same or rise2, and a validation error that typically falls at first and rises again once the model underfits. is ordinary least squares. scikit-learn's
alpha(Ridge, Lasso) is the strength;CinLogisticRegressionand SVMs is its inverse. - The bias is usually left unpenalized2; then a huge flattens the fit to the horizontal line .
- The penalty depends on coefficient size, hence on units: rescaling a feature leaves OLS predictions unchanged but changes ridge and lasso fits, so standardize first. In Bayesian terms, ridge corresponds to a zero-mean Gaussian prior on the weights and lasso to a Laplace prior6.
Collinearity3. If one feature is an exact combination of others (), loses rank, is singular and OLS has infinitely many solutions. Near-collinearity makes nearly singular, so the coefficients get large variances and can flip sign3; predictions within the range of the training data are much less affected. Forming also squares the condition number, , so solvers work with QR or SVD factorizations of .
Classical assumptions5. With a model linear in its parameters, full column rank, and errors of zero mean, equal variance and no correlation with each other, OLS is the best linear unbiased estimator (Gauss–Markov). Normal errors are not needed for that — only for exact small-sample and tests. Correlated features are allowed; only perfect collinearity is excluded.
Formulas
(The ridge formula assumes centered data, so that the intercept, , is not penalized.)
One feature4: , .
Gradient of is , so each gradient step first multiplies by — weight decay2. An step instead moves every non-zero weight toward 0 by the same . With orthonormal features, the lasso soft-thresholds the OLS coefficients6; for this gives .
Worked example
Points : , , and , so the slope is and the intercept . The fitted values leave residuals , which sum to 0 (and ). With residual sum of squares 1.8 and total sum of squares 26, , equal to .
Ridge with and an unpenalized intercept: the slope becomes and the intercept . The slope is halved, and the line still passes through .
In code
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso, LinearRegression, Ridge
X, y = make_regression(n_samples=60, n_features=8, n_informative=3, # informative:
noise=5.0, random_state=0) # features 0, 2, 5
ols = LinearRegression().fit(X, y).coef_
ridge = Ridge(alpha=10.0).fit(X, y).coef_
lasso = Lasso(alpha=5.0).fit(X, y).coef_
print(ols.round(1)) # [76.6 -0.7 88.1 -0.7 0.5 96.8 0.3 1.2]
print(ridge.round(1)) # [64. 0.7 76.3 -3.9 0.1 81.1 1.4 3.4]
print(lasso.round(1) + 0.0) # [70.1 0. 84. 0. 0. 91.8 0. 0. ]
print(np.sum(ridge == 0), np.sum(lasso == 0)) # 0 5 (exact zeros)
OLS gives the five useless features small non-zero weights, ridge shrinks all weights but keeps them non-zero, and lasso sets exactly those five to zero.
Common pitfalls
- regularization never removes a feature; only (or ) produces exact zeros.
- Larger
alpha= stronger penalty = simpler model; largerC= weaker penalty. Don't mix up the two directions. - A large (or negative) coefficient alone says nothing about importance: units and correlated features change it.
- Increasing cannot lower the training error; it can lower or raise the test error.
- Polynomial regression is still linear regression. Its fit is governed by the degree, not by the solver or by the assumed noise variance.
- Near-collinearity inflates the variance of the coefficients but leaves OLS unbiased and predictions largely intact.
- Squared loss chases outliers (mean); absolute loss resists them (median).
- For an OLS fit with an intercept (no perfectly collinear features), a training means every slope is 0 and the fitted line is ; the intercept need not be 0.
References
- Dive into Deep Learning — Sec. 3.1 Linear Regression (3.1.1 Basics, 3.1.3 The Normal Distribution and Squared Loss)
- Dive into Deep Learning — Sec. 3.7 Weight Decay (3.7.1 Norms and Weight Decay, 3.7.2 High-Dimensional Linear Regression)
- scikit-learn User Guide — Sec. 1.1 Linear Models (1.1.1 Ordinary Least Squares, 1.1.2 Ridge regression and classification, 1.1.3 Lasso, 1.1.5 Elastic-Net)
- Wikipedia: Simple linear regression — Formulation and computation; Interpretation; Numerical properties
- Wikipedia: Gauss–Markov theorem — Statement; Gauss–Markov theorem as stated in econometrics
- Wikipedia: Lasso (statistics) — Basic form (Orthonormal covariates); Interpretations (Bayesian interpretation); Generalizations (Elastic net)