Prediction¶
examples/prediction.py
compares ways of predicting log hourly wages from the same 2,000 or so
indicators as the quickstart: three penalties, three ways
of choosing the penalty, the group lasso and fixed effects, each judged on
people the fits never saw.
A held-out sample¶
The fits use 80% of the rows; the other 20% are held out. Both are lazy queries on the Parquet file, so neither is read into memory:
acs = load_acs()
train = pl.scan_parquet(acs).filter(pl.int_range(pl.len()) % 5 != 0)
test = pl.scan_parquet(acs).filter(pl.int_range(pl.len()) % 5 == 0)
fml = f"log_wage ~ {rhs(WAGE_PREDICTORS)}"
The lasso, ridge and elastic net¶
The three fits use the same folds (the same seed), so their
cross-validated errors are comparable:
fits = {"lasso": lasso_stream(fml, train, verbose=False),
"elastic net (0.5)": elastic_net_stream(fml, train, l1_ratio=0.5, verbose=False),
"ridge": ridge_stream(fml, train, verbose=False)}
print(pl.DataFrame({"method": list(fits),
"cv error": [f.cv_mean.min() for f in fits.values()],
"selected": [len(f.selected()) for f in fits.values()]}))
┌───────────────────┬──────────┬──────────┐
│ method ┆ cv error ┆ selected │
╞═══════════════════╪══════════╪══════════╡
│ lasso ┆ 0.36831 ┆ 1388 │
│ elastic net (0.5) ┆ 0.368311 ┆ 1389 │
│ ridge ┆ 0.369741 ┆ 1956 │
└───────────────────┴──────────┴──────────┘
predict() adds the prediction (xb) to any data, lazily, so the held-out
error is one more query:
def held_out(fit, which=None):
pred = fit.predict(test.filter(pl.col("log_wage").is_not_null()), which=which)
return pred.select(((pl.col("xb") - pl.col("log_wage")) ** 2).mean()).collect().item()
lasso held-out mean squared error 0.3633
elastic net (0.5) held-out mean squared error 0.3633
ridge held-out mean squared error 0.3641
The three predict about equally well. That is typical when there are many more rows than predictors: the penalty matters little, and the lasso’s advantage is that it says which predictors it used. The cross-validated errors ranked the three as the held-out errors do.
Choosing the penalty¶
lambda_1se (the largest penalty within one standard error of the smallest
cross-validated error) and the BIC choose larger penalties than lambda_min,
so fewer predictors:
lasso = fits["lasso"]
bic = lasso_stream(fml, train, penalty="bic", verbose=False)
lambda_min: 1388 selected, held-out 0.3633
lambda_1se: 852 selected, held-out 0.3669
BIC: 528 selected, held-out 0.3737
lambda_1se keeps 40% fewer predictors for 1% more error; the BIC keeps
60% fewer for 3% more. Which is better depends on whether a shorter list is
worth the error. lambda_1se comes from the same fit as lambda_min
(which="lambda_1se" in selected(), coef() and predict()); the BIC
needs no folds.
The group lasso¶
The plain lasso selects indicators: some occupations and not others. To ask which characteristics matter, select each factor as a whole:
grouped = lasso_stream(fml, train, groups="factors", penalty="cv_1se", verbose=False)
group lasso at lambda_1se: 34 of 39 factors kept; dropped: C(independent_living),
C(insurance_ihs), C(military), C(nativity), C(self_care)
The five dropped are rare or overlap with factors that stayed (nativity with citizenship and birthplace; the two disability items with the others).
Fixed effects¶
The 2,462 PUMAs (areas of about 100,000 people) can be absorbed as a fixed
effect, which is never penalized and costs no columns. With folds of PUMAs
(fold_by=), the held-out error is that of people in areas the fit did not
see:
fe = lasso_stream(f"{fml} | puma_id", train, fold_by="puma_id", verbose=False)
with PUMA fixed effects: cv error 0.3632, 1347 selected
A table¶
etable puts fits side by side. Penalized coefficients have no standard
errors, so the table has none; a blank is a coefficient the lasso left out.
keep= takes regular expressions, as pyfixest’s does:
print(etable([lasso, bic], type="md", keep=[r"C\(education\)\[T\.(16|21|22|24)\]"],
model_heads=["lambda_min", "BIC"]))
lambda_min (1) |
BIC (2) |
|
|---|---|---|
C(education)[T.16] |
-0.014 |
|
C(education)[T.21] |
0.187 |
0.207 |
C(education)[T.22] |
0.312 |
0.344 |
C(education)[T.24] |
0.430 |
0.466 |
Method |
Lasso |
Lasso |
Penalty |
0.001051 |
0.004656 |
Chosen by |
CV, lambda_min |
BIC |
Selected |
1388 of 1962 |
528 of 1962 |
CV mean squared error |
0.3683 |
|
Observations |
119,411 |
119,411 |
The BIC’s fit gives education larger coefficients: with fewer occupation and industry indicators to share it, education carries more of what they would have predicted. (16 is a high school diploma, 21 a bachelor’s, 22 a master’s and 24 a doctorate.)