The idea
Given observations , simple linear regression looks for a line . A residual is the vertical difference between an observation and the prediction.
Least squares chooses and by minimizing the sum of squared residuals:
Squaring prevents positive and negative residuals from cancelling and penalizes large errors. For nonconstant input values, this objective is convex and has a unique minimum.
One explanatory variable
For a simple regression, differentiating with respect to and gives
The denominator is nonzero when the observed are not all identical.
Several explanatory variables
For observations and explanatory variables, collect the observations in a design matrix . Its first column contains ones for the intercept; each remaining column contains one feature. Put the unknown coefficients in and the observed targets in :
The least-squares estimator is
The gradient is
At a minimum it vanishes, which gives the normal equations
If has full column rank, is invertible and
Without full column rank, minimizers may not be unique. The minimum-norm solution is , where is the Moore–Penrose pseudoinverse. Numerical software normally uses a QR or singular-value decomposition instead of explicitly computing .
Python example
The following example generates noisy observations around and solves the regression with numpy.linalg.lstsq:
import numpy as np
rng = np.random.default_rng(42)
x = np.linspace(0, 10, 100)
y = 2 * x + 3 + rng.normal(0, 1, len(x))
X = np.column_stack((x, np.ones(len(x))))
coefficients, residuals, rank, singular_values = np.linalg.lstsq(
X, y, rcond=None
)
slope, intercept = coefficients
predictions = X @ coefficients
print(slope, intercept)
The same construction works with more features: add one column to for each feature. The fitted object then becomes a hyperplane in the feature space; it is not obtained by intersecting separate hyperplanes.