2/12
Part 1 of 7 · Least squaresLearn and do

A regression line is the one with the smallest squared misses

Least squares, in NIST's words, picks the parameters that minimize the sum of the squared deviations between the observed values and the model. For one predictor the slope comes out as the covariance of x and y over the variance of x. Both must use the same divisor: np.cov divides by n − 1, so the code passes ddof=1 to make np.var do the same.

The shop wants to know what a discount does to spending. Loyal customers get bigger discounts, so the data has a trap in it, which the next part springs. The data here is simulated, so the truth is known: each discount point really adds $1.50.

import numpy as np

rng = np.random.default_rng(14)
n = 5_000
# years as a customer
tenure = rng.exponential(3.0, n)
# loyal customers get bigger discounts, in percent
discount = 5 + 2 * tenure + rng.normal(0, 3, n)
# each discount point really adds $1.50
spend = 60 + 8 * tenure + 1.5 * discount + rng.normal(0, 25, n)


def ols(columns, y):
    """Least squares with an intercept: returns [intercept, slope for each column]."""
    X = np.column_stack([np.ones(len(y))] + list(columns))
    return np.linalg.lstsq(X, y, rcond=None)[0]


b = ols([discount], spend)
print(f"spend = {b[0]:.1f} + {b[1]:.2f} x discount")
print(f"cov / var: {np.cov(discount, spend)[0, 1] / np.var(discount, ddof=1):.2f}")
Predict

Fit spend on discount alone. What slope comes out, when each point truly adds $1.50?

Pick one to see what it prints.
Pick an answer above to see the rest