> ## Documentation Index
> Fetch the complete documentation index at: https://docs.priorlabs.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> TabPFN-3 and later versions support up to 1,000,000 rows, subject to feature count and checkpoint/API limits.
> For large datasets, use per-estimator subsampling, e.g. inference_config={"SUBSAMPLE_SAMPLES": 100_000}, in TabPFNClassifier or TabPFNRegressor from tabpfn or tabpfn_client.
> Pass raw pandas DataFrames to fit and predict. Categorical strings/categories, raw text, and missing feature values are handled automatically; no manual integer/one-hot encoding, imputation, scaling, or outlier removal is needed.

# Causal Inference

> Estimate treatment effects, decide who to treat, and understand what treatment does with the help of TabPFN.

## Estimating treatment effects

In many domains, we are interested in predicting outcomes given different actions, often called *treatments*, in order to decide which one to apply. The difference between the outcome with a treatment and without one is the *causal effect*.
In a **randomized controlled trial (RCT)**, chance decides who gets the treatment (T=1) and who does not (T=0). The two groups then differ only by chance and by the treatment.

Let $X$ denote unit features, and $Y(1)$ and $Y(0)$ the outcome with and without treatment. We observe only one of them per unit (the "fundamental problem of causal inference").

* The **average treatment effect (ATE)** is $\tau\coloneqq\mathbb{E}[Y(1)-Y(0)]$.
* The **conditional average treatment effect (CATE)** is $\tau(x)\coloneqq\mathbb{E}[Y(1)-Y(0)|X=x]$.

We give an example of how TabPFN can be used to estimate the CATE within standard "Plugin-estimators" for causal inference. Such estimators build treatment effect estimates out of predictions. This allows leveraging TabPFN's predictive power for causal inference.

***

## Loading RCT data and estimating the ATE

We use data from the *LaLonde* experiment, a National Supported Work RCT that offered job training to 185 candidates, with 260 control candidates (Dehejia–Wahba 1999). The outcome is earnings in USD at follow-up. In an RCT, the difference in mean outcomes already estimates the ATE, without a model, so we can compute it as a first benchmark.

```python theme={null}
import pandas as pd
from scipy import stats

DATA_URL = "https://users.nber.org/~rdehejia/data/nsw_dw.dta"
# Covariates, all measured before treatment.
COVARIATES = ["age", "education", "black", "hispanic", "married", "nodegree", "re74", "re75"]
# One row per man: `treat` is 1 if he was offered training, `re78` is his 1978 earnings.
nsw = (pd.read_stata(DATA_URL).drop(columns="data_id").astype(float))

def difference_in_means(data):
    """Treated minus control mean of `re78`, with a 95% CI from Welch's t-test."""
    treated = data.loc[data["treat"] == 1, "re78"]
    control = data.loc[data["treat"] == 0, "re78"]
    t_test = stats.ttest_ind(treated, control, equal_var=False)
    ci = t_test.confidence_interval(confidence_level=0.95)
    return treated.mean() - control.mean(), ci.low, ci.high

difference, low, high = difference_in_means(nsw)
print(f"Difference in means: {difference:,.0f} (95% CI {low:,.0f} to {high:,.0f})")
```

```text theme={null}
Difference in means: 1,794 (95% CI 474 to 3,115)
```

We find a large positive and significant average treatment effect: candidates with job training earn more on average. This will serve as a sanity check for our more detailed effect estimates using TabPFN.

***

## CATE estimation using TabPFN

We fit one `TabPFNRegressor` for the treatment group, and one for the control group, and take their difference. The combined estimator is a *T-learner*: one model learns earnings with training, the other earnings without. `t_learner` returns the two fitted models, and the difference of their predictions is the predicted treatment effect for each observation.

> [!NOTE]
>
> Earnings are exactly zero for 35% of the control group and 24% of the treated group, hence we use `presets="zero_inflated"`, which requires `tabpfn` 10.2.0 or later.

```python theme={null}
from tabpfn import TabPFNRegressor

def t_learner(data):
    """Fit one TabPFN regressor per group: control (treat == 0) and treated (treat == 1)."""
    models = []
    for treat in (0, 1):
        group = data[data["treat"] == treat]
        model = TabPFNRegressor(presets="zero_inflated", random_state=0)
        models.append(model.fit(group[COVARIATES], group["re78"]))
    return models

model_control, model_treated = t_learner(nsw)
effects = model_treated.predict(nsw[COVARIATES]) - model_control.predict(nsw[COVARIATES])
print(f"Plug-in ATE: {effects.mean():,.0f}, SD of effects: {effects.std():,.0f}")
```

As a sanity check for our CATE estimator, we average the predicted effects to obtain an ATE for the plug-in estimator, and compare it to the difference in means between treatment and control group calculated above.

```text theme={null}
Plug-in ATE: 1,521, SD of effects: 987
```

We find that the plug-in ATE is close to the USD 1,794 found above, and well inside the confidence interval of the difference in means. With the sanity check completed, we move on to inspecting how treatment effects differ for different features.

### Comparing outcome distributions for different landmarks

To see how the effect differs between observations, compare the predicted earnings distributions with and without training for two observations: (i) no high-school degree and earnings of USD 1,000 in 1975, and (ii) with a degree and USD 5,000 earnings in 1975. TabPFN's ability to predict a distribution over outcomes allows us to contrast the distributions (here in the form of quantiles) for the two TabPFN predictors fitted as part of the T-learner.

> [accordion] Code for the landmarks
>
> ```python theme={null}
> # Two landmark men, with the same positive earnings in 1974 and 1975.
> landmarks = pd.DataFrame(
>     {
>         "age": [26, 26],
>         "education": [10, 12],
>         "black": [1, 1],
>         "hispanic": [0, 0],
>         "married": [0, 0],
>         "nodegree": [1, 0],
>         "re74": [1_000, 5_000],
>         "re75": [1_000, 5_000],
>     },
>     index=["No degree, USD 1,000 in 1975", "Degree, USD 5,000 in 1975"],
> )
> ```

```python theme={null}
import numpy as np

levels = list(np.linspace(0.005, 0.995, 199))
treatment = model_treated.predict(landmarks, output_type="quantiles", quantiles=levels)
control = model_control.predict(landmarks, output_type="quantiles", quantiles=levels)
```

> [accordion] Code for the plot
>
> ```python theme={null}
> import matplotlib.pyplot as plt
> import seaborn as sns
>
> mean_treatment = model_treated.predict(landmarks)  # predicted mean earnings per landmark
> mean_control = model_control.predict(landmarks)
> curves = [
>     ("With training", np.array(treatment), mean_treatment, "#101075"),
>     ("Without training", np.array(control), mean_control, "#b6698d"),
> ]
> fig, axes = plt.subplots(1, 2, figsize=(10, 3.5), sharex=True, sharey=True)
> for i, (ax, name) in enumerate(zip(axes, landmarks.index)):
>     for label, quantiles, mean, color in curves:
>         sns.kdeplot(quantiles[:, i], ax=ax, color=color, fill=True, alpha=0.3, clip=(0, None), label=label)
>         ax.axvline(mean[i], color=color, linestyle="--")
>     cate = mean_treatment[i] - mean_control[i]
>     ax.set(title=f"{name}\nCATE: USD {cate:,.0f}", xlabel="Predicted 1978 earnings (USD)")
>     ax.xaxis.set_major_formatter("{x:,.0f}")
>     ax.legend()
> plt.tight_layout()
> plt.show()
> ```

![Predicted 1978 earnings with and without training for two landmark men. The predicted effect is USD 834 for the man without a degree and USD 2,052 for the man with a degree.](https://mintcdn.com/priorlabs/9sb6GsaEp95Jrj-c/public/causal-inference-landmarks.png?fit=max\&auto=format\&n=9sb6GsaEp95Jrj-c\&q=85\&s=cdb69e59e69d82c9d4bc89d61651fe9d)

Training raises the predicted mean earnings by USD 834 for the man without a degree, and by USD 2,052 for the man with a degree. It also lowers the predicted chance of earning nothing in 1978, from 37% to 31% and from 35% to 21%. Only 4 men in the control group have a degree and earned between USD 3,000 and 7,000 in 1975, so the second landmark rests on little data.

## Summary

By fitting precise models for outcomes under treatment and control, TabPFN enables accurate treatment effect estimation as a function of the features. In addition, TabPFN's predictive distributions provide detailed insights into the properties of treatment effects. In combination, this allows developing policies on who to treat, and understanding what outcomes are likely following a treatment.

***

> [card] [Regression](https://docs.priorlabs.ai/capabilities/regression.md)
>
> Point predictions and guidance on other regression outputs.

> [card] [Classification](https://docs.priorlabs.ai/capabilities/classification.md)
>
> Binary and multi-class classification guide.

> [card] [Data Generation](https://docs.priorlabs.ai/capabilities/data-generation.md#causally-informed-generation-with-a-dag)
>
> Generate synthetic data that respects a causal DAG.

> [card] [TabPFN-4 changelog](https://docs.priorlabs.ai/changelog/tabpfn-4.md)
>
> Release notes and upgrade guidance for TabPFN-4.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.