A binary outcome

examples/employment.py predicts whether a Californian aged 25 to 64 is employed, with a lasso logit. The predictors leave out the job’s characteristics (occupation, industry, hours), which describe whether someone works, and the four widest factors (birthplace, language, ancestry, field of degree), to keep the example quick: 28 factors, 153 indicators.

factors = [p for p in PREDICTORS
           if p not in ("birthplace", "language", "ancestry", "degree_field")]
fml = f"employed ~ {rhs(factors)}"
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)

Cross-validated on the deviance

fit = lasso_logit_stream(fml, train, n_lambdas=30, verbose=False)
print(f"{fit.n_obs:,} people, {len(fit.coefnames)} indicators; "
      f"{len(fit.selected())} selected at lambda_min, "
      f"{len(fit.selected('lambda_1se'))} at lambda_1se")
print(f"passes over the data: {fit.diagnostics['passes']}")
162,870 people, 153 indicators; 151 selected at lambda_min, 126 at lambda_1se
solver: in_memory

The penalty minimizes the held-out deviance over 5 folds. A logit’s loss is not quadratic, so unlike the lasso it cannot be solved from one set of cross-products. On a sample this size the fit holds the rows in memory and runs coordinate descent over them (solver="auto" chose "in_memory"). On large data each Newton step reads the data again, a few times per penalty, with every fold’s model moving along the path in the same reads: plan for that cost (How it works). 30 penalties instead of the default 100 keep the example fast.

The coefficients are log odds relative to each factor’s reference level:

┌────────────────────────────┬───────────┐
│ term                       ┆ log odds  │
╞════════════════════════════╪═══════════╡
│ C(enrolled)[T.2]           ┆ -0.34882  │
│ C(enrolled)[T.3]           ┆ -0.474194 │
│ C(cognitive)[T.2]          ┆ 0.706196  │
│ C(ambulatory)[T.2]         ┆ 0.609747  │
│ C(insurance_medicaid)[T.1] ┆ -0.461971 │
└────────────────────────────┴───────────┘

In the Census’s coding the disability items are 1 for having the difficulty and 2 for not, so people without a cognitive or an ambulatory difficulty have about twice the odds of being employed. Being enrolled in a public (2) or private (3) school, and having Medicaid, lower the odds.

Probabilities for new people

predict() gives the log odds (xb) for any data, lazily:

pred = fit.predict(test).with_columns(p=1 / (1 + (-pl.col("xb")).exp()))
pred.select(mean_p=pl.col("p").mean(), employed=pl.col("employed").mean(),
            brier=((pl.col("p") - pl.col("employed")) ** 2).mean()).collect()
┌──────────┬──────────┬──────────┐
│ mean_p   ┆ employed ┆ brier    │
╞══════════╪══════════╪══════════╡
│ 0.740563 ┆ 0.743676 ┆ 0.134613 │
└──────────┴──────────┴──────────┘

By decile of the predicted probability, in the held-out 20%, the predictions are close to the shares employed:

┌────────┬───────────┬──────────┐
│ decile ┆ predicted ┆ observed │
╞════════╪═══════════╪══════════╡
│ 1.0    ┆ 0.162654  ┆ 0.189143 │
│ 2.0    ┆ 0.495605  ┆ 0.508841 │
│ 3.0    ┆ 0.644629  ┆ 0.635806 │
│ 4.0    ┆ 0.742492  ┆ 0.729126 │
│ 5.0    ┆ 0.807608  ┆ 0.788065 │
│ 6.0    ┆ 0.852031  ┆ 0.839106 │
│ 7.0    ┆ 0.88625   ┆ 0.891945 │
│ 8.0    ┆ 0.913568  ┆ 0.932466 │
│ 9.0    ┆ 0.937265  ┆ 0.947692 │
│ 10.0   ┆ 0.963408  ┆ 0.97446  │
└────────┴───────────┴──────────┘

No decile’s prediction is more than 2.6 points from its share employed (the lowest decile’s is the largest gap), and the mean prediction is within 0.3 points of the share employed overall.

A fixed effect

The penalized logit takes one absorbed fixed effect, never penalized. With the state’s, and the penalty by the BIC (no folds, so one path):

fe = lasso_logit_stream(f"{fml} | state", train, penalty="bic", verbose=False)
with state fixed effects (BIC): 144 selected