A count or other nonnegative outcome¶
examples/commute.py
predicts how many minutes a Californian aged 25 to 64 takes to get to work,
with a lasso Poisson regression. The rows are the workers who travel to
work: those who work from home, or have no job, have no commute. The
predictors are the employment example’s 28 factors and three of the job’s:
the class of worker, usual hours, and how the worker gets there. The
occupation and industry, about 800 indicators between them, are left out to
keep the example quick. That makes 265 indicators.
commuters = pl.scan_parquet(acs).filter(pl.col("commute_minutes") > 0)
factors = [p for p in PREDICTORS
if p not in ("birthplace", "language", "ancestry", "degree_field")]
factors += ["worker_class", "hours", "commute_mode"]
fml = f"commute_minutes ~ {rhs(factors)}"
train = commuters.filter(pl.int_range(pl.len()) % 5 != 0)
test = commuters.filter(pl.int_range(pl.len()) % 5 == 0)
Commute time is not a count of events, but the Poisson model suits any nonnegative outcome whose mean is the exponential of a linear predictor. The coefficients are consistent for that mean however the outcome is distributed around it. Economists call this Poisson pseudo-maximum likelihood. Commute times vary far more than a Poisson count would: the variance is about 20 times the mean. That does not bias the coefficients, and the held-out deviance remains a fair measure of fit for choosing the penalty.
Cross-validated on the deviance¶
fit = lasso_poisson_stream(fml, train, n_lambdas=30, verbose=False)
98,649 commuters, 265 indicators; 152 selected at lambda_min, 74 at lambda_1se
solver: in_memory
The penalty minimizes the held-out Poisson deviance over 5 folds. On a
sample this size the fit holds the rows in memory and runs coordinate
descent over them (solver="auto" chose "in_memory"); on a larger one it
streams the rows, one read per Newton step, with every fold’s model moving
along the path in the same reads
(How it works).
The coefficients are log rate ratios. exp() of one is the ratio of the
expected commute to the reference level’s, all else equal. For the way to
work, the reference is a car, truck or van:
coef = fit.coef()
math.exp(coef["C(commute_mode)[T.4]"]) # commuter rail
┌─────────────────────────┬────────────┐
│ mode ┆ rate ratio │
╞═════════════════════════╪════════════╡
│ bus ┆ 1.602494 │
│ subway or elevated rail ┆ 1.617807 │
│ commuter rail ┆ 2.432462 │
│ bicycle ┆ 0.765206 │
│ walked ┆ 0.494724 │
└─────────────────────────┴────────────┘
A bus or subway commute is expected to take about 60% longer than the same worker’s drive, and commuter rail about 2.4 times as long. Those who walk or cycle live closer: their commutes are half and three-quarters as long.
Predicted minutes for new workers¶
predict() gives the linear predictor (xb) for any data, lazily. Its
exponential is the expected commute:
pred = fit.predict(test).with_columns(mu=pl.col("xb").exp())
y, mu = pl.col("commute_minutes"), pl.col("mu")
deviance = 2 * (y * (y / mu).log() - (y - mu))
pred.select(predicted=mu.mean(), observed=y.mean(),
mean_abs_error=(y - mu).abs().mean(), deviance=deviance.mean()).collect()
┌───────────┬──────────┬────────────────┬───────────┐
│ predicted ┆ observed ┆ mean_abs_error ┆ deviance │
╞═══════════╪══════════╪════════════════╪═══════════╡
│ 30.079831 ┆ 30.06528 ┆ 16.183204 ┆ 14.633481 │
└───────────┴──────────┴────────────────┴───────────┘
By decile of the prediction, in the held-out 20%:
┌────────┬───────────┬───────────┐
│ decile ┆ predicted ┆ observed │
╞════════╪═══════════╪═══════════╡
│ 1.0 ┆ 21.948634 ┆ 20.98459 │
│ 2.0 ┆ 26.297875 ┆ 25.29927 │
│ 3.0 ┆ 27.484231 ┆ 27.879157 │
│ 4.0 ┆ 28.379614 ┆ 27.862125 │
│ 5.0 ┆ 29.226355 ┆ 29.734603 │
│ 6.0 ┆ 30.159047 ┆ 30.807708 │
│ 7.0 ┆ 31.166951 ┆ 30.442323 │
│ 8.0 ┆ 32.116758 ┆ 32.534105 │
│ 9.0 ┆ 33.294365 ┆ 33.09043 │
│ 10.0 ┆ 40.738542 ┆ 42.053912 │
└────────┴───────────┴───────────┘
The mean prediction is within a tenth of a minute of the mean commute, and no decile’s prediction is more than about a minute and a half off its observed mean. The spread is narrow, though. Most of the variation in commute times comes from where people live and work, which these characteristics barely capture.
A fixed effect¶
Where someone lives matters most for their commute, so the next model absorbs the PUMA (an area of at least 100,000 people) as a fixed effect, never penalized, cross-validated as before:
fe = lasso_poisson_stream(f"{fml} | puma_id", train, n_lambdas=30, verbose=False)
with PUMA fixed effects: 143 selected; held-out deviance 14.032 (without: 14.633)
The 281 PUMAs lower the held-out deviance by 4%. The penalized Poisson model takes one absorbed fixed effect.