# Causal Forests in Python: Estimate and Plot CATE with EconML

> Fit CausalForestDML from EconML to estimate conditional average treatment effects (CATE) in Python, plot them with confidence intervals, find what drives them, and decide whom to treat.

Source: https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, causal forest, cate, heterogeneous treatment effects, econml, random forest, matplotlib

A causal forest estimates the conditional average treatment effect (CATE): how
much a treatment changes the outcome for a unit with given characteristics. In
Python, fit `CausalForestDML` from EconML with `fit(Y, T, X=X)`, then call
`effect(X)` for each row's estimated effect and `effect_interval(X)` for its
confidence interval. This post uses EconML 0.17.1 and scikit-learn 1.9
(`pip install econml`).

## Quick Example

A software company's sales team gives some new accounts an onboarding call.
Larger accounts are more likely to get one, so a raw comparison is biased. The
data is simulated, so the true effect is known: the call is worth about $30 a
month for a brand new account and fades toward $4 for old ones.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from econml.dml import CausalForestDML
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor

rng = np.random.default_rng(163)

# Sample data: monthly spend, with and without an onboarding call
n = 6000
df = pd.DataFrame({
    "tenure": rng.uniform(0, 60, n).round(),   # months as a customer
    "seats": rng.integers(1, 51, n),
    "logins": rng.poisson(12, n),
    "region": rng.integers(0, 4, n),
})
true_effect = 4 + 26 * np.exp(-df.tenure / 15)      # unknown in real life
p_call = 1 / (1 + np.exp(0.8 - 0.05 * (df.seats - 25)))  # big accounts get calls
df["called"] = rng.binomial(1, p_call)
df["spend"] = (60 + 2.5 * df.seats + 1.5 * df.logins + 0.3 * df.tenure
               + true_effect * df.called + rng.normal(0, 15, n))

X = df[["tenure", "seats", "logins", "region"]]
forest = CausalForestDML(
    model_y=RandomForestRegressor(min_samples_leaf=10, random_state=0),
    model_t=RandomForestClassifier(min_samples_leaf=20, random_state=0),
    discrete_treatment=True,
    n_estimators=1000, min_samples_leaf=10, cv=5, random_state=0,
)
forest.fit(df.spend, df.called, X=X)

cate = forest.effect(X)
low, high = forest.effect_interval(X, alpha=0.05)

fig, ax = plt.subplots(figsize=(8, 4.8))
order = np.argsort(df.tenure.values, kind="stable")
ax.scatter(df.tenure + rng.uniform(-0.4, 0.4, n), cate, s=5, alpha=0.25,
           color="#2a7f9e", label="Estimated effect (one per account)")
ax.plot(df.tenure.values[order], true_effect.values[order], color="#d1495b",
        lw=2.5, label="True effect")
ax.set_xlabel("Tenure (months)")
ax.set_ylabel("Effect of a call on monthly spend ($)")
ax.set_title("Onboarding calls help new accounts the most")
ax.legend()
plt.show()
```

![Scatter plot of estimated treatment effects against tenure, falling from about 25 dollars for new accounts to about 5 dollars for old ones, closely following the red true effect curve](https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/images/causal-forest-cate.png)

The forest recovers the downward curve without being told its shape. Across all
6,000 accounts the correlation between estimated and true effects is 0.97, with
a typical (root mean squared) error of about $1.70.

## What is the average treatment effect?

After fitting, `ate_` holds a doubly robust estimate of the average effect and
`ate_stderr_` its standard error.

```python
ate, se = forest.ate_[0], forest.ate_stderr_[0]
raw = df.groupby("called").spend.mean().diff().iloc[1]

print(f"raw difference: {raw:.1f}")
print(f"forest ATE:     {ate:.1f} (95% CI {ate - 1.96 * se:.1f} to {ate + 1.96 * se:.1f})")
print(f"true ATE:       {true_effect.mean():.1f}")
```

```text
raw difference: 36.6
forest ATE:     9.9 (95% CI 8.9 to 11.0)
true ATE:       10.4
```

Comparing called and uncalled accounts says a call is worth $36.60, more than
three times the truth, because called accounts are bigger. The forest adjusts
for that.

`forest.ate(X)` also exists and averages the per-row estimates. Its
`ate_interval(X)` was much wider here (about 5.8 to 14.7), so use `ate_` when the
question is about the average.

## How do I plot CATE by group with confidence intervals?

`effect_interval(X_new)` works on any rows you pass, including a grid you build.
Vary one feature and hold the others at typical values:

```python
grid = pd.DataFrame({"tenure": np.arange(0, 61), "seats": 25,
                     "logins": 12, "region": 1})
point = forest.effect(grid)
lo, hi = forest.effect_interval(grid, alpha=0.05)

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.fill_between(grid.tenure, lo, hi, color="#7a5ea8", alpha=0.25,
                label="95% interval")
ax.plot(grid.tenure, point, color="#5b3f8c", lw=2, label="Estimate")
ax.plot(grid.tenure, 4 + 26 * np.exp(-grid.tenure / 15), color="#d1495b",
        ls="--", lw=2, label="True effect")
ax.set_xlabel("Tenure (months), for a 25-seat account")
ax.set_ylabel("Effect on monthly spend ($)")
ax.legend()
plt.show()
```

![Estimated treatment effect by tenure for a 25-seat account with a shaded 95 percent confidence band and the dashed true effect curve](https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/images/causal-forest-cate-interval.png)

```python
covered = np.mean((low <= true_effect) & (true_effect <= high))
print(f"{covered:.0%} of per-account intervals contain the true effect")
```

```text
97% of per-account intervals contain the true effect
```

Each interval is for one point on the curve, not for the whole curve at once.
They are also honest only about sampling noise: an unmeasured confounder would
shift both the line and the band.

## Which features drive the effect?

`feature_importances_` measures how much each feature in `X` is used to split on
differences in the *effect*, not in the outcome.

```python
importance = pd.Series(forest.feature_importances_, index=X.columns).sort_values()

fig, ax = plt.subplots(figsize=(7, 3.2))
bars = ax.barh(importance.index, importance, color="#2a7f9e")
ax.bar_label(bars, fmt="{:.2f}", padding=3)
ax.set_xlim(0, 1.05)
ax.set_title("What explains differences in the effect?")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Horizontal bar chart of causal forest feature importance with tenure far ahead of seats, logins and region](https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/images/causal-forest-importance.png)

`seats` strongly affects spend and who gets a call, but barely registers here,
since it doesn't change how much a call helps. That differs from ordinary
[feature importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/).

## Summarize the forest as a simple tree

`SingleTreeCateInterpreter` fits a shallow tree to the estimated effects, which
gives you segments you can describe to someone.

```python
from econml.cate_interpreter import SingleTreeCateInterpreter

interpreter = SingleTreeCateInterpreter(max_depth=2, min_samples_leaf=200)
interpreter.interpret(forest, X)

fig, ax = plt.subplots(figsize=(10, 4.8))
interpreter.plot(ax=ax, feature_names=list(X.columns), fontsize=10)
plt.show()
```

![Decision tree of depth two splitting accounts by tenure, showing the average estimated treatment effect in each of four segments](https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/images/causal-forest-tree.png)

All of the splits are on `tenure`. The tree is a description of the forest, so
treat the exact cut points as rounded guides.

## Whom should we treat?

Say a call costs the equivalent of $12 of monthly spend. Call an account only if
its estimated effect is higher than that. Because this is simulated data, the
true effect can score each rule.

```python
cost = 12
rules = {
    "Call nobody": np.zeros(n, bool),
    "Call everybody": np.ones(n, bool),
    "Call if estimate > cost": cate > cost,
    "Perfect knowledge": (true_effect > cost).values,
}
value = pd.Series({name: ((true_effect - cost) * chosen).sum() / n
                   for name, chosen in rules.items()})

fig, ax = plt.subplots(figsize=(8, 3.6))
colors = ["#9aa0a6", "#9aa0a6", "#2a7f9e", "#d1495b"]
bars = ax.barh(value.index, value, color=colors)
ax.bar_label(bars, padding=4,
             labels=[f"{'-' if v < 0 else ''}${abs(v):.2f}" for v in value])
ax.axvline(0, color="black", lw=0.8)
ax.invert_yaxis()
ax.set_xlim(-2.5, 3)
ax.set_xlabel("Net value per account per month")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
```

![Net value per account for four targeting rules: calling everybody loses money while calling accounts with a high estimated effect earns nearly as much as perfect knowledge](https://www.pythoncharts.com/causal-inference/causal-forest-cate-python/images/causal-forest-policy.png)

Calling everybody loses money, even though the average effect is positive.
Calling only the accounts whose estimate clears the cost gets close to the best
any rule could do on this data. On real data you can't score a rule this way, so
test it with a randomized experiment, or estimate its value on held-out data.

## Causal forest or another method?

| Question | Method |
|---|---|
| What is the average effect, with many confounders? | [Double machine learning](https://www.pythoncharts.com/causal-inference/double-machine-learning-python/) |
| How does the effect vary across many features? | Causal forest |
| Do a few segments you chose in advance differ? | [Segment analysis](https://www.pythoncharts.com/ab-testing/heterogeneous-treatment-effects-segments-python/) with interaction terms |
| Rank customers for a campaign from experiment data | [Uplift modeling](https://www.pythoncharts.com/causal-inference/uplift-modeling-python/) |
| Treatment depends on something you didn't measure | [Instrumental variables](https://www.pythoncharts.com/causal-inference/instrumental-variables-2sls-python/) |

## Practical tips

- A causal forest only handles confounders you give it. Features that affect the effect go in `X`; extra confounders that don't can go in `W`.
- Check overlap first. If some kinds of accounts always or never get the treatment, their estimates are extrapolation.
- Don't put variables measured after the treatment in `X` or `W`.
- Set `discrete_treatment=True` for a yes/no treatment and pass a classifier as `model_t`.
- Individual estimates are noisy compared with group averages. Act on segments or ranked groups, not on one account's number.
- Real effects are usually smaller and noisier than in this simulation, which needs far more data.

## Similar Topics

- [Double Machine Learning in Python with DoubleML](https://www.pythoncharts.com/causal-inference/double-machine-learning-python/)
- [Heterogeneous Treatment Effects and Segment Analysis](https://www.pythoncharts.com/ab-testing/heterogeneous-treatment-effects-segments-python/)
- [Propensity Score Matching in Python](https://www.pythoncharts.com/causal-inference/propensity-score-matching-python/)
