"""Double/debiased machine learning for the partially linear model
(Chernozhukov, Chetverikov, Demirer, Duflo, Hansen, Newey and Robins 2018),
with lasso or elastic-net nuisances, cross-fitted.
y = d theta + g(X) + fixed effects + e, d = m(X) + fixed effects + v
For each fold k, lassos fitted on the other folds give l(X) = E[y | X] and
m(X) = E[d | X]; on fold k's rows the residuals are y~ = y - l(X) and
d~ = d - m(X). Then theta = sum d~ y~ / sum d~^2 over all the folds (DoubleML's
"dml2", with the partialling-out score), and its variance is that of the score
psi = (y~ - theta d~) d~:
var(theta) = mean(psi^2) / mean(d~^2)^2 / n (robust)
clustered: sum over clusters of (sum psi)^2 instead of n mean(psi^2), times G/(G-1)
With several treatments, each is estimated as DoubleML estimates it: its
nuisances condition on the controls and the other treatments.
Everything but the variance comes from the folds' cross-products: each fold's
lassos are fitted on the other folds' (cross-validated, by default, over those
folds), and sum d~ y~ over a fold is a bilinear form in its own. The variance
takes one pass over the saved rows; each repetition of the cross-fitting
(n_repeats) another pass, its results combined as DoubleML combines them (the
median estimate, and the median of var_r + (theta_r - theta)^2).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import numpy as np
from hdfe_stream.core.results_base import RegressionResult, vcov_key
from . import _design
from ._folds import FOLD
from ._nuisance import fit_nuisance
from ._scores import ScoreMeat, iter_rows
from ._solver import augmented
from ._subset import sub_design
[docs]
@dataclass(kw_only=True)
class DoubleMLResult(RegressionResult):
"""The treatments' effects, their standard errors, intervals and tests
(`summary`, `tidy`, `confint`, `wald_test`; `etable` through
hdfe_stream.etable).
Beyond `RegressionResult`'s attributes:
Attributes
----------
controls : list of str
n_folds, n_repeats : int
penalty : str or float
How the nuisance lassos' penalties were chosen.
theta_repeats : numpy.ndarray
(n_repeats, treatments): each repetition's estimates.
nuisance : list of dict
For each repetition, fold and treatment: the outcome's and the
treatment's lasso penalties and number of controls selected.
fe_names : list of str
"""
controls: list = field(default_factory=list)
n_folds: int = 5
n_repeats: int = 1
penalty: Any = None
theta_repeats: Any = None
nuisance: list = field(default_factory=list)
fe_names: list = field(default_factory=list)
_normal_inference = True
def _summary_lines(self):
sel = [n["l_selected"] for n in self.nuisance] + [n["m_selected"] for n in
self.nuisance]
lines = [f"double machine learning (partially linear, lasso nuisances, penalty "
f"{self.penalty}); {self.n_folds} folds x {self.n_repeats} repetition"
f"{'s' * (self.n_repeats != 1)}; controls selected per nuisance: "
f"{min(sel)} to {max(sel)} of {len(self.controls)}"]
if self.fe_names:
lines.append("fixed effects: " + " + ".join(self.fe_names))
return lines + super()._summary_lines()
def _summary_fields(self):
return {**super()._summary_fields(), "estimator": "double machine learning (PLR)",
"n_folds": self.n_folds, "n_repeats": self.n_repeats,
"penalty": self.penalty, "fixed_effects": list(self.fe_names)}
def _pyfixest_attrs(self):
out = super()._pyfixest_attrs()
if self.fe_names:
out.update(_fixef="+".join(self.fe_names), _has_fixef=True)
return out
def _cluster_columns(key):
if key in ("iid", "hetero"):
return None
if not key.startswith("CRV1:") or "+" in key:
raise ValueError("double ML's vcov is 'hetero' or one-way {'CRV1': column}")
return [c.strip() for c in key.split(":", 1)[1].split("^")]
def _residual_vector(order, target, nuisance, controls):
"""Coefficients over [1, outcome, covariates...] (the augmented order) of
the target's residual: target - intercept - controls' fit."""
v = np.zeros(len(order) + 1)
pos = {nm: i + 1 for i, nm in enumerate(order)}
v[0] = -nuisance.intercept
v[pos[target]] = 1.0
for c, b in zip(controls, nuisance.beta, strict=True):
v[pos[c]] -= b
return v
def _one_repeat(design, treat, controls, unpen, *, penalty, l1_ratio, standardize, tol,
groups, cluster, loadings_cluster, rigorous_options):
cp = design.cp
K = cp.n_splits
order = [design.depvar, *design.names]
T = len(treat)
# residual vectors per fold and treatment: u (outcome), v (treatment)
U = np.zeros((K, T, len(order) + 1))
Vv = np.zeros((K, T, len(order) + 1))
info = []
num = np.zeros(T)
den = np.zeros(T)
for k in range(K):
train = [s for s in range(K) if s != k]
Mk = augmented(cp.gram[k], cp.sums[k], cp.weight_sums[k])
for t, d in enumerate(treat):
ctrl = [c for c in controls] + [o for o in treat if o != d]
opts = dict(penalty=penalty, l1_ratio=l1_ratio, standardize=standardize, tol=tol,
groups=groups, cluster=loadings_cluster,
rigorous_options=rigorous_options)
nl = fit_nuisance(sub_design(design, design.depvar, ctrl, unpen, splits=train),
**opts)
nm = fit_nuisance(sub_design(design, d, ctrl, unpen, splits=train), **opts)
U[k, t] = _residual_vector(order, design.depvar, nl, ctrl)
Vv[k, t] = _residual_vector(order, d, nm, ctrl)
num[t] += U[k, t] @ Mk @ Vv[k, t]
den[t] += Vv[k, t] @ Mk @ Vv[k, t]
info.append({"fold": k, "treatment": d, "l_penalty": nl.penalty,
"l_selected": len(nl.selected), "m_penalty": nm.penalty,
"m_selected": len(nm.selected)})
theta = num / den
# the scores' variance: one pass over the saved rows
weight = cp.weight_column
cols = [*order, FOLD] + ([weight] if weight else []) + (cluster or [])
acc = ScoreMeat(T, cluster)
W = float(cp.weight_sums.sum())
# every fold's residual vectors at once, (1 + k, 2 K T): each row then
# takes its own fold's
UV = np.concatenate([U.reshape(K * T, -1), Vv.reshape(K * T, -1)]).T
for b in iter_rows(cp, cols):
n = len(b[FOLD])
A = np.empty((n, len(order) + 1), order="F") # [1, y, x...]
A[:, 0] = 1.0
for j, c in enumerate(order):
A[:, j + 1] = b[c]
w = b[weight] if weight else np.ones(n)
R = (A @ UV).reshape(n, 2, K, T)
fold = np.asarray(b[FOLD], dtype=np.int64)
yt = R[np.arange(n), 0, fold] # (n, T)
dt = R[np.arange(n), 1, fold]
scores = w[:, None] * (yt - theta * dt) * dt
acc.add(scores, {c: b[c] for c in cluster} if cluster else None)
J = den / W # mean(d~^2), weighted
meat = acc.meat()
if cluster:
G = acc.n_clusters
meat = meat * G / max(G - 1, 1)
V = meat / W ** 2 / np.outer(J, J)
return theta, V, info, acc.n_clusters
[docs]
def double_ml_stream(fml: str, data: Any, *, controls: str, unpenalized=None,
penalty="cv", l1_ratio: float = 1.0, groups=None, vcov="hetero",
n_folds: int = 5, n_repeats: int = 1, fold_by: str | None = None,
seed: int = 0, weights=None, weights_type: str = "aweights",
standardize: bool = True, tol: float = 1e-7,
cluster: str | None = None, rigorous_options: dict | None = None,
**options) -> DoubleMLResult:
"""Double/debiased machine learning for the partially linear model, with
lasso (or elastic-net) nuisances.
Parameters
----------
fml : str
``"y ~ d | fe1 + fe2"``: the outcome, the treatment(s) and the fixed
effects (partialled out of everything).
data : str, Path, polars.LazyFrame or polars.DataFrame
controls : str
The controls X, a right-hand side (``"x1 + x2 + i(region)"``).
unpenalized : str or list of str, optional
Controls left unpenalized in every nuisance lasso.
penalty : default "cv"
The nuisance lassos' penalty, chosen for each fold on that fold's
training rows: ``"cv"`` (cross-validated over the other folds),
``"cv_1se"``, a criterion, ``"rigorous"`` (the plug-in penalty) or a
value.
l1_ratio : float, default 1
1 for lasso nuisances; below 1, elastic-net ones.
groups : optional
As for `lasso_stream` (not with ``penalty="rigorous"``).
vcov : default "hetero"
``"hetero"`` or ``{"CRV1": "cluster"}`` (one-way; the folds are then
made of whole clusters unless `fold_by` says otherwise).
n_folds : int, default 5
Folds of the cross-fitting.
n_repeats : int, default 1
Repetitions of the cross-fitting with new folds, combined by medians
(one more pass over the data each).
fold_by, seed, weights, weights_type, standardize, tol, rigorous_options
As for `lasso_stream`.
cluster : str, optional
With ``penalty="rigorous"``: cluster the loadings by this column;
default the vcov's cluster.
**options
hdfe-stream's options.
Returns
-------
DoubleMLResult
"""
if not isinstance(controls, str) or not controls.strip():
raise ValueError("controls must be a right-hand side, e.g. 'x1 + x2 + i(region)'")
if not isinstance(n_repeats, int) or n_repeats < 1:
raise ValueError("n_repeats must be a positive integer")
if not isinstance(n_folds, int) or n_folds < 2:
raise ValueError("n_folds must be at least 2")
key = vcov_key(vcov)
if key == "iid":
key = "hetero"
vcl = _cluster_columns(key)
loadings_cluster = ([c.strip() for c in cluster.split("^")] if cluster else vcl) \
if penalty == "rigorous" else None
lf = _design.as_lazy(data)
spec, yname, treat, _, fe, _ = _design.parse_model(fml, None, lf)
cfml = f"{spec.dep} ~ {controls}" + (f" | {spec.fe}" if spec.fe else "")
_, _, cnames, unpen, _, _ = _design.parse_model(cfml, unpenalized, lf)
clash = [c for c in cnames if c in treat]
if clash:
raise ValueError(f"{clash} are both treatments and controls")
full_rhs = " + ".join([spec.rhs, controls]
+ ([unpenalized] if isinstance(unpenalized, str) else []))
big = f"{spec.dep} ~ {full_rhs}" + (f" | {spec.fe}" if spec.fe else "")
if fold_by is None and vcl is not None:
fold_by = "^".join(vcl)
carry = list(dict.fromkeys((vcl or []) + (loadings_cluster or [])))
thetas, Vs, infos, G = [], [], [], None
design = None
for r in range(n_repeats):
design = _design.build(big, data, weights=weights, weights_type=weights_type,
n_folds=n_folds, fold_by=fold_by, seed=seed + r,
save_rows=True, carry=carry, options=options)
theta, V, info, G = _one_repeat(
design, treat, cnames, unpen, penalty=penalty, l1_ratio=l1_ratio,
standardize=standardize, tol=tol, groups=groups, cluster=vcl,
loadings_cluster=loadings_cluster, rigorous_options=rigorous_options)
for i in info:
i["repeat"] = r
thetas.append(theta)
Vs.append(V)
infos += info
design.cp.cleanup()
thetas = np.array(thetas)
theta = np.median(thetas, axis=0)
if n_repeats == 1:
V = Vs[0]
else:
# DoubleML: the median of each repetition's variance plus its squared
# deviation from the median estimate (elementwise, by treatment)
dev = [Vr + np.outer(tr - theta, tr - theta) for Vr, tr in zip(Vs, thetas,
strict=True)]
V = np.median(np.array(dev), axis=0)
cp = design.cp
N = cp.n_obs
return DoubleMLResult(
fml=fml, depvar=yname, coefnames=list(treat), beta=theta, vcov=V, vcov_type=key,
df_t=N - 1, n_obs=N, all_vcovs={key: (V, N - 1)},
n_clusters={key.split(":", 1)[1]: G} if vcl else {}, weights=weights,
weights_type=weights_type, controls=list(cnames), n_folds=n_folds,
n_repeats=n_repeats, penalty=penalty, theta_repeats=thetas, nuisance=infos,
fe_names=list(fe), diagnostics={"fold_by": design.fold_by})