"""Fixed effects for forests.
The model is additive, ``y = g(x) + alpha_group + e``, and the forest estimates
``g``. Three ways of handling the group effects:
``"backfit"``
Alternate a forest and the group effects. Given the current effects, a
forest is fitted to ``y - alpha`` and its out-of-bag predictions ``g_hat``
are taken; the effects are then re-estimated by regressing ``y - g_hat`` on
the fixed effects (hdfe-stream), and the cycle repeats until the effects stop
changing. Out-of-bag predictions keep the effects from absorbing the
forest's overfit.
``"outcome_within"``
Subtract the group means of the outcome once, then fit the forest to the
result. This is right only if the features are unrelated to the groups.
``"group_means"``
Leave the outcome alone and add each group's mean of each feature as
further features, so the forest can learn the part of the group effect
that those means explain.
"""
from __future__ import annotations
import shutil
import time
import warnings
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import polars as pl
import pyarrow as pa
import pyarrow.parquet as pq
FIXED_EFFECTS = ("backfit", "outcome_within", "group_means")
_SERIES = "__outcome"
_WEIGHTS = "__weights"
[docs]
class FixedEffectsWarning(UserWarning):
"""The fixed-effects handling did not converge, or its assumption looks
violated by the data."""
def fe_columns(terms: list[str]) -> list[str]:
"""The data columns that the fixed-effect terms use."""
cols = []
for t in terms:
if "[" in t or "]" in t:
raise ValueError(f"{t!r}: varying slopes are not available in forests")
for c in t.split("^"):
c = c.strip()
if c not in cols:
cols.append(c)
return cols
def _memmap(path, n):
return np.lib.format.open_memmap(path, mode="w+", dtype=np.float64, shape=(n,))
class GroupEffects:
"""The fitted group effects of an outcome that changes from round to
round, estimated with hdfe-stream on a Parquet file of the fixed-effect
columns written once, in the store's row order."""
def __init__(self, terms, lf_rows, store, workdir, chunk_rows, verbose=False, fixef_rm="none"):
if fixef_rm not in ("none", "singleton"):
raise ValueError(f"fixef_rm must be 'none' or 'singleton', not {fixef_rm!r}")
self.fixef_rm = fixef_rm
self.terms = list(terms)
self.formula = " + ".join(self.terms)
self.store = store
self.n = store.n
self.workdir = Path(workdir)
self.workdir.mkdir(parents=True, exist_ok=True)
self.chunk_rows = chunk_rows
self.verbose = verbose
self.columns = fe_columns(self.terms)
self.path = self.workdir / "fe.parquet"
lf_rows.select("row_id", *self.columns).sink_parquet(self.path)
ids = pl.scan_parquet(self.path).select("row_id").collect(engine="streaming")["row_id"]
if not np.array_equal(ids.to_numpy(), store.row_ids()):
raise RuntimeError("the fixed-effect columns are not in the store's row order")
self.seconds = 0.0
n_dropped = 0 # rows left out of the last fit as singletons
rank = None # parameters of the fixed effects, from the last fit
def standard_error_scale(self, sigma: float, n_eff: float | None = None) -> float | None:
"""The root mean square over rows of the standard errors of the fitted
group effects: ``sigma * sqrt(rank / rows)`` for the residuals' standard
deviation `sigma` and the number of parameters `rank` of the fixed
effects (the average leverage of a row in a regression on them is
rank / rows). With one fixed effect this is ``sigma * sqrt(groups /
rows)``, since each effect is a mean of its group's rows. With weights
`rows` is the effective number, ``(sum w)^2 / sum w^2``, and `sigma`
the weighted root mean square. None when hdfe-stream did not report
the rank."""
if not self.rank:
return None
return sigma * float(np.sqrt(self.rank / (n_eff or self.n)))
def _intercept(self) -> float:
res = self._last_fit.resid()
return float(res.select(pl.col("xb").first()).collect(engine="streaming").item())
def tables(self):
"""The group effects of the last fit: ``({term: table}, intercept)``, a
table with the term's columns and the ``effect`` of each group. The
fitted part of the outcome is the intercept plus the effects of a row's
groups, one per term."""
res = self._last_fit.resid()
tables = {}
for term in self.terms:
key = [c.strip() for c in term.split("^")]
tables[term] = (
res.select(*key, pl.col(f"fe_{term}").alias("effect"))
.unique(subset=key)
.collect(engine="streaming")
)
return tables, self._intercept()
def fitted(self, d_path, out_path) -> None:
"""Write to `out_path` the part of `d` (a float64 file in storage
order) that the fixed effects explain."""
from hdfe_stream import feols_stream
t0 = time.perf_counter()
d = np.load(d_path, mmap_mode="r")
weighted = self.store.weighted
sample_weights = self.store.weights() if weighted else None
src = self.workdir / "round.parquet"
schema = None
pf = pq.ParquetFile(self.path)
a = 0
writer = None
try:
for batch in pf.iter_batches(batch_size=self.chunk_rows, columns=self.columns):
k = batch.num_rows
table = pa.Table.from_batches([batch]).append_column(
_SERIES, pa.array(np.asarray(d[a : a + k]))
)
if weighted:
table = table.append_column(_WEIGHTS, pa.array(sample_weights[a : a + k]))
if writer is None:
schema = table.schema
writer = pq.ParquetWriter(src, schema)
writer.write_table(table)
a += k
finally:
if writer is not None:
writer.close()
with warnings.catch_warnings():
# the count of dropped rows is reported in `fit.backfit`
warnings.filterwarnings("ignore", message=".*singleton observations dropped.*")
fit = feols_stream(
f"{_SERIES} ~ 1 | {self.formula}",
src,
workdir=self.workdir / "hdfe",
fixef_rm=self.fixef_rm,
**({"weights": _WEIGHTS} if weighted else {}),
**({} if self.verbose else {"verbose": False}),
)
self.rank = getattr(fit, "k_fe", None)
self._last_fit = fit # kept, for `tables`
out = _memmap(out_path, self.n)
out[:] = np.nan
for res in fit.resid().collect_batches(chunk_size=self.chunk_rows):
ids = res["row_id"].to_numpy()
out[ids] = d[ids] - res["resid"].to_numpy()
missing = np.isnan(out)
self.n_dropped = int(missing.sum())
if self.n_dropped:
if self.fixef_rm == "none":
raise RuntimeError(f"{self.n_dropped} rows have no fixed-effect estimate")
# left out as singletons: no group effect beyond the constant
out[missing] = self._intercept()
out.flush()
del out
self.seconds += time.perf_counter() - t0
@dataclass
class BackfitResult:
"""What a backfit left behind: files (float64, storage order) and how it
went."""
effects: Path # the group effects' fitted values, row by row
y0: Path # the column that was fitted, before the effects
fitted: Path | None # the last round's out-of-bag predictions of g
iterations: int
converged: bool
stopped: str = "tolerance" # "tolerance", "noise_floor", "max_iterations" or "single_round"
changes: list = field(default_factory=list) # per round, in units of `scale`
changes_abs: list = field(default_factory=list) # per round, root mean square
scale: float | None = None # the unit of `changes`
scale_kind: str = "" # "standard_error" or "seed_noise"
noise: float | None = None # root mean square change from reseeding alone
sigma: float | None = None # residual standard deviation after the last round
seconds: float = 0.0
forest_seconds: float = 0.0
effects_seconds: float = 0.0
dropped: int = 0 # rows left out of the last fit as singletons
def column(store, which, path, chunk_rows):
"""Write the store's treatment ("w"), outcome ("y") or instrument ("z")
column to a file."""
out = _memmap(path, store.n)
a = 0
if which == "z":
for z in store.instrument_chunks(chunk_rows):
out[a : a + z.size] = z
a += z.size
else:
for _, w, y, _ in store.chunks(chunk_rows):
out[a : a + w.size] = w if which == "w" else y
a += w.size
out.flush()
del out
return path
def write_difference(a_path, b_path, out_path, n, chunk_rows):
"""out = a - b, for float64 files."""
a = np.load(a_path, mmap_mode="r")
b = np.load(b_path, mmap_mode="r") if b_path is not None else None
out = _memmap(out_path, n)
for s in range(0, n, chunk_rows):
out[s : s + chunk_rows] = a[s : s + chunk_rows] - (
0.0 if b is None else b[s : s + chunk_rows]
)
out.flush()
del out
def rms_difference(a_path, b_path, chunk_rows, weights=None):
"""The root mean square of a - b, for float64 files; weighted by `weights`
(an array in storage order) if given."""
a = np.load(a_path, mmap_mode="r")
b = np.load(b_path, mmap_mode="r")
total = 0.0
for s in range(0, a.size, chunk_rows):
d = np.asarray(a[s : s + chunk_rows]) - np.asarray(b[s : s + chunk_rows])
total += float(d @ d) if weights is None else float(weights[s : s + chunk_rows] @ (d * d))
return float(np.sqrt(total / (a.size if weights is None else weights.sum())))
def _at_noise_floor(changes, tolerance):
"""Whether the changes in the effects have stopped shrinking while within a
few times the tolerance. Each round's forest differs from the last in its
sampling noise, so the changes fall geometrically and then level off at a
floor; asking for less than the floor would never end."""
if len(changes) < 10:
return False
recent, before = min(changes[-5:]), min(changes[-10:-5])
return recent >= 0.8 * before and recent < 5 * tolerance
def _write_pred(g_path, pred, n):
pred = np.where(np.isfinite(pred), pred, np.nanmean(pred))
out = _memmap(g_path, n)
out[:] = pred
out.flush()
def _fit_round(make_engine, store, r, seed, round_dir, g_path, trees=None, keep=False):
"""One forest on the outcome file `r`: its out-of-bag predictions are
written to `g_path`. Returns the seconds taken, and the engine if `keep`
(its trees stay in `round_dir`)."""
t = time.perf_counter()
engine = make_engine(seed) if trees is None else make_engine(seed, trees)
engine.outcome_file = r
engine.fit_store(store, round_dir)
pred = engine.fitted_values()
if not keep:
shutil.rmtree(round_dir, ignore_errors=True)
_write_pred(g_path, pred, store.n)
return (time.perf_counter() - t, engine) if keep else time.perf_counter() - t
def backfit(
*,
store,
which,
effects: GroupEffects | None,
make_engine,
workdir,
tolerance,
max_iterations,
chunk_rows,
iterate=True,
probe_noise=None,
warm_start=True,
log=lambda msg: None,
) -> BackfitResult:
"""Alternate a forest and the group effects for the column `which` ("y" or
"w") of the store, until the effects change, from one round to the next, by
less than `tolerance` times a scale (root mean square over rows).
The scale is the typical standard error of the fitted effects:
``sigma * sqrt(rank / rows)``, for the residuals' standard deviation
`sigma` and the number of parameters `rank` of the fixed effects (see
`GroupEffects.standard_error_scale`). Changes much smaller than that cannot
matter to anything estimated from the effects. If hdfe-stream does not
report the rank, the scale is the noise that reseeding alone makes in the
effects, measured once: a second forest, fitted to the same outcome with
another seed, and the effects it implies (the root mean square difference,
over the square root of two, is the noise of one forest). That noise is
below the standard error by a factor that depends on the number of trees,
so a tolerance in its units is stricter, and the rounds may end at the
noise floor instead. `probe_noise=True` measures it in any case, for
comparison.
The rounds also end when the changes level off within a few times
`tolerance` (the same noise, seen round to round), which counts as
converged.
With `warm_start`, the first round grows a forest and the later rounds keep
its splits and estimate the leaf values again on the new outcome (one pass
over the data per batch of trees, instead of growing the trees again).
Without `effects`, or with ``iterate=False``, there is one round: the
effects (if any) are estimated once from the column itself, then a
forest and its out-of-bag predictions. `make_engine(seed)` returns a
fresh regression engine, for the given seed (None: the default).
"""
workdir = Path(workdir)
workdir.mkdir(parents=True, exist_ok=True)
n = store.n
y0 = column(store, which, workdir / "y0.npy", chunk_rows)
sample_weights = store.weights() if store.weighted else None
n_eff = None
if sample_weights is not None:
n_eff = float(sample_weights.sum() ** 2 / (sample_weights**2).sum())
t0 = time.perf_counter()
forest_s = 0.0
a_path = workdir / "a.npy"
if effects is None:
out = _memmap(a_path, n)
out[:] = 0.0
out.flush()
del out
else:
effects.fitted(y0, a_path)
a_prev = workdir / "a_prev.npy"
g_path = workdir / "g.npy"
changes, changes_abs = [], []
converged = effects is None or not iterate
stopped = "single_round" if converged else "max_iterations"
rounds = 1 if converged else max_iterations
scale = scale_kind = noise = sigma = None
if probe_noise is None:
probe_noise = effects is not None and not effects.rank
it = 0
warm_engine = None
for it in range(1, rounds + 1):
r = workdir / "r.npy"
write_difference(y0, a_path, r, n, chunk_rows)
if warm_start and not converged and warm_engine is not None:
# the trees' splits stay; only the leaf values are estimated again
t_r = time.perf_counter()
warm_engine.reestimate(r)
_write_pred(g_path, warm_engine.fitted_values(), n)
forest_s += time.perf_counter() - t_r
elif warm_start and not converged:
dt, warm_engine = _fit_round(
make_engine, store, r, None, workdir / "round", g_path, keep=True
)
forest_s += dt
else:
forest_s += _fit_round(make_engine, store, r, None, workdir / "round", g_path)
if converged:
break
d = workdir / "d.npy"
write_difference(y0, g_path, d, n, chunk_rows)
shutil.copy(a_path, a_prev)
effects.fitted(d, a_path)
sigma = rms_difference(d, a_path, chunk_rows, sample_weights)
if it == 1 and probe_noise:
# the same outcome, another seed: what the effects differ by is noise
gb, ab = workdir / "g_probe.npy", workdir / "a_probe.npy"
forest_s += _fit_round(make_engine, store, r, 10_007, workdir / "round_probe", gb)
write_difference(y0, gb, workdir / "d_probe.npy", n, chunk_rows)
effects.fitted(workdir / "d_probe.npy", ab)
noise = rms_difference(a_path, ab, chunk_rows) / float(np.sqrt(2.0))
log(f"backfit: reseeding alone moves the effects by {noise:.2e} (root mean square)")
se = effects.standard_error_scale(sigma, n_eff)
if se is not None:
scale, scale_kind = se, "standard_error"
elif noise is not None:
scale, scale_kind = noise, "seed_noise"
change = rms_difference(a_path, a_prev, chunk_rows, sample_weights)
changes_abs.append(change)
changes.append(change / scale if scale else float("nan"))
unit = "standard errors" if scale_kind == "standard_error" else "seed noise"
log(f"backfit round {it}: effects changed by {changes[-1]:.2e} {unit}")
if changes[-1] < tolerance:
converged = True
stopped = "tolerance"
break
if _at_noise_floor(changes, tolerance):
converged = True
stopped = "noise_floor"
break
shutil.rmtree(workdir / "round", ignore_errors=True)
if not converged:
unit = (
"standard errors of the effects"
if scale_kind == "standard_error"
else "the noise from reseeding"
)
warnings.warn(
f"backfitting did not converge in {max_iterations} rounds: the group effects "
f"changed by {changes[-1]:.2e} {unit} in the last (tolerance {tolerance:g}). "
"Raise max_iterations or the tolerance; slow convergence is typical when the "
"features are close to functions of the groups.",
FixedEffectsWarning,
stacklevel=3,
)
return BackfitResult(
effects=a_path,
y0=y0,
fitted=g_path,
iterations=it,
converged=converged,
stopped=stopped,
changes=changes,
changes_abs=changes_abs,
scale=scale,
scale_kind=scale_kind or "",
noise=noise,
sigma=sigma,
seconds=time.perf_counter() - t0,
forest_seconds=forest_s,
effects_seconds=0.0 if effects is None else effects.seconds,
dropped=0 if effects is None else effects.n_dropped,
)
# --------------------------------------------------------- outcome_within
def between_group_shares(lf, features, terms, workdir, verbose=False, weights=None):
"""For each feature, the share of its variance that lies between groups
(the R-squared of the feature on the fixed effects, weighted by the column
`weights` if given), one hdfe-stream call."""
from hdfe_stream import feols_stream
names = ", ".join(features)
fit = feols_stream(
f"sw({names}) ~ 1 | {' + '.join(terms)}"
if len(features) > 1
else f"{features[0]} ~ 1 | {' + '.join(terms)}",
lf,
workdir=workdir,
**({"weights": weights} if weights else {}),
**({} if verbose else {"verbose": False}),
)
models = [fit] if len(features) == 1 else [fit.fetch_model(i) for i in range(len(features))]
if weights:
w = pl.col(weights)
aggs = [w.sum().alias("_w")]
aggs += [(w * pl.col(c)).sum().alias(f"_m{i}") for i, c in enumerate(features)]
aggs += [(w * pl.col(c) ** 2).sum().alias(f"_q{i}") for i, c in enumerate(features)]
else:
aggs = [pl.len().cast(pl.Float64).alias("_w")]
aggs += [pl.col(c).sum().alias(f"_m{i}") for i, c in enumerate(features)]
aggs += [(pl.col(c) ** 2).sum().alias(f"_q{i}") for i, c in enumerate(features)]
moments = lf.select(aggs).collect(engine="streaming").row(0, named=True)
out = {}
for i, (c, m) in enumerate(zip(features, models, strict=True)):
total = moments[f"_q{i}"] - moments[f"_m{i}"] ** 2 / moments["_w"]
res = m.resid()
if weights:
res = res.join(lf.select(weights).with_row_index("row_id"), on="row_id", how="left")
within = res.select((pl.col(weights) * pl.col("resid") ** 2).sum())
else:
within = res.select((pl.col("resid") ** 2).sum())
within = within.collect(engine="streaming").item()
out[c] = float(max(0.0, 1.0 - within / total)) if total > 0 else 0.0
return out
# ------------------------------------------------------------ group means
def _key(term):
return [c.strip() for c in term.split("^")]
def mean_feature_names(features, terms):
return [f"{x}__mean_by_{'_'.join(_key(t))}" for t in terms for x in features]
def group_mean_tables(lf, features, terms, weights=None):
"""For each fixed-effect term, a table of the group means of the features
(one row per group), weighted by the column `weights` if given."""
tables = []
for t in terms:
key = _key(t)
aggs = [
(
(pl.col(x) * pl.col(weights)).sum() / pl.col(weights).sum()
if weights
else pl.col(x).mean()
).alias(f"{x}__mean_by_{'_'.join(key)}")
for x in features
]
tables.append(lf.group_by(key).agg(aggs).collect(engine="streaming"))
return tables
def add_group_means(lf, tables, terms):
"""`lf` with the group means joined on, row order kept."""
for t, table in zip(terms, tables, strict=True):
lf = lf.join(table.lazy(), on=_key(t), how="left", maintain_order="left")
return lf