Linear Regression in Python From Scratch: Math, Code and a Real Dataset

Derive linear regression, build it in NumPy two ways, match scikit-learn to 1e-13 and see why gradient descent needs scaled features, with data.

Scatter of patients' BMI against diabetes progression with a fitted regression line and vertical residual lines.

Fit the same linear model to the same 353 patients twice with gradient descent. With the features in their raw units, the error is still 6.0% above the best possible value after 1,000,000 steps. Standardize the features first and gradient descent lands on the exact least squares answer in 6,403 steps. Nothing else changed: same data, same model, same safe step size.

This tutorial explains linear regression from the model and its loss function to the closed-form solution and gradient descent, then implements both from scratch in NumPy, checks them against scikit-learn and tests them on a real medical dataset with a baseline. Every program was run for this article with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04, again on Python 3.13, and on Windows 11 with Python 3.14.6; all 22 unit tests pass on both systems, and every output block on this page is captured from the companion repository.

What Is Linear Regression?

Linear regression is a supervised learning algorithm that predicts a numeric value as a weighted sum of the input features plus a constant. Training picks the weights that minimize the mean squared difference between the predictions and the observed values. That problem has an exact solution (least squares), and gradient descent can also find it step by step.

With one input feature the model is a straight line, which is called simple linear regression. With several features it is a flat surface in more dimensions, called multiple linear regression; the mathematics and the code are the same. The method of least squares behind it goes back to Legendre (1805) and Gauss (1809), and it is still the first model to try on any regression problem, because it is fast, has no settings to tune and its weights can be read directly. In Python, the standard implementation is scikit-learn’s LinearRegression, which this article rebuilds by hand and then uses as a reference.

When to Use Linear Regression (and When Not To)

SituationGood fit?Why
Predicting a number (price, demand, a medical score) from a handful of featuresYesThis is the task the model was made for
You need to explain how each feature moves the predictionYesEach weight is the change in the prediction per unit of its feature, other features held fixed
You need a baseline before trying complex modelsYesSeconds to fit, no hyperparameters; any fancier model has to beat it
The relationship is curved or has thresholdsNot as isAdd transformed features (squares, logs) or use a tree-based model
The target is a category (spam or not spam)NoUse logistic regression, a classification model
Many strongly correlated features, or more features than rowsWith careWeights become unstable; ridge or lasso regularization helps
Large outliers in the targetWith careSquared error lets a few points pull the line; consider a robust loss

How Linear Regression Works

  1. Arrange the data. Put the features in a matrix X with one row per example and one column per feature, and the targets in a vector y. Add a column of ones to X so the model can learn a constant term (the intercept).
  2. Choose the loss. Linear regression uses the mean squared error: the average of the squared differences between predictions and targets.
  3. Find the weights. Either solve for the minimum directly with least squares, or start from zero and repeatedly step against the gradient of the loss (gradient descent).
  4. Evaluate on unseen data. Measure the error on a held-out test set and compare it with a baseline that always predicts the training mean.
  5. Check the residuals. Plot the prediction errors to see whether a straight-line model suits the data.

In pseudocode:

Xb    = [1 | X]                      # prepend a column of ones
theta = least_squares(Xb, y)         # or: gradient descent below

theta = 0
repeat until the gradient is tiny:
    gradient = (2 / n) * Xb^T (Xb theta - y)
    theta    = theta - step * gradient

predict(x) = theta[0] + x . theta[1:]

The Math Behind Linear Regression

The model

where ŷ is the prediction, x1 to xp are the p features of one example, θ0 is the intercept and θ1 to θp are the weights. Stacking the n examples as rows of a matrix X whose first column is all ones, the predictions for the whole dataset are Xθ.

The loss: mean squared error

where yi is the observed target of example i and ‖·‖ is the length of a vector. Squaring makes every error positive and punishes large errors more than small ones. The loss is a bowl-shaped (convex) function of θ, so it has no local minima to get stuck in: any point where the slope is zero is the best answer.

The closed-form solution

For one feature, setting the derivatives to zero gives the slope and intercept directly:

where x̄ and ȳ are the means of the feature and the target. For any number of features, the same condition gives the normal equations:

The right-hand formula is how the solution is usually written, but it is not how it should be computed. Forming X⊤X squares the condition number of the problem, and inverting it fails, sometimes silently, when two features are perfectly correlated (the Common Mistakes section shows a case). Numerical libraries solve the least squares problem from X itself instead: numpy.linalg.lstsq uses the singular value decomposition, and scikit-learn’s LinearRegression calls SciPy’s lstsq.

Gradient descent

Gradient descent does not solve the equations at all. It starts with all weights at zero and walks downhill. The gradient of the loss is

and each step moves the weights against it:

where η is the step size (learning rate) and λmax is the largest eigenvalue of the loss’s curvature matrix. With a fixed step of 1/L or smaller, gradient descent on this loss is guaranteed to converge, and above 2/L it diverges. How fast it converges depends on the condition number, the ratio of the largest to the smallest eigenvalue of X⊤X: the number of steps grows roughly in proportion to it (Tibshirani, Convex Optimization lecture notes). That one fact explains the experiment in the introduction.

Measuring the fit: R²

The numerator is the sum of squared residuals (SSE); the denominator is the error of always predicting the mean (SST). R² = 1 is a perfect fit, 0 is no better than the mean, and on test data it can be negative, which means worse than the mean.

A Worked Example by Hand

Five students report hours studied and their exam score (a small, made-up dataset chosen so every step can be checked by hand):

Hours (x)Score (y)x − x̄y − ȳ(x − x̄)(y − ȳ)(x − x̄)²
152−2−8164
255−1−551
3610100
4641441
56828164
Sum4110

The means are x̄ = 3 and ȳ = 60. The slope is 41 / 10 = 4.1 points per hour, and the intercept is 60 − 4.1 × 3 = 47.7. So the fitted line is score = 47.7 + 4.1 × hours. The residuals (observed minus predicted) are 0.2, −0.9, 1.0, −0.1 and −0.2; their squares sum to SSE = 1.90, while the squared distances from the mean sum to SST = 170, so R² = 1 − 1.90 / 170 = 0.9888.

1 2 3 4 5 hours studied 50 55 60 65 70 exam score +0.2 −0.9 +1.0 −0.1 −0.2 Least squares picks the line with the smallest sum of squared residuals fitted line: score = 47.7 + 4.1 × hours observed score residual (observed − predicted)
Figure 1: The five-point example. The fitted line is score = 47.7 + 4.1 × hours; the dashed segments are the residuals, whose squares sum to 1.90.

The program below repeats the calculation by hand, then fits the same data with both methods of the from-scratch class:

"""The article's worked example: five students, hours studied vs exam score."""

import numpy as np

from linear_regression import LinearRegressionScratch

hours = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
score = np.array([52.0, 55.0, 61.0, 64.0, 68.0])

# By hand: slope = Sxy / Sxx, intercept = mean(y) - slope * mean(x)
x_mean, y_mean = hours.mean(), score.mean()
s_xy = np.sum((hours - x_mean) * (score - y_mean))
s_xx = np.sum((hours - x_mean) ** 2)
slope = s_xy / s_xx
intercept = y_mean - slope * x_mean
print(f"By hand:  slope = {s_xy:.1f} / {s_xx:.1f} = {slope:.4f}")
print(
    f"          intercept = {y_mean:.1f} - {slope:.1f} * {x_mean:.1f} = {intercept:.4f}"
)

X = hours.reshape(-1, 1)  # one feature, so one column
exact = LinearRegressionScratch(method="lstsq").fit(X, score)
descent = LinearRegressionScratch(method="gd").fit(X, score)
print(f"lstsq:    slope = {exact.coef_[0]:.4f}, intercept = {exact.intercept_:.4f}")
print(
    f"gd:       slope = {descent.coef_[0]:.4f}, intercept = {descent.intercept_:.4f}"
    f"  ({descent.n_iter_} iterations, step {descent.learning_rate_:.5f})"
)

predicted = exact.predict(X)
residuals = score - predicted
print("\nhours  score  predicted  residual")
for x, y, p, r in zip(hours, score, predicted, residuals, strict=True):
    print(f"{x:5.0f}  {y:5.0f}  {p:9.1f}  {r:8.1f}")

sse = np.sum(residuals**2)
sst = np.sum((score - y_mean) ** 2)
print(f"\nSSE = {sse:.2f}, SST = {sst:.2f}, R^2 = 1 - SSE/SST = {1 - sse / sst:.4f}")

Output:

By hand:  slope = 41.0 / 10.0 = 4.1000
          intercept = 60.0 - 4.1 * 3.0 = 47.7000
lstsq:    slope = 4.1000, intercept = 47.7000
gd:       slope = 4.1000, intercept = 47.7000  (1214 iterations, step 0.04226)

hours  score  predicted  residual
    1     52       51.8       0.2
    2     55       55.9      -0.9
    3     61       60.0       1.0
    4     64       64.1      -0.1
    5     68       68.2      -0.2

SSE = 1.90, SST = 170.00, R^2 = 1 - SSE/SST = 0.9888

Least squares reproduces the hand calculation exactly. Gradient descent reaches the same line to four decimals, but it needs 1,214 steps even on five points, because the hours column (values 1 to 5) and the column of ones point in similar directions. That is a small preview of the scaling problem measured later.

Linear Regression in Python From Scratch

The whole model lives in linear_regression.py, which needs only NumPy. Four small helpers do the mathematics, each matching one equation above:

def add_intercept(X: FloatArray) -> FloatArray:
    """Prepend a column of ones so that theta[0] is the intercept."""
    return np.column_stack([np.ones(X.shape[0]), X])


def mse(Xb: FloatArray, y: FloatArray, theta: FloatArray) -> float:
    """Mean squared error of the predictions Xb @ theta."""
    residuals = Xb @ theta - y
    return float(residuals @ residuals) / len(y)


def gradient(Xb: FloatArray, y: FloatArray, theta: FloatArray) -> FloatArray:
    """Gradient of the mean squared error with respect to theta."""
    return (2.0 / len(y)) * (Xb.T @ (Xb @ theta - y))


def lipschitz_constant(Xb: FloatArray) -> float:
    """Largest eigenvalue of the MSE Hessian (2/n) Xb^T Xb.

    Gradient descent with a fixed step converges for any step below 2/L;
    1/L is the safe default.
    """
    hessian = (2.0 / Xb.shape[0]) * (Xb.T @ Xb)
    return float(np.linalg.eigvalsh(hessian)[-1])

add_intercept builds the matrix X with its column of ones. mse is the mean squared error, gradient is its gradient from the formula above, and lipschitz_constant computes L from the update rule, so the default step 1/L is always safe.

The fit method validates the input, adds the intercept column and then either calls the least squares solver or runs gradient descent:

    def fit(self, X: ArrayLike, y: ArrayLike) -> LinearRegressionScratch:
        X_arr, y_arr = _validate(X, y)
        Xb = add_intercept(X_arr)
        if self.method == "lstsq":
            theta = np.linalg.lstsq(Xb, y_arr)[0]
            self.n_iter_ = 0
            self.converged_ = True
            self.loss_history_ = [mse(Xb, y_arr, theta)]
        else:
            theta = self._gradient_descent(Xb, y_arr)
        self.intercept_ = float(theta[0])
        self.coef_ = theta[1:]
        return self

np.linalg.lstsq returns the weight vector that minimizes the squared error; the first entry is the intercept and the rest are the feature weights. Gradient descent is the loop from the pseudocode, with three practical additions: it stops when the gradient has shrunk by a factor of 10⁹ from where it started, it raises a clear error if the loss blows up (a step that is too large), and it warns if it runs out of iterations before converging:

    def _gradient_descent(self, Xb: FloatArray, y: FloatArray) -> FloatArray:
        lr = self.learning_rate
        if lr is None:
            lr = 1.0 / lipschitz_constant(Xb)
        theta = np.zeros(Xb.shape[1])
        grad = gradient(Xb, y, theta)
        stop_at = self.tol * float(np.linalg.norm(grad))
        history = [mse(Xb, y, theta)]
        converged = float(np.linalg.norm(grad)) <= stop_at
        iteration = 0
        with np.errstate(over="ignore", invalid="ignore"):
            while not converged and iteration < self.max_iter:
                iteration += 1
                theta = theta - lr * grad
                grad = gradient(Xb, y, theta)
                loss = mse(Xb, y, theta)
                if not np.isfinite(loss):
                    raise FloatingPointError(
                        f"gradient descent diverged at iteration {iteration}; "
                        "lower the learning rate"
                    )
                history.append(loss)
                converged = float(np.linalg.norm(grad)) <= stop_at
        if not converged:
            warnings.warn(
                f"gradient descent stopped after {self.max_iter} iterations "
                "without converging; scale the features or raise max_iter",
                RuntimeWarning,
                stacklevel=3,
            )
        self.learning_rate_ = lr
        self.n_iter_ = iteration
        self.converged_ = converged
        self.loss_history_ = history
        return theta

Prediction is one matrix product plus the intercept:

    def predict(self, X: ArrayLike) -> FloatArray:
        X_arr = np.asarray(X, dtype=np.float64)
        if X_arr.ndim != 2 or X_arr.shape[1] != len(self.coef_):
            raise ValueError(f"X must have shape (n_samples, {len(self.coef_)})")
        return X_arr @ self.coef_ + self.intercept_

The repository’s tests check the parts most likely to go wrong: agreement with the hand calculation and with scikit-learn, the normal equations holding at the solution (every column of X is orthogonal to the residuals), the loss never increasing with the default step, a FloatingPointError when the step exceeds 2/L, and inputs such as a 1-D X, NaN values, a constant column or more features than rows. A separate script re-applies 11 plausible bugs to a copy of the code; every one makes a test fail, including a gradient missing its factor of 2. That bug still converges to the right weights, so no test of the final answer notices it; it is caught by the tests that check the number of steps taken and the step size at which gradient descent diverges.

Linear Regression on a Real Dataset

The diabetes dataset that ships with scikit-learn has 442 patients, 10 measurements taken at a baseline visit and a target that measures disease progression one year later. It comes from the paper that introduced least angle regression (Efron, Hastie, Johnstone and Tibshirani, 2004).

PropertyValue
Sourcesklearn.datasets.load_diabetes, bundled with scikit-learn (documentation)
Rows and features442 patients, 10 numeric features
Featuresage, sex, BMI, average blood pressure and six blood serum measurements (s1 to s6: total cholesterol, LDL, HDL, total/HDL ratio, a triglyceride measure, blood sugar)
TargetDisease progression one year after baseline, from 25 to 346
Missing valuesNone
Preprocessing hereLoaded with scaled=False (raw units); standardized with a scaler fitted on the training rows only
Split80/20, random_state=42: 353 training rows, 89 test rows

By default load_diabetes returns features that were already centered and scaled using all 442 rows, test rows included. Loading the raw values and fitting the scaler on the training rows keeps the test set out of every step of training. For ordinary least squares the predictions would come out the same either way, because rescaling features does not change them (mistake 3 below shows this), but the habit matters for every model that is sensitive to scale.

The experiment fits four models on the same standardized training data: a baseline that always predicts the training mean, the from-scratch model with least squares, the from-scratch model with gradient descent and scikit-learn’s LinearRegression:

# Raw units (age in years, BMI, blood pressure in mm Hg ...), not the
# pre-scaled copy, so that the scaler is fitted on training rows only.
data = load_diabetes(scaled=False)
X, y = data.data, data.target
names = list(data.feature_names)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
Xs_train, Xs_test = scaler.transform(X_train), scaler.transform(X_test)

models = {
    "baseline (predict the mean)": DummyRegressor(strategy="mean"),
    "scratch, lstsq": LinearRegressionScratch(method="lstsq"),
    "scratch, gradient descent": LinearRegressionScratch(method="gd"),
    "scikit-learn LinearRegression": LinearRegression(),
}
print(f"train rows: {len(y_train)}, test rows: {len(y_test)}\n")
print(f"{'model':32} {'MAE':>7} {'RMSE':>7} {'R^2':>7}")
results = {}
for label, model in models.items():
    model.fit(Xs_train, y_train)
    pred = model.predict(Xs_test)
    mae = mean_absolute_error(y_test, pred)
    rmse = float(np.sqrt(mean_squared_error(y_test, pred)))
    r2 = r2_score(y_test, pred)
    results[label] = {"mae": mae, "rmse": rmse, "r2": r2}
    print(f"{label:32} {mae:7.2f} {rmse:7.2f} {r2:7.3f}")

Output (the full script also repeats the split 100 times and checks how stable the weights are):

train rows: 353, test rows: 89

model                                MAE    RMSE     R^2
baseline (predict the mean)        64.01   73.22  -0.012
scratch, lstsq                     42.79   53.85   0.453
scratch, gradient descent          42.79   53.85   0.453
scikit-learn LinearRegression      42.79   53.85   0.453

gradient descent: 6403 iterations
largest coefficient gap, scratch lstsq vs scikit-learn: 7.8e-14
largest coefficient gap, gradient descent vs lstsq:     1.4e-05

coefficients (per standard deviation of each feature):
  s1     -44.45
  s5      35.16
  bmi     25.61
  s2      24.64
  bp      16.83
  s4      13.14
  sex    -11.51
  s3       7.68
  s6       2.35
  age      1.75
  intercept 153.74

test R^2 over 100 random 80/20 splits:
  linear regression  mean 0.467  std 0.070  min 0.258  max 0.658
  baseline           mean -0.013  std 0.017

coefficient spread over the same 100 splits:
  s1   mean  -38.59  std   9.47  range  -64.37 to  -17.74
  s2   mean   23.45  std   7.35  range    5.06 to   41.03
  bmi  mean   24.78  std   1.64  range   19.33 to   28.52
  bp   mean   15.78  std   1.74  range   11.73 to   19.97
correlation of s1 and s2 in the training rows: 0.891

Reading the results:

  • The model is useful but far from perfect. On the test rows, linear regression cuts the root mean squared error from 73.22 (baseline) to 53.85 and reaches R² = 0.453: it explains about 45% of the variation in disease progression. The other 55% depends on things the ten baseline measurements do not capture, or on relationships that are not straight lines.
  • All three linear models agree. The from-scratch least squares weights match scikit-learn to 7.8 × 10⁻¹⁴, which is floating-point rounding. Gradient descent agrees with least squares to 1.4 × 10⁻⁵ after 6,403 steps, close enough that all three give identical metrics to two decimals.
  • One test score is one draw. Over 100 different random 80/20 splits, test R² averaged 0.467 but ranged from 0.258 to 0.658. With 89 test rows, which patients land in the test set moves the score more than many modelling choices would. Report the spread, or use cross-validation, before comparing models.
  • Correlated features share credit unpredictably. s1 (total cholesterol) has the largest weight, −44.45, and s2 (LDL) a large positive one, +24.64. The two are correlated at 0.891 in the training rows, so the model can trade weight between them: across the 100 splits the s1 weight ranged from −64.37 to −17.74, while the BMI weight stayed between 19.33 and 28.52. Do not read the weights of correlated features one at a time.

The residual plot is the standard check that a straight-line model suits the data:

50 100 150 200 250 300 predicted disease progression −150 −100 −50 0 50 100 residual (observed − predicted) Diabetes test rows: residuals against predictions
Figure 2: Residuals of the least squares model on the 89 diabetes test rows (RMSE 53.85).

The residuals scatter around zero with no curve, so the linear form is reasonable; their size (most within about ±100 on a 25 to 346 scale) is what an R² of 0.45 looks like.

Why Gradient Descent Needs Scaled Features

Least squares gives the same predictions whatever units the features are in. Gradient descent ends at those same predictions too, but how long it takes to get there depends entirely on the units. The scaling experiment runs gradient descent on the 353 training rows twice, once on the raw features (age in years, blood pressure in mm Hg, cholesterol values in the hundreds) and once on standardized features, with the safe step 1/L each time and a limit of one million steps:

for label, features in inputs.items():
    Xb = add_intercept(features)
    hessian_eigs = np.linalg.eigvalsh((2.0 / len(y_train)) * (Xb.T @ Xb))
    condition = hessian_eigs[-1] / hessian_eigs[0]
    best = mse(Xb, y_train, np.linalg.lstsq(Xb, y_train)[0])

    model = LinearRegressionScratch(method="gd", max_iter=MAX_ITER)
    start = time.perf_counter()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RuntimeWarning)
        model.fit(features, y_train)
    seconds = time.perf_counter() - start
    gap = (model.loss_history_[-1] - best) / best

Output (the seconds column depends on the machine; the step counts do not):

features       condition no.    step 1/L  iterations  converged  loss gap  seconds
raw units           4.99e+07     6.8e-06   1,000,000      False   6.0e-02     13.7
standardized             430       0.126       6,403       True   1.3e-15      0.1

relative loss gap (loss - best) / best after k steps:
        k   raw units  standardized
       10     9.3e-01       3.8e-02
      100     6.7e-01       6.9e-03
    1,000     2.7e-01       1.0e-04
   10,000     1.2e-01     converged
  100,000     9.2e-02     converged
1,000,000     6.0e-02     converged
1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 gradient descent step (log scale) 1 0 − 1 6 1 0 − 1 4 1 0 − 1 2 1 0 − 1 0 1 0 − 8 1 0 − 6 1 0 − 4 1 0 − 2 1 0 0 (loss − best loss) / best loss standardized: converged at 6,403 steps raw: still 6.0% above the best loss after 1,000,000 steps Same data, same model, same safe step 1/L: only the feature units differ raw units (condition number 5.0 × 10⁷) standardized (condition number 430)
Figure 3: Gradient descent on the 353 diabetes training rows. With raw features the loss is still 6.0% above the least squares optimum after 1,000,000 steps; with standardized features it converges in 6,403.

The condition number explains the result. In raw units, the curvature of the loss is about 50 million times larger in its steepest direction than in its flattest one (condition number 5.0 × 10⁷). The step size must be small enough for the steep direction, 6.8 × 10⁻⁶, so progress along the flat direction is almost nil: after a million steps the loss is still 6.0% above the optimum and still falling slowly. Standardizing gives every feature mean 0 and standard deviation 1, which brings the condition number down to 430 and allows a step of 0.126. Gradient descent then converges to within 1.3 × 10⁻¹⁵ of the optimum in 6,403 steps.

Two practical rules follow. Standardize features before any gradient-based training, which also applies to regularized linear models, neural networks and anything else fitted by gradient descent. And when an exact solver is available, as it is for ordinary least squares, use it: lstsq solved both versions of this problem directly, with no step size and no iterations.

Complexity and Scaling

MethodTimeMemoryUse when
Least squares (lstsq, SVD or QR)About O(n p²) for n rows and p featuresThe n × p matrixp up to a few thousand; the default choice
Batch gradient descentO(n p) per step, times the number of stepsThe matrix, plus p weightsTeaching, or as the basis for the methods below
Stochastic or mini-batch gradient descentO(b p) per step for a batch of b rowsOne batch at a timeData too large for memory, or streaming data

(If big-O notation is new to you, breaking down complex algorithms explains how to read it.) Prediction always costs O(p) per example, one multiply-add per feature, which is why a trained linear model is easy to deploy almost anywhere, including in C or C++ with no machine learning library at all; machine learning with C++ covers the general case of running trained models outside Python.

Common Mistakes With Linear Regression

1. Solving the normal equations with an inverse. If two columns are perfectly correlated (the same quantity in two units, or a one-hot encoding plus an intercept), X⊤X is singular. In floating point it may not look singular, and a direct solve may raise an error or may return nonsense without one. Here BMI is added a second time, multiplied by 10:

gram = X_dup.T @ X_dup
print(f"columns: {X_dup.shape[1]}, rank of X: {np.linalg.matrix_rank(X_dup)}")
print(f"condition number of X^T X: {np.linalg.cond(gram):.1e}")

try:
    theta_ne = np.linalg.solve(gram, X_dup.T @ y)
    pred_ne = X_dup @ theta_ne
    print("normal equations: solve() returned without an error")
    print(f"  bmi weights: {theta_ne[3]:.4g} and {theta_ne[-1]:.4g}")
    print(f"  training MSE: {np.mean((pred_ne - y) ** 2):.2f}")
except np.linalg.LinAlgError as err:
    print(f"normal equations: LinAlgError: {err}")

theta_ls, _, rank, _ = np.linalg.lstsq(X_dup, y)
pred_ls = X_dup @ theta_ls
print(f"lstsq: rank {rank}, bmi weights {theta_ls[3]:.4g} and {theta_ls[-1]:.4g}")
print(f"  training MSE: {np.mean((pred_ls - y) ** 2):.2f}")

Output on Ubuntu 24.04:

columns: 12, rank of X: 11
condition number of X^T X: 1.0e+18
normal equations: solve() returned without an error
  bmi weights: -2.296e+13 and 2.296e+12
  training MSE: 2925.18
lstsq: rank 11, bmi weights 0.05547 and 0.5547
  training MSE: 2859.70
without the copy: bmi weight 5.603, training MSE 2859.70

On Ubuntu, np.linalg.solve returned weights in the tens of trillions and a worse fit, with no warning. On a Windows 11 PC, with the same NumPy version and the same data, the same call raised LinAlgError: Singular matrix. On a GitHub Actions Windows runner with Python 3.13, it raised nothing and returned an ordinary-looking BMI weight of 2.41. Three machines, three behaviours: what happens with a singular system depends on rounding inside the linear algebra library, so code can count on neither an error nor an obviously wrong answer. lstsq gave the same answer on both systems: it detected that the matrix has rank 11, not 12, and split the BMI weight between the two copies (0.05547 + 10 × 0.5547 = 5.603, the weight BMI gets on its own).

2. Forgetting the intercept. Without the column of ones, the fitted surface must pass through the origin. On the standardized diabetes data, whose target averages about 154, that is catastrophic:

# Wrong: no column of ones, so the fitted line must pass through the origin.
w = np.linalg.lstsq(Xs_train, y_train)[0]
print(f"without intercept: test R^2 = {r2_score(y_test, Xs_test @ w):.3f}")

# Right: prepend the column of ones.
ones_train = np.column_stack([np.ones(len(y_train)), Xs_train])
ones_test = np.column_stack([np.ones(len(y_test)), Xs_test])
theta = np.linalg.lstsq(ones_train, y_train)[0]
print(
    f"with intercept:    test R^2 = {r2_score(y_test, ones_test @ theta):.3f}"
    f"  (intercept {theta[0]:.2f}, mean of y_train {y_train.mean():.2f})"
)

Output:

without intercept: test R^2 = -4.235
with intercept:    test R^2 = 0.453  (intercept 153.74, mean of y_train 153.74)

A test R² of −4.235 means the model is more than five times worse than predicting the mean. With standardized features the fitted intercept equals the mean of the training targets exactly, as the output shows.

3. Reading raw-unit weights as feature importance. A weight is “change in prediction per unit of the feature”, so it depends on the unit. Fitted on all 442 patients, the same model looks very different in raw units and per standard deviation:

feature   raw units  per std dev
s5           68.483        35.73
sex         -22.860       -11.41
s4            6.534         8.42
bmi           5.603        24.73
bp            1.117        15.43
s1           -1.090       -37.68
s2            0.746        22.68
s3            0.372         4.81
s6            0.280         3.22
age          -0.036        -0.48

BMI weight: 5.603 -> 0.5603 after BMI x 10; predictions unchanged: True

In raw units, sex looks like the second most important feature because it is coded 1 or 2, and s1 looks minor because cholesterol values are in the hundreds. Per standard deviation, s1 has the largest weight. Rescaling BMI by 10 divides its weight by 10 and leaves every prediction unchanged. Compare weights only on standardized features, and even then remember the correlated pair above.

4. Trusting a single split. As measured above, the same model scored anywhere from 0.258 to 0.658 depending on the split. Report the spread over repeated splits or use k-fold cross-validation.

5. Extrapolating. The fitted line is only checked where the training data lives. Predicting far outside that range (a BMI of 60 when the data stops at 42) assumes the straight line continues, which the data cannot confirm.

ModelPredictsHandles curvesKey difference from linear regression
Linear regressionA numberOnly with added featuresThe baseline: least squares, exact solution
Polynomial regressionA numberYesLinear regression on powers of the features
Ridge and lasso regressionA numberOnly with added featuresAdd a penalty on the weights; stable with correlated features; lasso can set weights to zero
Logistic regressionA probability of a classOnly with added featuresSame weighted sum, passed through a sigmoid; trained with log loss
Decision tree regressionA numberYesSplits the data into regions; no straight-line assumption, but piecewise and less smooth
k-nearest neighbors regressionA numberYesAverages the targets of the closest training examples; no training step

Key Takeaways

  • Linear regression predicts a number as a weighted sum of features plus an intercept, and training minimizes the mean squared error.
  • Solve ordinary least squares with lstsq, not an explicit inverse. On collinear data, solving the normal equations directly raised an error on one machine, returned weights in the trillions on another and returned plausible-looking weights on a third.
  • Gradient descent reaches the same answer only if the features are scaled. On the diabetes data it converged in 6,403 steps when standardized and was still 6.0% off after 1,000,000 steps in raw units.
  • Always compare with a baseline. Linear regression reached test R² 0.453 where predicting the mean scored −0.012.
  • One train/test split is one sample. The same model’s test R² ranged from 0.258 to 0.658 over 100 splits.
  • Weights are not importances unless the features share a scale, and correlated features trade weight from split to split.

Conclusion

Linear regression is small enough to derive on one page and implement in a hundred lines, yet it already shows the habits every model needs: a baseline to beat, a held-out test set touched once, more than one split, and residuals checked by eye. It also shows the difference between a model and the way it is fitted. Least squares and gradient descent produce the same line, but one is exact in a single call and the other depends on the units of the data.

Those same pieces carry straight into the next models. Logistic regression keeps the weighted sum and changes the loss, regularized regression adds a penalty to the same objective, and neural networks are trained by the same gradient descent loop on a much larger scale. More tutorials in this series are collected in the artificial intelligence section.

Source Code and Tests

Linear regression build status

All programs on this page are in the machine-learning/linear-regression directory of the MYCPLUS Python examples repository.

Build and test:

python -m pip install -r requirements-dev.txt
python -m unittest discover -s tests -v
sh run_all.sh

What the build checks. On Linux and Windows, with Python 3.13, 3.14 and 3.15 and the pinned NumPy and scikit-learn versions, the build runs ruff and mypy --strict, the 22 unit tests, and checks that the worked example and two of the pitfall programs print exactly the output shown on this page. It also runs the diabetes experiment, and on Linux re-applies 11 deliberate bugs and confirms that each one makes a test fail. It does not check timings.

What I Verified

CheckUbuntu 24.04Windows 11
EnvironmentPython 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1; every output block on this page captured from these runsWindows 11 (build 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1
Same programs on Python 3.13.18Identical output for the worked example, both pitfall programs and the diabetes experimentNot applicable
22 unit tests (unittest)PassPass
ruff check, ruff format --check, mypy --strictNo issuesNo issues
Output of the worked example and two pitfall programsMatches this pageMatches this page
Diabetes experimentMetrics as shown; largest weight difference from scikit-learn 7.8 × 10⁻¹⁴Same metrics, splits and weights; largest weight difference 7.3 × 10⁻¹⁴
Gradient descent, raw vs standardized features1,000,000 steps without converging vs 6,403Same step counts and loss gaps
Normal equations on collinear columnssolve() returned weights of −2.3 × 10¹³ with no errorsolve() raised LinAlgError: Singular matrix
11 deliberate bugsAll 11 caughtAll 11 caught

Not covered: macOS, ARM processors, other NumPy or scikit-learn versions, and GPU or multi-threaded BLAS settings other than the defaults.

Scroll to Top