Quickstart¶
examples/quickstart.py
fits the two kinds of model this package is for, on the 2023 American
Community Survey’s Californians aged 25 to 64: a lasso that predicts wages
from about 2,000 indicators, and the gender wage gap after selecting
controls from the same indicators.
Data¶
load_acs() downloads the Census Bureau’s file the first time and returns
the path of a Parquet file. Nothing reads it whole: the fits stream it.
from acs_data import EDUCATION, WAGE_PREDICTORS, load_acs, rhs
from penalized_stream import double_selection_stream, lasso_stream
acs = load_acs()
WAGE_PREDICTORS are 39 characteristics: age, sex, race, Hispanic origin,
marital status, birthplace, language, ancestry, education, field of degree,
disabilities, health coverage, military service, and the job’s occupation,
industry, class of worker, hours, weeks and commute. Each is a code, so
rhs() enters each as a categorical, C(occupation): about 2,000
indicator columns in all.
A cross-validated lasso¶
fit = lasso_stream(f"log_wage ~ {rhs(WAGE_PREDICTORS)}", acs, verbose=False)
print(f"{fit.n_obs:,} workers, {len(fit.coefnames)} indicators, "
f"{len(fit.selected())} selected at lambda_min, "
f"{len(fit.selected('lambda_1se'))} at lambda_1se")
print(f"cross-validated mean squared error: {fit.cv_mean.min():.4f} "
f"(with no predictors: {fit.cv_mean.max():.4f})")
149,192 workers, 1972 indicators, 1524 selected at lambda_min, 1001 at lambda_1se
cross-validated mean squared error: 0.3666 (with no predictors: 0.6644)
The penalty is chosen by 5-fold cross-validation over 100 penalties, all
from one pass over the data: each fold’s cross-products are kept apart, so
every fold’s fit and held-out error come from them. The predictors explain
about 45% of the variance of log wages. lambda_min is the penalty with the
smallest cross-validated error; lambda_1se, the largest within one
standard error of it, keeps a third fewer indicators.
fit.plot_cv() draws the cross-validated error along the path:
ax = fit.plot_cv()
ax.figure.savefig("output/quickstart_cv.svg")
The coefficients are on the outcome’s scale, here log points. Education’s, relative to no schooling and holding the other selected indicators fixed:
coef = fit.coef()
print(pl.DataFrame({"education": list(EDUCATION.values()),
"coefficient": [coef.get(f"C(education)[T.{k}]", 0.0) for k in EDUCATION]}))
┌────────────────────────┬─────────────┐
│ education ┆ coefficient │
╞════════════════════════╪═════════════╡
│ grade 6 ┆ -0.033286 │
│ grade 10 ┆ 0.0 │
│ high school diploma ┆ 0.006601 │
│ GED ┆ 0.000658 │
│ some college, 1+ years ┆ 0.050417 │
│ associate's degree ┆ 0.037102 │
│ bachelor's degree ┆ 0.189295 │
│ master's degree ┆ 0.313978 │
│ professional degree ┆ 0.363058 │
│ doctorate ┆ 0.428907 │
└────────────────────────┴─────────────┘
A lasso’s coefficients are shrunk toward zero, and they are conditional on the occupation and industry indicators, which carry much of education’s effect: read them as a prediction model’s, not as returns to schooling. Grade 10 is exactly zero: the lasso left it out.
The gender gap, after selecting controls¶
For the effect of one variable, a lasso’s coefficient is the wrong tool: the selection biases it, and it has no valid standard error. Post-double-selection runs a lasso of the outcome and a lasso of the variable of interest on the candidate controls, then an ordinary regression on the union of what they kept:
controls = rhs([p for p in WAGE_PREDICTORS if p != "female"])
gap = double_selection_stream("log_wage ~ female", acs, controls=controls, verbose=False)
b, se = gap.coef()["female"], gap.se[gap.coefnames.index("female")]
print(f"gender gap: {b:.4f} log points (se {se:.4f}), "
f"with {len(gap.double_selection.union)} controls selected")
print(gap.double_selection.summary_text())
gender gap: -0.1253 log points (se 0.0064), with 497 controls selected
post-double-selection: 497 of 1971 controls selected (penalty: rigorous)
log_wage: 323 selected (C(age)[T.26], C(age)[T.27], C(age)[T.28], ...)
female: 311 selected (C(age)[T.26], C(age)[T.27], C(age)[T.28], ...)
Women’s hourly wages are about 12 log points lower than men’s with the same selected characteristics, occupation and industry among them. The penalty is the plug-in rule (Belloni, Chen, Chernozhukov and Hansen 2012), whose theory makes the standard error valid, and the standard error is robust to heteroskedasticity. The effect of a variable compares this estimate with double machine learning and the debiased lasso.