Forest backend (forestriesz)

forestriesz ships two random-forest backends. They differ in whether the user has to make per-estimand modeling choices to fit the model.

rieszreg exposes the two entry points as Backend.fit_augmented and MomentBackend.fit_rows respectively.

How they work

An estimand has the form \(\mathbb E[m(\mu)(Z, Y)]\). For the built-in estimands, a row’s features are \(Z = (A, X)\), the treatment \(A\) and covariates \(X\); \(Y\) is its outcome, \(\mu(z) = \mathbb E[Y \mid Z = z]\) is the outcome regression, and \(m\) is the estimand’s linear operator, which maps a function such as \(\mu\) to a linear combination of its values at a few points. Both backends estimate the Riesz representer \(\alpha_0\): the function of \(Z\) with \(\mathbb E[m(f)(Z, Y)] = \mathbb E[\alpha_0(Z)\, f(Z)]\) for every square-integrable \(f\). Estimands defines these.

Augmentation-style (AugForestRieszRegressor)

For each original row \(i = 1, \dots, n\), Estimand.augment emits the original observation \(Z_i\) and one evaluation point for each point at which the operator \(m\) evaluates the outcome regression \(\mu\) in \(m(\mu)(Z_i, Y_i)\), merging points that coincide. This gives \(M\) augmented rows in total. Each augmented row \(r\) carries an evaluation point \(z_r\), a weight \(D_r \in \{0, 1\}\) that is \(1\) exactly when \(z_r\) is the original observation, and a coefficient \(C_r\) equal to minus the sum of \(m\)’s coefficients on \(\mu(z_r)\) (\(C_r = 0\) when \(m\) does not evaluate \(\mu\) at \(z_r\)). For ATE, and for TSM on a row already at the target level, the original observation coincides with an evaluation point, so it carries \(D_r = 1\) and \(C_r = \pm 1\); the other evaluation points carry \(D_r = 0\) and \(C_r \ne 0\). Estimands works through the construction.

Each loss is generated by a convex, twice-differentiable function \(h\) with \(h'' > 0\) on the loss’s \(\alpha\)-domain, the set of values its \(\alpha\) may take (see Losses). Write \(h'\) and \(h''\) for its first two derivatives and \(\tilde h(t) = t\,h'(t) - h(t)\). The empirical Bregman-Riesz loss is

\[ \hat L(\alpha) \;=\; \frac{1}{n} \sum_{r=1}^M \big[\, D_r\, \tilde h(\alpha(z_r)) \;+\; C_r\, h'(\alpha(z_r)) \,\big]. \]

Its population counterpart is minimised at the Riesz representer \(\alpha_0\) (Losses). The sum runs over the \(M\) augmented rows, but they come from \(n\) observations, hence the \(1/n\). Grouped by original row \(i\), exactly one of its augmented rows has \(D_r = 1\), and by the definition of \(C_r\) its \(h'\) terms add up to \(-m(h' \circ \alpha)(Z_i, Y_i)\), so \(\hat L(\alpha) = \frac1n \sum_{i=1}^n \big[\tilde h(\alpha(Z_i)) - m(h' \circ \alpha)(Z_i, Y_i)\big]\).

SquaredLoss has \(h(t) = t^2\), so \(h'(t) = 2t\) and \(\tilde h(t) = t \cdot 2t - t^2 = t^2\). Each summand of \(\hat L\) is then \(D_r\, \alpha(z_r)^2 + 2 C_r\, \alpha(z_r)\).

Each tree partitions the feature space into leaves and predicts a single value \(\alpha\) for every point in leaf \(\ell\). With \(D_\ell = \sum_{r \in \ell} D_r\) and \(C_\ell = \sum_{r \in \ell} C_r\) summed over the augmented rows in the leaf, the leaf’s summands add up to \(\sum_{r \in \ell} \big[D_r\, \tilde h(\alpha) + C_r\, h'(\alpha)\big] = D_\ell\, \tilde h(\alpha) + C_\ell\, h'(\alpha)\). No two leaves share a value, so each leaf is optimised on its own, and the factor \(1/n\) does not move the minimiser. The leaf stores

\[ \hat\alpha_\ell \;=\; \arg\min_{\alpha \text{ in the }\alpha\text{-domain}} \big[\, D_\ell\, \tilde h(\alpha) \;+\; C_\ell\, h'(\alpha) \,\big]. \]

By the product rule, \(\tilde h'(t) = h'(t) + t\, h''(t) - h'(t) = t\, h''(t)\), so the derivative of the bracket is \(D_\ell\, \alpha\, h''(\alpha) + C_\ell\, h''(\alpha) = h''(\alpha)\,(D_\ell\, \alpha + C_\ell)\). Every leaf holds at least one original row (min_samples_leaf, at least 1, counts original rows), so \(D_\ell \ge 1\). Because \(h'' > 0\), the derivative has the sign of \(\alpha + C_\ell / D_\ell\): the bracket decreases up to \(-C_\ell / D_\ell\) and increases after it. When \(-C_\ell / D_\ell\) lies in the \(\alpha\)-domain it is the minimiser,

\[ \hat\alpha_\ell \;=\; -\,\frac{C_\ell}{D_\ell}, \]

and this formula is the same for every built-in loss. When \(-C_\ell / D_\ell\) falls outside the \(\alpha\)-domain, the bracket is monotone over the domain, so the minimum is at the nearest boundary. BoundedSquaredLoss(lo, hi) clips the leaf value to \([\mathrm{lo}, \mathrm{hi}]\); for the open domains of KLLoss (\(\alpha > 0\)) and BernoulliLoss (\(0 < \alpha < 1\)) the leaf stores the boundary value or a point just inside it. Tree backend has the details. The forest averages the per-tree predictions of \(\hat\alpha\).

The splitter can split on any feature, the treatment included, and each leaf value \(-C_\ell / D_\ell\) comes straight from the weights \(D_r\) and coefficients \(C_r\) of the augmented rows in the leaf. So the user does not supply any basis functions.

Moment-style (ForestRieszRegressor)

The user supplies a list of functions \(\varphi = (\varphi_1, \dots, \varphi_p)\) of the features \(z\). Within each leaf \(\ell\) the model is \(\alpha(z) = \theta^\top \varphi(z)\) for a coefficient vector \(\theta \in \mathbb R^p\). The forest is grown on the \(n\) original rows and splits on the columns in split_feature_indices (by default the covariates for ATE, ATT, and TSM, and every feature otherwise).

Only SquaredLoss is supported. With \(h(t) = t^2\), the row-grouped form of \(\hat L\) above says original row \(i\) contributes \(\alpha(Z_i)^2 - 2\, m(\alpha)(Z_i, Y_i)\). Because the operator \(m\) is linear, \(m(\theta^\top \varphi) = \theta^\top m(\varphi)\), where \(m(\varphi) = (m(\varphi_1), \dots, m(\varphi_p))\). Let \(n_\ell\) be the number of original rows in leaf \(\ell\) and \(\lambda \ge 0\) the l2 ridge (default \(0\)). Substituting \(\alpha = \theta^\top \varphi\), the leaf’s squared Riesz loss with the ridge penalty is

\[ \sum_{i\in\ell} \Big[\, \big(\theta^\top \varphi(Z_i)\big)^2 - 2\, \theta^\top m(\varphi)(Z_i, Y_i) \,\Big] \;+\; n_\ell\, \lambda\, \lVert\theta\rVert^2 . \]

Write \(G_\ell = \sum_{i\in\ell} \varphi(Z_i)\,\varphi(Z_i)^{\top}\) for the leaf’s Gram matrix and \(b_\ell = \sum_{i\in\ell} m(\varphi)(Z_i, Y_i)\) for its moment sum. Since \(\sum_{i\in\ell} (\theta^\top \varphi(Z_i))^2 = \theta^\top G_\ell\, \theta\) and \(\sum_{i\in\ell} \theta^\top m(\varphi)(Z_i, Y_i) = \theta^\top b_\ell\), the loss is \(\theta^\top (G_\ell + n_\ell \lambda I)\, \theta - 2\, \theta^\top b_\ell\). The Gram matrix is a sum of outer products, so \(G_\ell + n_\ell \lambda I\) is positive semidefinite and the loss is convex in \(\theta\). Its gradient \(2\big[(G_\ell + n_\ell \lambda I)\,\theta - b_\ell\big]\) vanishes at the minimiser, so the leaf solves the linear-moment equation \((G_\ell + n_\ell \lambda I)\,\theta = b_\ell\). When \(G_\ell + n_\ell \lambda I\) is invertible (always when \(\lambda > 0\); when \(\lambda = 0\), exactly when the Gram matrix is),

\[ \hat\theta_\ell \;=\; \big(G_\ell + n_\ell\,\lambda I\big)^{-1} b_\ell . \]

Splits use EconML’s "mse" criterion, which approximately chooses the split whose children’s leaf coefficients \(\hat\theta_\ell\) most lower this loss.

The forest does not average the per-tree leaf coefficients \(\hat\theta_\ell\). As in generalized random forests (GRF), it pools the leaf sums across trees. For a query point \(z\) and trees \(t = 1, \dots, T\), let \(\ell_t(z)\) be the leaf of tree \(t\) that contains \(z\), and give original row \(i\) the weight \(w_i(z) = \frac{1}{T} \sum_{t=1}^{T} \mathbf 1\{i \in \ell_t(z)\} / n_{\ell_t(z)}\). Here a leaf holds only the rows of its tree’s subsample (the estimation half when honest=True), and \(n_{\ell_t(z)}\) counts them. In each tree the indicator picks out the \(n_{\ell_t(z)}\) rows of \(z\)’s leaf, each weighted \(1/n_{\ell_t(z)}\), so they total \(1\); averaging over trees keeps the total at \(1\). The weights depend on \(z\) only through the split columns. The forest’s coefficient \(\hat\theta(z)\) solves the weighted version of the leaf equation (with a pseudo-inverse when the left side is singular),

\[ \Big(\sum_{i=1}^{n} w_i(z)\, \varphi(Z_i)\,\varphi(Z_i)^{\top} + \lambda I\Big)\, \hat\theta(z) \;=\; \sum_{i=1}^{n} w_i(z)\, m(\varphi)(Z_i, Y_i), \]

and the prediction is \(\hat\alpha(z) = \hat\theta(z)^\top \varphi(z)\). With a single tree, \(w_i(z) = \mathbf 1\{i \in \ell\} / n_\ell\) for \(z\)’s leaf \(\ell\), and this equation is the leaf equation divided by \(n_\ell\), which is why the ridge appears as \(\lambda\) rather than \(n_\ell \lambda\).

The list \(\varphi\) has to be chosen per estimand. The default riesz_feature_fns="auto" picks defaults for built-in estimands:

Estimand Default list Effect
ATE, ATT [1{A=0}, 1{A=1}] Forest splits on covariates only; the basis resolves treatment in each leaf.
TSM(level=v) [1{A=v}] Single-basis fit; intervals supported.
AdditiveShift, LocalShift, custom none — auto-resolution falls back to a constant function, which is row-degenerate Backend raises with a hint. Use AugForestRieszRegressor instead, or pass a custom list.

For ATE with the default basis \(\varphi(a, x) = (\mathbf 1\{a = 0\}, \mathbf 1\{a = 1\})\), every row has \(m(\varphi)(Z_i, Y_i) = \varphi(1, X_i) - \varphi(0, X_i) = (0, 1) - (1, 0) = (-1, 1)\), so the moment sum is \(b_\ell = (-n_\ell, n_\ell)\). Each row’s \(\varphi(Z_i)\varphi(Z_i)^\top\) is \(\operatorname{diag}(1, 0)\) if untreated and \(\operatorname{diag}(0, 1)\) if treated, so the Gram matrix is \(G_\ell = \operatorname{diag}(n_{\ell,0},\, n_{\ell,1})\), where \(n_{\ell,0}\) and \(n_{\ell,1}\) count the untreated and treated rows in the leaf. Write \(\hat P(A = a \mid \ell) = n_{\ell,a} / n_\ell\) for the leaf’s share of rows with \(A = a\). With ridge \(\lambda = 0\) and both arms present in the leaf (\(n_{\ell,0}, n_{\ell,1} > 0\), so the Gram matrix is invertible), the leaf solve is \(\hat\theta_\ell = G_\ell^{-1} b_\ell = (-n_\ell / n_{\ell,0},\; n_\ell / n_{\ell,1})\); dividing each numerator and denominator by \(n_\ell\),

\[ \hat\theta_\ell \;=\; \Big(-\frac{1}{\hat P(A = 0 \mid \ell)},\; \frac{1}{\hat P(A = 1 \mid \ell)}\Big). \]

Since \(\hat\alpha = \hat\theta_\ell^\top \varphi\) picks out the coordinate of the point’s arm, a treated point in the leaf gets \(\hat\alpha = 1/\hat P(A = 1 \mid \ell)\) and an untreated one gets \(-1/\hat P(A = 0 \mid \ell)\). The forest’s prediction follows from the same algebra with the weights \(w_i(z)\) in place of \(1/n_\ell\). Let \(\hat\pi(z) = \sum_i w_i(z)\, A_i\) be the forest-weighted share of treated rows. The weighted Gram matrix is \(\operatorname{diag}(1 - \hat\pi(z),\, \hat\pi(z))\) and the weighted moment sum is \((-1, 1)\), so \(\hat\alpha(1, x) = 1/\hat\pi(z)\) and \(\hat\alpha(0, x) = -1/(1 - \hat\pi(z))\). This is the inverse-propensity-weight representer \(\alpha_0(a, x) = a/\pi(x) - (1 - a)/(1 - \pi(x))\), with the propensity score \(\pi(x) = P(A = 1 \mid X = x)\) replaced by the forest-weighted treated share \(\hat\pi(z)\).

How they differ

AugForestRieszRegressor ForestRieszRegressor
Per-estimand setup none — works on every estimand directly user supplies riesz_feature_fns (auto-resolved for ATE, ATT, TSM)
Loss support SquaredLoss, KLLoss, BernoulliLoss, BoundedSquaredLoss SquaredLoss only
Confidence intervals not in v1 yes — predict_interval on single-basis fits with honest=True, inference=True
Splits on full feature space covariates only when the basis handles treatment
Backend Protocol Backend.fit_augmented MomentBackend.fit_rows
When to pick default for general use; required for shift-style or custom estimands when you need CIs on ATE, ATT, or TSM

Bregman losses

AugForestRieszRegressor accepts every loss rieszreg ships. The per-tree splitter dispatches to a per-loss leaf-loss formula (squared, KL, Bernoulli, bounded-squared) so splits are chosen against the loss the user actually supplied. The forest averages the per-tree predictions \(\hat\alpha\) of the representer.

import numpy as np, pandas as pd
from forestriesz import AugForestRieszRegressor, TSM
from rieszreg import KLLoss

rng = np.random.default_rng(0)
n = 1500
x = rng.uniform(0, 1, n)
pi = 1 / (1 + np.exp(-(0.5 * x - 0.3)))
a = rng.binomial(1, pi).astype(float)
df_tsm = pd.DataFrame({"a": a, "x": x})

# KLLoss is matched to density-ratio estimands like TSM and IPSI,
# whose α is non-negative.
est = AugForestRieszRegressor(
    estimand=TSM(level=1, treatment="a", covariates=("x",)),
    loss=KLLoss(),
    n_estimators=200,
    random_state=0,
)
est.fit(df_tsm)
AugForestRieszRegressor(estimand=<rieszreg.estimands.base.TSM object at 0x7f202f77fd10>,
                        loss=<rieszreg.losses.kl.KLLoss object at 0x7f202fb06de0>,
                        n_estimators=200)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
alpha_hat = est.predict(df_tsm)
print(f"alpha_hat range: [{alpha_hat.min():.3f}, {alpha_hat.max():.3f}]")
alpha_hat range: [0.000, 2.856]

KLLoss and BernoulliLoss can’t represent ATE / ATT / shift-style estimands, because their Riesz representer \(\alpha_0\) takes negative values, outside both losses’ \(\alpha\)-domains; fit warns, and the fitted \(\hat\alpha\) collapses to 0. BoundedSquaredLoss(lo, hi) with lo < 0 accepts them and clips \(\hat\alpha\) into the interval.

Quickstart — ATE

import numpy as np, pandas as pd
from forestriesz import ForestRieszRegressor, ATE

rng = np.random.default_rng(0)
n = 1500
x = rng.uniform(0, 1, n)
pi = 1 / (1 + np.exp(-(-0.02*x - x**2 + 4*np.log(x + 0.3) + 1.5)))
a = rng.binomial(1, pi).astype(float)
df = pd.DataFrame({"a": a, "x": x})

fr = ForestRieszRegressor(
    estimand=ATE(treatment="a", covariates=("x",)),
    n_estimators=500,
    min_samples_leaf=10,
    random_state=0,
)
fr.fit(df)
ForestRieszRegressor(estimand=<rieszreg.estimands.base.ATE object at 0x7f2023b7b170>,
                     min_samples_leaf=10, n_estimators=500)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
alpha_hat  = fr.predict(df)
true_alpha = a / pi - (1 - a) / (1 - pi)
print(f"corr(α̂, α₀) = {np.corrcoef(alpha_hat, true_alpha)[0, 1]:.3f}")
corr(α̂, α₀) = 0.939
print(f"RMSE         = {np.sqrt(np.mean((alpha_hat - true_alpha)**2)):.3f}")
RMSE         = 0.880
pkgload::load_all("../packages/forestriesz/r/forestriesz")
use_python_forestriesz(file.path(getwd(), "../.venv/bin/python"))

set.seed(0)
n  <- 1500
x  <- runif(n)
pi <- 1 / (1 + exp(-(-0.02 * x - x^2 + 4 * log(x + 0.3) + 1.5)))
a  <- rbinom(n, 1, pi)
df <- data.frame(a = as.numeric(a), x = x)

fr <- ForestRieszRegressor$new(
  estimand = ATE(treatment = "a", covariates = "x"),
  n_estimators = 500,
  min_samples_leaf = 10,
  random_state = 0
)
fr$fit(df)

alpha_hat  <- fr$predict(df)
true_alpha <- a / pi - (1 - a) / (1 - pi)
cat(sprintf("corr(α̂, α₀) = %.3f\n", cor(alpha_hat, true_alpha)))

Quickstart — AdditiveShift with the augmentation-style backend

AdditiveShift has no canonical list of basis functions, so the moment-style backend would require the user to construct one. AugForestRieszRegressor works on it directly.

from forestriesz import AugForestRieszRegressor, AdditiveShift

# Continuous-treatment data
a_cont = rng.normal(0.5*x, 1.0)
df_cont = pd.DataFrame({"a": a_cont, "x": x})

afr = AugForestRieszRegressor(
    estimand=AdditiveShift(delta=0.5, treatment="a", covariates=("x",)),
    n_estimators=500,
    random_state=0,
)
afr.fit(df_cont)
AugForestRieszRegressor(estimand=<rieszreg.estimands.base.AdditiveShift object at 0x7f2024ab53d0>,
                        n_estimators=500)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
alpha_hat = afr.predict(df_cont)
print(f"alpha_hat range: [{alpha_hat.min():.3f}, {alpha_hat.max():.3f}]")
alpha_hat range: [-0.808, 1.694]

Quickstart — TSM with confidence intervals

TSM uses a single-basis fit, so v1’s predict_interval works. It returns an interval for the true representer \(\alpha_0\) at each row. For TSM(level=1) the basis is \(0\) on untreated rows, so their interval is the single point \(0 = \alpha_0\). The check below uses the treated rows, where \(\alpha_0 = 1/\pi(x)\), the inverse of the propensity score \(\pi(x) = P(A = 1 \mid X = x)\) (pi in the ATE quickstart). The intervals reflect the forest’s sampling variance but not its smoothing bias, so pointwise coverage can fall below the nominal level.

from forestriesz import ForestRieszRegressor, TSM

fr = ForestRieszRegressor(
    estimand=TSM(level=1, treatment="a", covariates=("x",)),
    n_estimators=500,
    honest=True,
    inference=True,
    random_state=0,
)
fr.fit(df)
ForestRieszRegressor(estimand=<rieszreg.estimands.base.TSM object at 0x7f20239fe420>,
                     honest=True, inference=True, n_estimators=500)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
alpha_hat = fr.predict(df)
lb, ub    = fr.predict_interval(df, alpha=0.05)

true_alpha = a / pi          # α₀ for TSM(level=1)
treated    = a == 1
covers     = (lb <= true_alpha) & (true_alpha <= ub)
print(f"treated rows: mean 95% CI width     = {(ub - lb)[treated].mean():.3f}")
treated rows: mean 95% CI width     = 0.981
print(f"treated rows: share covering α₀     = {covers[treated].mean():.2f}")
treated rows: share covering α₀     = 0.88
pkgload::load_all("../packages/forestriesz/r/forestriesz")
use_python_forestriesz(file.path(getwd(), "../.venv/bin/python"))

fr <- ForestRieszRegressor$new(
  estimand = TSM(level = 1L, treatment = "a", covariates = "x"),
  n_estimators = 500L,
  honest = TRUE,
  inference = TRUE,
  random_state = 0L
)
fr$fit(df)
alpha_hat <- fr$predict(df)
ci <- fr$predict_interval(df, alpha = 0.05)

true_alpha <- a / pi          # α₀ for TSM(level = 1)
treated    <- a == 1
covers     <- ci$lb <= true_alpha & true_alpha <= ci$ub
cat(sprintf("treated rows: mean 95%% CI width     = %.3f\n", mean((ci$ub - ci$lb)[treated])))
cat(sprintf("treated rows: share covering α₀     = %.2f\n", mean(covers[treated])))

Hyperparameters

AugForestRieszRegressor

Mirrors sklearn.ensemble.RandomForestRegressor:

Knob Default Notes
n_estimators 100 Number of trees.
max_depth None Grow until leaves saturate min_samples_leaf.
min_samples_split 2 Minimum count of original (\(D_r = 1\)) augmented rows in a node before considering a split.
min_samples_leaf 50 Minimum count of original rows in each child of a candidate split. Leaves store a ratio of sums, \(-C_\ell / D_\ell\), so small leaves give noisy leaf values \(\hat\alpha_\ell\); the best value grew with \(n\) in simulations (roughly \(2\sqrt{n}\)), so raise it for large samples.
max_features 1.0 Per-split feature-subsampling rule.
max_leaf_nodes None Cap on per-tree leaf count. When set, trees grow best-first, as in sklearn.
min_impurity_decrease 0.0 Reject splits below this gain.
ccp_alpha 0.0 Cost-complexity pruning per tree.
bootstrap True Per-tree resampling at the original-row level (block bootstrap).
max_samples None Per-tree subsample size as fraction or count of original rows.
n_jobs None Parallelism across trees via joblib.Parallel.
splitter "exact" "exact", "hist", or "random" — riesztree splitter dispatch.
max_bins 255 Histogram-splitter bin count.
categorical_features None Column names, or positions in feature_keys, treated as integer category labels.

With splitter="hist", the bin mapper is fitted once on the full augmented training data and every tree slices the shared binned matrix (the sklearn HistGradientBoostingRegressor convention). The win is largest at shallow depths, where per-tree binning dominates tree-build time.

init has no effect on AugForestRieszRegressor: each leaf stores its loss-optimal value \(\hat\alpha_\ell\) directly.

random_state seeds the whole forest. Each tree gets two seeds derived from it: one for its bootstrap draw and one for the tree’s own randomness (per-split feature sampling when max_features < 1, random thresholds when splitter="random"). The two are drawn separately, so a tree’s bootstrap sample and its feature sampling are independent, as in EconML’s GRF. sklearn’s RandomForestRegressor instead starts both from the same per-tree seed.

ForestRieszRegressor

Forwarded to EconML’s BaseGRF:

Knob Default Notes
n_estimators 100 Number of trees. With inference=True must be divisible by subforest_size (default 4).
max_depth None Grow until leaves saturate min_samples_leaf.
min_samples_leaf 5 Tighter leaves give lower bias, higher variance. Paper guidance: 5–20.
min_samples_split 10
max_samples 0.45 Per-tree subsample fraction. GRF default.
honest False Enable for valid-coverage CIs (50/50 sample split).
inference False Enable for predict_interval; preserves subforest structure.
subforest_size 4 Trees per subforest when computing inference variance.
l2 0 The ridge \(\lambda\): each leaf solves \((G_\ell + n_\ell \lambda I)\,\theta = b_\ell\) (Moment-style). For TSM(level=v) the basis is \(\varphi = \mathbf 1\{A = v\}\), so every row has \(m(\varphi) = 1\), the moment sum is \(b_\ell = n_\ell\), and the Gram matrix is the count \(n_{\ell,v}\) of rows at level \(v\). The leaf coefficient is \(\hat\theta_\ell = n_\ell / (n_{\ell,v} + n_\ell \lambda) = 1 / (\hat P(A = v \mid \ell) + \lambda)\), with \(\hat P(A = v \mid \ell) = n_{\ell,v} / n_\ell\) the leaf’s share at level \(v\). With \(\lambda = 0\) a leaf with no rows at level \(v\) has no solution to its leaf equation. EconML’s split score counts such a child as \(0\), which puts the split below the unsplit node, so with honest=False the forest never grows one. With \(\lambda > 0\) the same child solves to \(\hat\theta_\ell = 1/\lambda\) exactly, and its ridge-penalised loss is \(-n_\ell/\lambda\), so the forest favours these leaves. They pull the predicted \(\hat\alpha\) of query points at level \(v\) toward \(1/\lambda\), which is very large for small \(\lambda\). With honest=True, a leaf’s estimation half can lack rows at level \(v\) even at \(\lambda = 0\). Such a leaf adds to the right side of the forest equation but not the left, which inflates \(\hat\alpha\) near it. Leave it at 0 unless you need it.
n_jobs -1 Parallel tree training.

Save / load

import tempfile, os
with tempfile.TemporaryDirectory() as tmp:
    save_dir = os.path.join(tmp, "fitted")
    fr.save(save_dir)

    loaded = ForestRieszRegressor.load(save_dir)
    pred_loaded = loaded.predict(df)
    print(f"max abs diff after round-trip: {np.max(np.abs(pred_loaded - alpha_hat)):.2e}")
max abs diff after round-trip: 1.78e-15

For built-in estimands the moment-style basis is auto-resolved on load. For custom bases, repass the callables: ForestRieszRegressor.load(path, riesz_feature_fns=my_basis). AugForestRieszRegressor round-trips without any extra arguments.

Sklearn integration

Both regressors are BaseEstimators, so they compose with clone, GridSearchCV, cross_val_predict, Pipeline. See Tuning and Cross-Fitting.

Basis requirements (moment-style only)

For built-in estimands the per-row moment \(m(\varphi)(Z_i, Y_i)\) doesn’t depend on \(Z_i\) when \(\varphi \equiv 1\), so the constant basis is degenerate (every leaf would predict the same constant). ForestRieszRegressor raises on the constant basis, whether from an explicit riesz_feature_fns=None or from "auto" on an estimand with no default basis. For ATE, ATT and TSM the error points to "auto" or AugForestRieszRegressor; otherwise it points to a custom list or AugForestRieszRegressor. AugForestRieszRegressor is unaffected — its splitter does not depend on a user-supplied basis.

For ATE, ATT and TSM the forest splits on the covariates only (unless you pass split_feature_indices), so the basis \(\varphi\) has to carry all of the dependence of the representer on the treatment \(A\). For other estimands the forest also splits on \(A\), but the requirements below still apply. A custom riesz_feature_fns must meet both.

The basis must vary across the points the estimand evaluates. As on the Estimands page, write the estimand for row \(i\), with observation \(Z_i\) and outcome \(Y_i\), as a weighted sum of its argument at evaluation points,

\[ m(\mu)(Z_i, Y_i) \;=\; \textstyle\sum_{j} C_{ij}\, \mu(Z_{ij}), \]

with coefficients \(C_{ij}\) and evaluation points \(Z_{ij}\) that share the covariates \(X_i\) but set the treatment: \(A = 1\) and \(A = 0\) for ATE, and for ATT on treated rows (\(A_i = 1\)); \(A = v\) for TSM(level=v); \(A = A_i + \delta\) (the observed treatment \(A_i\) plus the shift amount \(\delta\), delta) and \(A = A_i\) for AdditiveShift; and the same two points for LocalShift when \(A_i\) is below its threshold \(t\) (threshold). Call the basis uninformative if, for every row, every basis function takes the same value at the observed point \(Z_i\) and at each evaluation point \(Z_{ij}\). Then \(\varphi(Z_{ij}) = \varphi(Z_i)\), so the moment of the basis factors as

\[ m(\varphi)(Z_i, Y_i) \;=\; \textstyle\sum_j C_{ij}\, \varphi(Z_{ij}) \;=\; \Big(\textstyle\sum_j C_{ij}\Big)\, \varphi(Z_i) \;=\; m(1)(Z_i, Y_i)\, \varphi(Z_i), \]

where \(m(1)\) is the estimand applied to the constant function \(1\), the sum of its coefficients. For every built-in estimand \(m(1)\) is a constant: \(1 - 1 = 0\) for ATE, ATT, AdditiveShift and LocalShift, and \(1\) for TSM. Substituting the factored moment into the leaf solve above gives

\[ \hat\theta_\ell \;=\; \big(\textstyle\sum_{i\in\ell} \varphi(Z_i)\,\varphi(Z_i)^{\top} + n_\ell\,\lambda I\big)^{-1} \textstyle\sum_{i\in\ell} \varphi(Z_i)\, m(1)(Z_i, Y_i), \]

the coefficients of a least-squares regression (ridge, when l2 \(> 0\)) of the known quantity \(m(1)\) on the basis. When \(m(1)\) is a constant, as for every built-in, that regression target carries no information about the treatment, whichever columns the forest splits on. For ATE, ATT and the shift estimands the target is \(0\), so \(\hat\theta_\ell = 0\) and the fitted representer \(\hat\alpha\) is \(0\) everywhere. For TSM the target is \(1\), so with l2 \(= 0\), \(\hat\alpha = 1\) whenever the basis can express a constant within each leaf. In both cases \(\hat\alpha\) equals \(\mathbb E[\alpha_0(Z) \mid X]\), the true representer \(\alpha_0\) averaged over the treatment given the covariates: applying the Riesz representation \(\mathbb E[m(f)(Z, Y)] = \mathbb E[\alpha_0(Z) f(Z)]\) to a function \(f\) of the covariates alone, for which \(m(f) = m(1)\, f\) because every evaluation point shares the covariates, gives \(\mathbb E[\alpha_0(Z) f(X)] = \mathbb E[m(1)(Z, Y) f(X)]\) for every such \(f\), so \(\mathbb E[\alpha_0(Z) \mid X] = \mathbb E[m(1)(Z, Y) \mid X]\), which is \(0\) or \(1\).

Apart from the constant basis, which raises (above), ForestRieszRegressor still fits an uninformative basis but warns that \(\hat\alpha\) estimates \(\mathbb E[\alpha_0(Z) \mid X]\). This check is skipped for estimands that evaluate only the observed point. Separately, if the basis is not flagged as uninformative but the moment \(m(\varphi)(Z_i, Y_i)\) of every basis function is zero on every row, it warns that each leaf parameter \(\hat\theta_\ell\), and therefore the fitted representer \(\hat\alpha\), is \(0\).

What else the basis must represent depends on the estimand. Within a leaf, the basis must be able to express how the true representer \(\alpha_0\) varies with the treatment \(A\):

Estimand How \(\alpha_0\) depends on the treatment \(A\) Basis
ATE (binary \(A\)) \(\alpha_0(A, X) = \mathbb 1\{A = 1\}/\pi(X) - \mathbb 1\{A = 0\}/(1 - \pi(X))\), with propensity \(\pi(X) = P(A = 1 \mid X)\) The default [1{A=0}, 1{A=1}] represents its dependence on \(A\) exactly; the forest approximates the functions of \(X\).
ATT (binary \(A\)) \(\alpha_0(A, X) = \mathbb 1\{A = 1\} - \mathbb 1\{A = 0\}\, \pi(X)/(1 - \pi(X))\), for the unnormalized moment \(A\,(\mu(1, X) - \mu(0, X))\), without dividing by \(P(A = 1)\) The same default, exactly in \(A\).
TSM(level=v) \(\alpha_0(A, X) = \mathbb 1\{A = v\} / P(A = v \mid X)\), with \(P(A = v \mid X)\) the probability of level \(v\) given the covariates The default [1{A=v}], exactly in \(A\).
AdditiveShift (continuous \(A\)) \(\alpha_0(A, X) = p(A - \delta \mid X)/p(A \mid X) - 1\), with \(p(\cdot \mid X)\) the conditional density of the treatment No default. Without knowing the conditional density, no fixed basis represents this exactly in general: pass a sieve in \(A\), such as polynomials or splines, and accept some approximation error.
LocalShift(threshold=t) (continuous \(A\)) \(\alpha_0(A, X) = \mathbb 1\{A < t + \delta\}\, p(A - \delta \mid X)/p(A \mid X) - \mathbb 1\{A < t\}\) No default. As for AdditiveShift, and include the indicators \(\mathbb 1\{A < t\}\) and \(\mathbb 1\{A < t + \delta\}\), where the representer jumps.

A basis that adds covariate-only functions to these still fits, provided the functions are linearly independent within each leaf. The ATE and ATT default already sums to the constant function, so adding a covariate function that is constant, or nearly constant, within a leaf makes the leaf solve singular or unstable; small leaves make this more likely.

NoteNot stated in the ForestRiesz paper

Chernozhukov et al. (2022), Section 4, allow splits on the covariates only and write the basis as \(\varphi(T, X)\), a function of the treatment \(T\) (called \(A\) on this page) and the covariates \(X\), but state neither requirement above. The first follows from the leaf solve: with an uninformative basis, each leaf regresses the known quantity \(m(1)\) on the basis, and for every estimand on this page \(m(1)\) is a constant, so no split can recover how the representer depends on the treatment. (For a derivative functional, which the paper also considers, a basis that does not depend on the treatment has moment \(0\) directly.)