# Double Machine Learning in Python with DoubleML

> Double machine learning in Python: fit DoubleMLPLR with random forests, compare with naive OLS and OLS with linear controls, build the residual-on-residual estimator manually, and check sensitivity to the sample split.

Source: https://www.pythoncharts.com/causal-inference/double-machine-learning-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, double machine learning, doubleml, confounding, cross-fitting, random forest, observational data, scikit-learn

Double machine learning (DML) estimates the effect of a treatment on an outcome when many confounders could be influencing both, by using machine learning models to remove the confounders' influence and then regressing the leftover outcome on the leftover treatment. In Python, the `DoubleML` package does this with `DoubleMLPLR(data, ml_l, ml_m)` for a partially linear model, where `ml_l` predicts the outcome and `ml_m` predicts the treatment from the covariates. It needs `pip install doubleml`, and this post uses version 0.11.4 with scikit-learn 1.9.

## Quick Example

A store gives customers discounts of different depths (`d`). Customer traits `x0` to `x9` influence both who gets large discounts and how much they buy (`y`), in non-linear ways. The true effect of one more unit of discount on purchases is 0.5. The code compares three estimates: the raw regression, a regression with linear controls, and DoubleML with random forests.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
from doubleml import DoubleMLData, DoubleMLPLR
from sklearn.ensemble import RandomForestRegressor

rng = np.random.default_rng(15)

# Sample data: discount depth (d) and weekly purchases (y); customer traits confound both
n, p = 4000, 10
X = rng.normal(size=(n, p))
true_theta = 0.5
d = np.sin(X[:, 0]) + X[:, 1] ** 2 - 1 + rng.normal(size=n)
y = true_theta * d + 1.5 * np.cos(X[:, 0]) + 1.5 * X[:, 1] ** 2 + np.maximum(X[:, 2], 0) + rng.normal(size=n)
cols = [f"x{i}" for i in range(p)]
df = pd.DataFrame(X, columns=cols)
df["d"], df["y"] = d, y

# Baselines: naive OLS, OLS with linear controls
naive = sm.OLS(df.y, sm.add_constant(df[["d"]])).fit()
ols = sm.OLS(df.y, sm.add_constant(df[["d"] + cols])).fit()

# DoubleML (partially linear regression)
dml_data = DoubleMLData(df, y_col="y", d_cols="d", x_cols=cols)
learner = lambda: RandomForestRegressor(n_estimators=300, min_samples_leaf=3, n_jobs=-1, random_state=0)
np.random.seed(0)    # DoubleML draws its sample split from NumPy's global random state
dml = DoubleMLPLR(dml_data, ml_l=learner(), ml_m=learner(), n_folds=5)
dml.fit()
print(dml.summary)
```

```text
       coef   std err          t         P>|t|     2.5 %   97.5 %
d  0.523149  0.025899  20.199302  9.929157e-91  0.472387  0.57391
```

DoubleML estimates 0.523 with a 95% interval of 0.472 to 0.574, which contains the true 0.5. The other two are far off:

| Estimate | Effect of `d` | 95% CI |
|---|---|---|
| Naive OLS (`y ~ d`) | 1.402 | 1.370 to 1.434 |
| OLS with linear controls | 1.509 | 1.477 to 1.540 |
| DoubleML, random forests | 0.523 | 0.472 to 0.574 |

Adding the covariates linearly did not help (it made the estimate slightly worse), because the confounding runs through curved relationships (`sin(x0)`, `x1 ** 2`) that a linear control cannot remove.

![Estimates of the effect of d on y with 95 percent intervals. Naive OLS near 1.4 and OLS with linear controls near 1.5 are far to the right of the true effect line at 0.5. Manual DML and DoubleML both sit close to 0.52, with intervals covering 0.5](https://www.pythoncharts.com/causal-inference/double-machine-learning-python/images/dml-estimates.png)

## How Does Double Machine Learning Work?

For the partially linear model `y = theta * d + g(X) + noise`, where `theta` is the effect you want, DML:

1. Predicts `y` from `X` with a flexible model, giving `y_hat`.
2. Predicts `d` from `X` with a flexible model, giving `d_hat`.
3. Regresses the outcome residual `y - y_hat` on the treatment residual `d - d_hat`. The slope is `theta`.

The residual `d - d_hat` is the part of the treatment that the covariates cannot explain, which is as good as random if all confounders are in `X`. The "double" refers to the two prediction models. Two details make it valid:

- **Cross-fitting.** Each prediction is made by a model that did not train on that row (the `n_folds=5` argument). Without this, overfit forests would leak the row's own noise into its residual and bias the estimate.
- **Orthogonality.** The final estimate is insensitive to small errors in the two prediction models, so you can use flexible learners and still get a usable confidence interval.

## How Can I Build Double Machine Learning by Hand?

Writing out the three steps with `cross_val_predict` shows nothing is hidden inside the package:

```python
from sklearn.model_selection import KFold, cross_val_predict

kf = KFold(5, shuffle=True, random_state=0)
y_hat = cross_val_predict(learner(), df[cols], df.y, cv=kf)
d_hat = cross_val_predict(learner(), df[cols], df.d, cv=kf)
y_res, d_res = df.y - y_hat, df.d - d_hat
manual = sm.OLS(y_res, d_res).fit(cov_type="HC1")
print("manual theta", round(manual.params.iloc[0], 3), "se", round(manual.bse.iloc[0], 3))
```

This gives 0.523 with a standard error of 0.026, matching `DoubleMLPLR` here. The match is partly because both used the same five folds. Other splits would differ slightly, as the next section shows. The package adds the `n_rep` repetition, other score functions, tuning, and the other models (interactive regression for binary treatments, instrumental variables).

```python
fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
axes[0].scatter(df.d, df.y, s=6, alpha=0.3, color="#8a8f98")
b = np.polyfit(df.d, df.y, 1)
xs = np.linspace(df.d.min(), df.d.max(), 50)
axes[0].plot(xs, np.polyval(b, xs), color="#d1495b", lw=2, label=f"slope {b[0]:.2f}")
axes[0].set_xlabel("d (raw)")
axes[0].set_ylabel("y (raw)")
axes[0].set_title("Raw data: slope is inflated by confounding")
axes[0].legend(loc="upper left")
axes[1].scatter(d_res, y_res, s=6, alpha=0.3, color="#1b6ca8")
axes[1].plot(xs - xs.mean(), manual.params.iloc[0] * (xs - xs.mean()), color="#d1495b", lw=2,
             label=f"slope {manual.params.iloc[0]:.2f}")
axes[1].set_xlabel("d residual (d minus predicted d)")
axes[1].set_ylabel("y residual")
axes[1].set_title("After partialling out X: slope is close to 0.5")
axes[1].legend(loc="upper left")
fig.tight_layout()
```

![Two scatter plots. Left: raw outcome against raw treatment with a fitted slope of 1.40. Right: outcome residual against treatment residual with a fitted slope of 0.52, a round cloud centered at zero](https://www.pythoncharts.com/causal-inference/double-machine-learning-python/images/dml-partialling-out.png)

## Does the Random Sample Split Change the Answer?

Yes, a little, because cross-fitting depends on a random split. `DoubleMLPLR` can repeat the procedure (`n_rep`) and combine the estimates. To see how much the split matters, here are 20 fits with different splits and forests:

```python
ests = []
for seed in range(20):
    m = DoubleMLPLR(dml_data, ml_l=RandomForestRegressor(n_estimators=100, min_samples_leaf=3, n_jobs=-1, random_state=seed),
                    ml_m=RandomForestRegressor(n_estimators=100, min_samples_leaf=3, n_jobs=-1, random_state=seed), n_folds=5)
    np.random.seed(seed)
    m.draw_sample_splitting()
    m.fit()
    ests.append(float(m.coef[0]))
ests = np.array(ests)
print("mean", ests.mean().round(3), "sd", ests.std().round(3), "range", ests.min().round(3), ests.max().round(3))

fig, ax = plt.subplots(figsize=(8, 3.8))
ax.axvspan(*dml.confint().iloc[0].values, color="#cfd8e3", alpha=0.6, label="95% CI of the main fit")
ax.hist(ests, bins=12, color="#7a4ea3", edgecolor="white")
ax.set_xlim(0.44, 0.60)
ax.axvline(true_theta, color="#d1495b", ls="--", lw=2, label=f"True effect = {true_theta}")
ax.set_xlabel("DoubleML estimate with a different random sample split")
ax.set_ylabel("Runs")
ax.legend()
fig.tight_layout()
```

![Histogram of 20 DoubleML estimates with different sample splits, all between 0.516 and 0.532, well inside the shaded 95 percent confidence interval of the main fit, with a dashed line at the true value of 0.5](https://www.pythoncharts.com/causal-inference/double-machine-learning-python/images/dml-split-variation.png)

Across the 20 splits the estimates ranged from 0.516 to 0.532 (standard deviation 0.004), small next to the standard error of 0.026. So the split is a minor source of noise here, but with small samples or noisy learners it can matter, and setting `n_rep` (for example, `n_rep=10`) is cheap insurance. Notice also that all 20 land a little above 0.5: this is just sampling noise in the data, which no split can remove.

## Which Learners Should I Use?

Any scikit-learn regressor works as `ml_l` and `ml_m`. Practical guidance:

| Learner | Good for | Watch out for |
|---|---|---|
| Random forest | Non-linear confounding with little tuning (used above) | Slow with many folds and repetitions |
| Gradient boosting | Often more accurate, but sensitive to settings | Strong smoothing can bias the estimate |
| Lasso or elastic net | Many covariates with mostly linear effects | Misses curved confounding |

Check how well each nuisance model predicts with `dml.evaluate_learners()`. A learner that barely beats predicting the mean for `d` leaves little treatment variation after residualizing, which makes the estimate noisy. In a quick check on this same data, `HistGradientBoostingRegressor` (200 iterations, learning rate 0.05) gave 0.582 (interval 0.511 to 0.653) against 0.521 for the forest, so the choice of learner is something to check, not assume.

## When Does Double Machine Learning Not Work?

DML handles flexible relationships between the covariates and the outcome and treatment. It does **not** handle:

- **Unmeasured confounders.** If something that drives both treatment and outcome is not in `X`, the estimate is biased regardless of how good the learners are. `DoubleMLPLR` has `sensitivity_analysis()` for asking how strong such a confounder would need to be to change the conclusion.
- **Bad controls.** Do not include variables caused by the treatment (mediators) or by both treatment and outcome (colliders) in `X`.
- **No overlap.** If some customers essentially never or always get large discounts, the model extrapolates.

If you have a randomized experiment, analyze it directly (see [A/B test analysis](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/)). DML is for observational data, or for sharpening an experiment with many covariates, as [CUPED](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/) does with a single one. For a binary treatment, [propensity score matching](https://www.pythoncharts.com/causal-inference/propensity-score-matching-python/) is the classic alternative. If an instrument is available, [instrumental variables](https://www.pythoncharts.com/causal-inference/instrumental-variables-2sls-python/) handle unmeasured confounding that DML cannot. EconML is another Python package with DML estimators and heterogeneous-effect methods. I did not run it for this post.

## Practical Tips

- Include every plausible confounder in `X`, but not mediators or colliders.
- Use enough folds (5 is the default) and set `n_rep` for stability. Fix `np.random.seed` before drawing splits, since DoubleML reads NumPy's global state.
- Compare against a plain regression. A big difference tells you the confounding is non-linear, and no difference means you may not need DML.
- Report the confidence interval, not just the coefficient.
- The simulation here has a known effect and all confounders observed, which is the best case. Real data rarely is.

## Similar Topics

- [Propensity Score Matching in Python](https://www.pythoncharts.com/causal-inference/propensity-score-matching-python/)
- [Instrumental Variables in Python](https://www.pythoncharts.com/causal-inference/instrumental-variables-2sls-python/)
- [CUPED Variance Reduction in Python](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/)
- [Causal Inference in Python: A Guide](https://www.pythoncharts.com/causal-inference/causal-inference-python-guide/)
