Linear regression: coefficients, controls and standard errors

55 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Fit a line by least squares, and read a slope as an average difference
  • Explain why controls change a coefficient, and compute the omitted variable bias
  • Tell a control that removes confounding or noise from one that adds bias
  • Read dummy variables and coefficients on a log outcome as percent differences
  • Choose robust standard errors, and say what R squared does and doesn't tell you

Regression and its coefficients, the way the rounds ask

An Airbnb coding round asked candidates to aggregate user activity, fit a regression and interpret the coefficients (1 source), and a Netflix statistics round asked why you add controls to a regression (1 report). This lesson's practice problem puts both in code with numpy, in three levels:

  1. ols(columns, y): the intercept and one slope per column, fitted all at once. r_squared(columns, y): the share of y's variation the fit explains.
  2. standard_errors(columns, y): the classical standard errors, and the robust ones, HC1.
  3. omitted_variable_bias(x, z, y): the slope without a control, with it, and the bias the formula predicts. percent_effect(b): a coefficient on log(y) as a percent.
CallReturns
ols([[1, 2, 3, 4]], [3, 5, 7, 9])[1.0, 2.0]: the intercept first, then one slope per column
r_squared for eight points on a steady climb0.9965
omitted_variable_bias(x, z, y) on 300 simulated rows3.517, 1.934 and 1.584: the first minus the second is the third
percent_effect(0.3)0.350, a 35% change

The lesson follows the shop's discounts and spending: least squares, controls and the bias they remove, good and bad controls, dummies and logs, and robust standard errors. Six steps end with a small task in the editor.

Part 1 of 7about 8 min
Least squares

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
Part 1 done
Part 2 of 7about 16 min
Controls

Add the confounder, and the coefficient compares like with like

Why add controls, as the Netflix statistics round asked (1 report)? Here's the answer in one run: put tenure in the model next to discount.

b2 = ols([discount, tenure], spend)
print(f"spend = {b2[0]:.1f} + {b2[1]:.2f} x discount + {b2[2]:.2f} x tenure")
Predict

With tenure in the model, what's the discount coefficient?

Pick one to see what it prints.
Predict

Tenure fixed the coefficient. Does that prove $1.51 is what a discount does?

Pick an answer above to see the rest

The omitted variable bias formula says how far off you were

Gelman and Hill show how to quantify the bias from leaving out one confounder. The coefficient without it equals the true one plus two links multiplied together: the confounder's effect on the outcome, and how much the confounder moves with the treatment.

# how much more tenure comes with each discount point
delta = ols([discount], tenure)[1]
print(f"naive {b[1]:.2f} - adjusted {b2[1]:.2f} = {b[1] - b2[1]:.2f}")
print(f"tenure's effect x tenure per discount point = {b2[2]:.2f} x {delta:.3f} = {b2[2] * delta:.2f}")
naive 4.62 - adjusted 1.51 = 3.10
tenure's effect x tenure per discount point = 7.81 x 0.397 = 3.10
Predict

When does leaving out a variable cause no bias at all?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 3 min
Good and bad controls

Some controls only cut noise, and some add bias

Not every control is about confounding. Gelman and Hill note that including a pre-test as a predictor increases the precision of the estimates: a variable measured before the treatment that predicts the outcome soaks up noise. That's what CUPED does in the experimentation track.

Predict

In a randomized test of a discount, why add last month's spending as a control?

Pick an answer above to see the rest
Predict

Read the two lines that build the data. Control for items, and what does the discount coefficient come out near?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 8 min
Dummies and logs

A dummy is a shift, and a log turns coefficients into percents

A dummy variable is 1 for one group and 0 for the rest, and its coefficient is the average gap between the groups at equal values of the other predictors.

Predict

Why not add both a member dummy and a non-member dummy, next to the intercept?

Pick an answer above to see the rest
Predict

On log spend, membership gets a coefficient of 0.144. How much more do members spend, at equal tenure?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 8 min
Standard errors

Classical standard errors assume equal noise everywhere

The classical standard errors rest on NIST's assumptions about the random errors: their means are zero and their standard deviation is constant. Spending isn't so tidy: customers with unusual discounts can be far more unpredictable. Halbert White's 1980 paper gave a covariance estimator that stays consistent even when the noise varies, and the two estimators are about equal when it doesn't and diverge when it does. statsmodels lists it as HC0, White's robust standard errors, with variants up to HC3. The code below uses HC1: HC0 scaled by n / (n − k), where k counts the coefficients with the intercept, the same small-sample fix the classical formula makes when it divides by n − k.

def standard_errors(columns, y):
    """Classical and HC1 robust standard errors for each coefficient."""
    X = np.column_stack([np.ones(len(y))] + list(columns))
    beta = np.linalg.lstsq(X, y, rcond=None)[0]
    resid = y - X @ beta
    k = X.shape[1]
    inv = np.linalg.inv(X.T @ X)
    classical = np.sqrt(np.diag(inv) * (resid @ resid) / (len(y) - k))
    meat = X.T @ (X * resid[:, None] ** 2)
    robust = np.sqrt(np.diag(inv @ meat @ inv) * len(y) / (len(y) - k))
    return classical, robust


gap = np.abs(discount - discount.mean())
# unusual discounts, noisy spend
noisy = 60 + 8 * tenure + 1.5 * discount + rng.normal(0, 1, n) * 5 * gap
classical, robust = standard_errors([discount, tenure], noisy)
print(f"standard error of the discount coefficient: classical {classical[1]:.3f}, robust {robust[1]:.3f}")
Predict

The noise is biggest for customers with unusual discounts. Which standard error is too small?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 4 min
The worked example

A worked example: user activity to coefficients, out loud

Here's the Airbnb question, worked out loud.

You have a table of user events. Aggregate each user's activity, fit a regression of their bookings on it, and interpret the coefficients.

1. Pick the unit and the window. One row per user, with activity counted before the outcome window, so no predictor is caused by the outcome.

2. Name the question. Prediction, or the effect of one thing? Gelman and Hill warn that a causal reading needs much stricter assumptions than prediction.

Predict

Users who used the wishlist book 30% more, controlling for their search count. What's the safe way to say it?

Pick an answer above to see the rest
Predict

Which belongs in the model of bookings on wishlist use: searches in the month before, or messages to hosts after the wishlist?

Pick an answer above to see the rest
Predict

Each user has 30 rows, one per day. Treat the rows as independent, and the standard errors come out how?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 8 min
Follow-ups

What R squared measures

Two follow-ups come up after regression questions. The first is what R² measures.

R² is the share of the outcome's variation the model explains: 1 minus the sum of squared residuals over the sum of squared distances of y from its mean.

Predict

Adding tenure raised R squared from 0.3 to 0.5. What does that show about the discount coefficient?

Pick an answer above to see the rest

Correlated predictors

The second follow-up is about predictors that move together. When they do, the model struggles to tell them apart. Airbnb's data science team reported that putting correlated marketing channels in one regression flipped the signs of most coefficients, a clear sign of multicollinearity. Group the correlated predictors, or report their combined effect.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.Spend rises $4.62 per discount point, but loyal customers get bigger discounts and spend more. With tenure added, the coefficient is $1.51. Why?

  2. 2.When does leaving a variable out cause no bias?

  3. 3.In an A/B test of a discount, should you control for the number of items in the cart?

  4. 4.A coefficient of 0.165 on log spend means what?

  5. 5.Why default to robust standard errors?

Practice

Sources (18)
  1. 4.4.3.1. Least Squares · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
    “are estimated by finding numerical values for the parameters that minimize the sum of the squared deviations between the observed responses and the functional portion of the model.”
  2. Regression and Other Stories: frontmatter and contents (section 6.3) · Andrew Gelman, Jennifer Hill and Aki Vehtari, Cambridge University Press · Jan 1, 2021
    “Interpret coefficients as comparisons, not effects”
  3. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “Causal interpretations of regression coefficients can only be justified by relying on much stricter assumptions than are needed for predictive inference.”
  4. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “In general, then, causal effects can be estimated using regression if the model includes all confounding covariates (predictors that can affect treatment assignment or the outcome) and if the model is correct.”
  5. A Survey of Causal Inference Applications at Netflix · Netflix Technology Blog · May 21, 2022
    “We analyzed the data across various languages and applied double machine learning methods to properly control for measured confounders.”
  6. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “We can quantify the bias incurred by excluding a confounding covariate in the context where a simple linear regression model is appropriate and there is only one confounding covariate.”
  7. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “If there is no association between the treatment and the purported confounder ... or if there is no association between the outcome and the confounder ... then the variable is not a confounder because there will be no bias”
  8. Directed Acyclic Graphs (Causal Inference: The Mixtape, first edition) · Scott Cunningham · Nov 19, 2026
    “In regression terms, open backdoor paths introduce omitted variable bias, and for all you know, the bias is so bad that it flips the sign entirely.”
  9. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “Including pre-test data as a predictor increases the precision of the estimates.”
  10. Chapter 9: Causal inference using regression on the treatment variable · Andrew Gelman and Jennifer Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models · Dec 9, 2007
    “we recommend controlling for pre-treatment covariates when estimating causal effects in experiments and observational studies. However, it is generally not a good idea to control for variables measured after the treatment.”
  11. Directed Acyclic Graphs (Causal Inference: The Remix) · Scott Cunningham · Nov 19, 2026
    “when you estimate a model and condition on a collider, it opens up spurious correlations between the treatment and outcome accessible via that now open backdoor path.”
  12. 4.2.1. What are the typical underlying assumptions in process modeling? · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
    “The means of the random errors are zero. The random errors have a constant standard deviation.”
  13. A Heteroskedasticity-Consistent Covariance Matrix Estimator and a Direct Test for Heteroskedasticity · Halbert White, Econometrica 48(4) · May 1, 1980
    “This paper presents a parameter covariance matrix estimator which is consistent even when the disturbances of a linear regression model are heteroskedastic.”
  14. A Heteroskedasticity-Consistent Covariance Matrix Estimator and a Direct Test for Heteroskedasticity · Halbert White, Econometrica 48(4) · May 1, 1980
    “in the absence of heteroskedasticity, the two estimators will be approximately equal, but will generally diverge otherwise.”
  15. statsmodels.regression.linear_model.RegressionResults.HC0_se · statsmodels documentation · Nov 19, 2026
    “White's (1980) heteroskedasticity robust standard errors.”
  16. Probability and Regression Review (Causal Inference: The Mixtape, first edition) · Scott Cunningham · Nov 19, 2026
    “I would encourage you not to fixate on R-squared in research projects where the aim is to estimate some causal effect, though. It's a useful summary measure, but it does not tell us about causality.”
  17. Airbnb at KDD 2023 · The Airbnb Tech Blog (Alex Deng) · Dec 22, 2023
    “In fact, when we include the correlated channels in the same regression, the coefficients flip signs for most channels, a clear sign of multicollinearity.”
  18. How Airbnb Measures Future Value to Standardize Tradeoffs · The Airbnb Tech Blog · Jul 13, 2021
    “after the matching stage, we could run a regression that directly controls for key features that we want an almost exact match for.”