50Regression from scratch

mediumpython
40:00

50 Regression from scratch

An Airbnb candidate had to aggregate user activity, fit a regression and interpret the coefficients (1 source), a Netflix statistics round asked why you add controls to a regression (1 report), and an Airbnb round asked for a user-day panel and a causal regression (1 source). This is practice in that shape, not a leaked question. Use numpy.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/50_regression -k level1. Earlier levels must keep passing.

Every function takes the predictors as a list of columns, each a list or array of the same length as y. y can be a plain list too, so convert with np.asarray(..., dtype=float) before you use numpy methods.

Level 1. Least squares. ols(columns, y) fits y on an intercept and every column at once, and returns a numpy array: the intercept, then one slope per column. np.linalg.lstsq solves least squares. r_squared(columns, y) is 1 minus the sum of squared residuals over the sum of squared distances of y from its own mean.

Level 2. Standard errors. standard_errors(columns, y) returns a tuple of two arrays, (classical, robust), each with one standard error per coefficient in the order ols uses. The classical one is the square root of the diagonal of (XᵀX)⁻¹ times the sum of squared residuals over n − k, where X includes the column of ones and k is its number of columns. The robust one, HC1, is the square root of the diagonal of (XᵀX)⁻¹ (Xᵀ diag(e²) X) (XᵀX)⁻¹ times n / (n − k), where e are the residuals.

Level 3. Controls and logs. omitted_variable_bias(x, z, y) returns three floats: the slope of y on x alone, the slope on x when z is in the model too, and z's coefficient in that second model times the slope of z on x alone. Every slope here comes from a fit with an intercept, and the slope of z on x means z regressed on x. The first minus the second always equals the third. percent_effect(coefficient) turns a coefficient from a model of log(y) into the percent change in y, as a fraction: e^b − 1.

Things to get right: the intercept, fitting all the columns together, n − k, the n / (n − k) correction, and which way the slope of z on x goes. Follow-ups from the lesson: controls that only cut noise, bad controls, and why a big R² doesn't mean causal.

solution.py
Run the tests to see which pass.