Metadata-Version: 2.4
Name: penalized-stream
Version: 0.1.0
Summary: Lasso, ridge and elastic net with absorbed fixed effects on data larger than memory, with cross-validation from one pass and post-double-selection inference
Author: Lee Tucker
License-Expression: MIT
Project-URL: Homepage, https://github.com/leetucker/penalized-stream
Project-URL: Source, https://github.com/leetucker/penalized-stream
Project-URL: Issues, https://github.com/leetucker/penalized-stream/issues
Project-URL: Documentation, https://leetucker.github.io/penalized-stream/
Project-URL: Changelog, https://github.com/leetucker/penalized-stream/blob/main/CHANGELOG.md
Keywords: econometrics,lasso,ridge,elastic net,post-double-selection,high-dimensional fixed effects,cross-validation,out-of-core
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: hdfe-stream[formula]>=0.13.4
Requires-Dist: stream-limits>=0.3.0
Requires-Dist: polars!=1.41.*,>=1.37
Requires-Dist: numpy>=2.0
Requires-Dist: scipy>=1.13
Requires-Dist: numba>=0.60
Requires-Dist: pyarrow>=16.0
Requires-Dist: great-tables>=1.0
Provides-Extra: benchmark
Requires-Dist: stream-limits[launcher]>=0.3.0; extra == "benchmark"
Requires-Dist: matplotlib>=3.7; extra == "benchmark"
Requires-Dist: psutil>=5.9; extra == "benchmark"
Requires-Dist: scikit-learn>=1.5; extra == "benchmark"
Requires-Dist: glum>=3.0; extra == "benchmark"
Provides-Extra: docs
Requires-Dist: sphinx>=8.0; extra == "docs"
Requires-Dist: myst-parser>=4.0; extra == "docs"
Requires-Dist: furo>=2024.8.6; extra == "docs"
Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
Requires-Dist: sphinx-design>=0.6; extra == "docs"
Provides-Extra: logit
Requires-Dist: logit-stream>=0.8.0; extra == "logit"
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == "plot"
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: scikit-learn>=1.5; extra == "test"
Requires-Dist: matplotlib>=3.7; extra == "test"
Requires-Dist: logit-stream>=0.8.0; extra == "test"
Dynamic: license-file

# penalized-stream

Lasso, ridge and elastic net for data that do not fit in memory, with any
number of absorbed fixed effects, cross-validated from one pass over the data,
and inference after selection: post-double-selection (with instruments, too),
double machine learning, the debiased lasso and stability selection
(`lasso_stream`, `ridge_stream`, `elastic_net_stream`, `double_selection_stream`,
`double_selection_iv_stream`, `double_ml_stream`, `debiased_lasso_stream`,
`stability_selection_stream`); the penalized logit, probit and Poisson
model, with post-double-selection for a binary outcome (`lasso_logit_stream`,
`elastic_net_logit_stream`, `lasso_probit_stream`, `lasso_poisson_stream`, ...,
`double_selection_logit_stream`); and the penalized multinomial logit and
ordered logit and probit (`lasso_mlogit_stream`,
`lasso_ologit_stream`, `lasso_oprobit_stream`, ...).

```python
from penalized_stream import lasso_stream, double_selection_stream

fit = lasso_stream(
    "log_earn ~ age + tenure + i(occupation) + i(industry) | worker_id + year",
    "data/*.parquet",              # a Parquet path or glob, never fully loaded
    workdir="scratch",             # where intermediates go: disk, not memory
)
fit.summary()                      # the selected covariates at lambda_min
fit.plot_cv()

effect = double_selection_stream(
    "log_earn ~ union | worker_id + year",
    "data/*.parquet",
    controls="age + tenure + i(occupation) + i(industry) + i(state)",
    vcov={"CRV1": "worker_id"},
)
effect.summary()                   # the union effect, with clustered standard errors
```

The documentation, with worked examples on the American Community Survey
and a guide to choosing a method, is at
<https://leetucker.github.io/penalized-stream/>.

Formulas follow [pyfixest](https://github.com/py-econometrics/pyfixest)
syntax and are compiled by [hdfe-stream](https://github.com/leetucker/hdfe-stream),
so coefficient names and coding match pyfixest's. The fixed effects after `|`
are partialled out as hdfe-stream's regressions partial them out, and are never
penalized.

## Features

- **The lasso, ridge and elastic net**, with covariates standardized, analytic
  or frequency weights, and covariates left unpenalized (`unpenalized=`).
- **The group lasso** (`groups="factors"`, or groups you name): each factor's
  indicators enter or leave together, so a factor's selection does not depend
  on its reference level. grpreg's group lasso and group elastic net.
- **The penalty**: by K-fold cross-validation (lambda_min or lambda_1se), an
  information criterion (AIC, BIC, extended BIC, AICc), Belloni, Chen,
  Chernozhukov and Hansen's plug-in ("rigorous") penalty with heteroskedastic
  or cluster-robust loadings, or a given value.
- **Cross-validation from one pass.** The pass keeps each fold's
  cross-products apart, so the whole path and every fold's held-out error
  come from K small matrices. Folds are made of rows, or of a column's groups;
  by default, of the groups of the largest fixed effect.
- **Fixed effects in the cross-validation**: partialled out once from all the
  rows (the default), or estimated again on each fold's training rows
  (`cv_fixed_effects="refit"`, exact). With one fixed effect and folds of its
  groups the default is already exact. On simulated panels the two choose the
  same penalty or a neighboring one, with the same prediction error; the
  default's cross-validated error is a less reliable estimate of out-of-sample
  error when cells are small. See
  [docs/fixed_effects_cv.md](docs/fixed_effects_cv.md).
- **Post-double-selection** (Belloni, Chernozhukov and Hansen 2014): the
  effect of one or more treatments controlling for the controls a lasso
  selects for the outcome and for each treatment, with always-included
  controls, and robust or clustered standard errors. With `groups=`, each
  factor among the controls is selected or left out as a block. The result is
  an hdfe-stream regression, so it reports and exports (`etable`) like one; so
  do the double machine learning and debiased lasso results.
- **Post-double-selection with instruments** (`double_selection_iv_stream`;
  Chernozhukov, Hansen and Spindler 2015): one endogenous treatment
  (`"y ~ 1 + [d ~ z1 + z2] | fe"`), with the controls selected for the
  outcome, the treatment and each instrument, then 2SLS on their union, with
  hdfe-stream's first stage and robust or clustered standard errors. With many
  instruments, `select_instruments=True` selects them by a lasso of the
  treatment on the instruments and the controls. The selections are those of
  hdm's `rlassoIVselectX` and `rlassoIV`, and `method="partialling_out"` gives
  hdm's estimate (2SLS on each variable's residual from its own selected
  controls) in place of 2SLS on the union.
- **Double machine learning** for the partially linear model (Chernozhukov et
  al. 2018): one or more treatments, lasso or elastic-net nuisances cross-fitted
  from the folds' cross-products (cross-validated within each fold's training
  rows, or the plug-in penalty), repeated cross-fitting, and robust or clustered
  standard errors. DoubleML's estimates and standard errors.
- **The debiased lasso** (van de Geer, Buhlmann, Ritov and Dezeure 2014):
  confidence intervals for any or all of a lasso's coefficients, with iid,
  robust or clustered standard errors; hdi's `lasso.proj` formulas.
- **Stability selection** with complementary pairs (Meinshausen and Buhlmann
  2010; Shah and Samworth 2013): each covariate's (or group's) selection
  probability over 100 half-samples, the stable set and the bound on false
  selections, as R's stabs computes them, from one pass.
- **The penalized logit, probit and Poisson model** (`lasso_logit_stream`,
  `elastic_net_logit_stream`, `lasso_probit_stream`, `elastic_net_probit_stream`,
  `lasso_poisson_stream`, `elastic_net_poisson_stream`): with no absorbed fixed
  effect or one, cross-validated on the held-out deviance, by an information
  criterion, or (the logit) with the plug-in penalty of Belloni, Chernozhukov
  and Wei (hdm's `rlassologit`). Each Newton step is one read of the data,
  shared by every cross-validation model, from each row's nonzeros when the
  design is indicators: a path of 100 penalties reads the data about 300 times
  (from hdfe-stream's compact copy of it, not the source). When the rows fit in
  memory, `solver="in_memory"` fits by coordinate descent on them instead;
  `solver="auto"` chooses it up to 200,000 rows or for a wide design. glmnet's
  coefficients and cross-validation curves (the logit and Poisson; glmnet has
  no probit).
- **The penalized multinomial logit and ordered logit and probit**
  (`lasso_mlogit_stream`, `elastic_net_mlogit_stream`,
  `lasso_ologit_stream`, `elastic_net_ologit_stream`,
  `lasso_oprobit_stream`, `elastic_net_oprobit_stream`): with no
  absorbed fixed effect or one, weights and unpenalized covariates, the penalty
  chosen by cross-validation on the held-out deviance, an information
  criterion, or given. The multinomial logit has a coefficient for every
  outcome level and covariate, identified by the penalty, so the fit does not
  depend on a base level: glmnet's `family = "multinomial"`, with its
  ungrouped penalty or, with `grouped=True`, its grouped one (a covariate in
  or out for every level at once). The ordered model is ordinalNet's parallel cumulative logit or
  probit, with unpenalized cutpoints. Each Newton step is one read of
  logit-stream's stored rows, shared by every cross-validation model; the
  multinomial logit can instead fit on the rows in memory
  (`solver="in_memory"`, which `solver="auto"` chooses for smaller data).
  They need logit-stream (`pip install penalized-stream[logit]`).
- **Post-double-selection for a binary outcome**
  (`double_selection_logit_stream`; Belloni, Chernozhukov and Wei 2016): a
  lasso logit of the outcome, a lasso of each treatment weighted by the
  logit's variance, and a final logit (hdfe-stream's `feglm_stream`) with
  robust or clustered standard errors.
- **Results**: `summary()`, `tidy()`, `coef()`, `selected()`, the whole path
  (`path()`, `cv()`), `plot_path()`, `plot_cv()`, lazy `predict()`, and
  `sample()` (which rows were used, and why the others were not).
- **Tables**: `etable()` puts fits side by side (or one fit at lambda_min and
  lambda_1se), with the selected coefficients, the fixed effects, the penalty
  and how it was chosen, as a Great Tables table, a DataFrame, Markdown, HTML
  or LaTeX. Penalized coefficients have no standard errors, so the table has
  none; `double_selection_stream`'s results go in `hdfe_stream.etable`.

## When to use this, and when not to

**Use it when the data are larger than memory, or when there are fixed effects
with many levels.** The design is never built in memory: memory grows with the
square of the number of covariates (times the number of folds), not with the
number of rows. In-memory libraries hold the whole design, often several
copies of it.

**It is also fast when the data do fit.** The penalty path and the
cross-validation never touch the rows again after the pass: a path of 100
penalties over 5 folds takes a fraction of a second, whatever the number of
rows. The penalized logit, probit, Poisson and multinomial logit have a
second solver that works on the rows in memory, which `solver="auto"` uses
on smaller or wide designs. On the
[benchmarks](https://leetucker.github.io/penalized-stream/benchmarks/index.html),
five models fitted to the American Community Survey from 10,000 rows to
8 million, penalized-stream was the fastest library on every model from about
100,000 rows up: 33 times faster than glmnet on the cross-validated lasso at
3 million rows, 7 times on the lasso logit at 8 million (in 3.2 GB against
36 GB), and 110 to 400 times faster than ordinalNet on the ordered logit.

**Use something else for:**

- **More covariates than rows**, or, for least squares and for a logit,
  probit or Poisson whose rows do not fit in memory, more than about 20,000
  covariates: the cross-products grow with the square of the width, and a
  solver that works on the rows (glmnet, scikit-learn, skglm) is the right
  tool.
- **Small data, when seconds matter**: at 10,000 rows glmnet is as fast or a
  little faster, and uses less memory.
- **A penalized logit, probit, Poisson, multinomial or ordered regression
  with several fixed effects**: not yet available (they take no fixed effect
  or one); use glmnet, glum or scikit-learn.
- **ordinalNet's semi-parallel and nonparallel ordered models**: not
  available.
- **Machine learning beyond linear models** (forests, boosting, neural nets).

## Conventions

The penalty is on the scale of scikit-learn's `Lasso` and `ElasticNet`:

    1/(2W) sum_i w_i (y_i - b0 - x_i'b)^2 + penalty * sum_j (l1_ratio |b_j| + (1 - l1_ratio)/2 b_j^2)

over standardized covariates, W the sum of the weights. For the lasso this is
also glmnet's lambda. [docs/conventions.md](docs/conventions.md) converts
between this package's penalty and glmnet's, scikit-learn's, hdm's and
lassopack's.

## Install

```bash
pip install penalized-stream
```

Python 3.10 or later. It installs hdfe-stream (0.13.4 or later), Polars,
NumPy, SciPy and numba. Plots need matplotlib (`pip install penalized-stream[plot]`),
and the multinomial and ordered models logit-stream, 0.8.0 or later
(`pip install penalized-stream[logit]`).

## Testing

The tests compare with glmnet (lasso paths and cross-validation curves with
weights, penalty factors and fixed effects; the binomial lasso and elastic
net, with a fixed effect as dummies; the multinomial lasso and elastic net,
with weights and a fixed effect as dummies), ordinalNet (the ordered logit
and probit, with weights and a fixed effect as dummies), scikit-learn (the elastic net and
ridge), grpreg (the group lasso), hdm (`rlasso`, `rlassoEffect`, `rlassologit`, and
its pieces for the logit's double selection), DoubleML
(the partially linear model), hdi (`lasso.proj`), stabs (`stabsel`) and direct
computations (the information criteria, the exact cross-validation with
several fixed effects).
The R comparisons need an R environment with glmnet, hdm and the other
packages named here; see
`tests/conftest.py`.
