---
title: "Frengression and Engression"
date: "2026-03-21"
---
In the [causal simulation chapter](causal-simulation.qmd), I used @evans-didelez-2024's decomposition of the joint distribution $p(x,a,y)$ into three pieces:
$$ p(x,a,y) = p(x,a) \cdot p_a(y) \cdot c(x,y|a) $$ {#eq-frengression-1}
where $p(x,a)$ is the "past" distribution of covariates and treatment, $p_a(y)$ is the causal margin, and $c(x,y|a)$ is the copula linking covariates and outcome given treatment. The `causl` package implements this with parametric families. We specify Gaussian, binomial, and so on for each piece.
But real data can be hard to specify parametrically. We may not know the right copula family. The marginal distributions may have mass points, skewness, or other features that are annoying to write down.
Frengression [@yang-2025] keeps the same decomposition but learns the pieces with neural networks.
There are two uses: causal simulation with a learned generative model, and interventional prediction using learned confounding structure. The second part uses engression, so I start there.
## Engression
Engression [@shen-meinshausen-2024-engression] stands for energy regression. Standard regression estimates $E[Y|X]$. Engression tries to learn the whole conditional distribution $P(Y|X)$ using neural networks trained with the energy score.
### The Energy Score
The energy score is a proper scoring rule for distributions. Given observations $Y$ and samples $\hat Y, \hat Y'$ from the model:
$$ S(Y, \hat Y, \hat Y') = E\|Y - \hat Y\| - \frac{1}{2}E\|\hat Y - \hat Y'\| $$ {#eq-frengression-2}
The first term rewards samples close to the truth. The second term keeps the simulated distribution from collapsing to one point. This is why the method targets the full distribution rather than only the mean.
### The Stochastic Network (StoNet)
The building block is a `StoNet`, a neural network that adds random noise $\epsilon \sim N(0,I)$ to the input at each layer:
$$\text{StoNet}(x) = f(x, \epsilon), \quad \epsilon \sim N(0,I)$$ {#eq-frengression-3}
Different noise draws produce different outputs. Each output is a sample from the learned conditional distribution. So we can:
- **Predict the mean**: average over many noise draws → $E[Y|X=x]$
- **Predict quantiles**: take quantiles of the noise draws → conditional quantile regression
- **Sample**: each forward pass with fresh noise is a sample from $P(Y|X=x)$
### Why Engression?
Compared with quantile regression or mixture density networks, engression is useful because:
1. it handles multivariate responses directly;
2. it does not require us to specify a Gaussian mixture or a list of quantiles;
3. it gives samples from the conditional distribution, which is convenient for simulation.
### Quick Example
The `engression` R package, separate from `Rfrengression`, provides the
standalone estimator. The code below shows the API. The `Rfrengression`
examples later are the ones I actually run here.
```{r}
#| label: engression_example
#| warning: false
#| cache: true
#| message: false
#| eval: false
library(engression)
# Nonlinear DGP with heteroskedastic noise
n <- 1000
X <- matrix(rnorm(n * 2), ncol = 2)
Y <- (X[,1])^2 + X[,2] + rnorm(n) * (0.5 + abs(X[,1]))
# Fit engression; it learns the full conditional distribution
engr <- engression(X, Y)
# Predict conditional mean (like lm, but nonlinear)
Yhat_mean <- predict(engr, X, type = "mean")
# Predict conditional quantiles (like quantile regression, but joint)
Yhat_quant <- predict(engr, X, type = "quantiles")
# Sample from the learned distribution (generative)
Ysample <- predict(engr, X, type = "sample", nsample = 1)
```
The point is that engression gives a distributional model of $Y|X$, not just a fitted mean.
## From Engression to Frengression
Frengression is frugal simulation plus engression. It uses three engression models to represent the decomposition of $P(X,A,Y)$. Each sub-network is trained with the energy score.
## The Architecture
Frengression has three sub-networks, matching the three pieces of the decomposition:
| Decomposition | causl (parametric) | Frengression (neural net) |
|---|---|---|
| $P(X,A)$ — the past | Specified by family + params | `model_xz`: noise-only generator |
| $P_a(Y)$ — causal margin | Specified by family + params | `model_y`: takes $(x, \text{eta})$, outputs $y$ |
| $c(X,Y \mid A)$ — copula | Gaussian/Frank/etc. copula | `model_eta`: takes $(x,z)$, outputs eta |
The important part is `model_eta`. It takes $(x,z)$ and outputs a latent variable `eta` that carries the dependence between confounders and outcome. During training, a Z-permutation trick forces `eta` to be marginally $N(0,I)$. This means:
- When `eta` comes from `model_eta(x,z)`, it carries the observational confounding information.
- When `eta` is sampled independently from $N(0,1)$, it gives the interventional prediction.
Same network, different source of `eta`. That is the trick.
## Using Rfrengression
The `Rfrengression` package is a native R implementation using `torch`.
```{r}
#| label: setup
#| warning: false
#| cache: false
#| message: false
library(Rfrengression)
```
### Example: Binary Treatment DGP
Use a DGP with binary treatment, binary outcome, and four confounders. We draw
$n = 2000$ observations with $w_1, w_2 \sim \text{Bernoulli}(0.5)$,
$w_3 \sim U(0,4)$ and $w_4 \sim U(0,5)$; treatment is
$A \sim \text{Bernoulli}(\Lambda(-0.4 + 0.2w_2 + 0.15w_3 + 0.2w_4 + 0.15w_2w_4))$;
and both potential outcomes are Bernoulli with the same logit index shifted by
the treatment. Since both are simulated, the realized ATE is known:
```{r}
#| label: dgp
#| warning: false
#| cache: false
#| message: false
set.seed(42)
n <- 2000
w1 <- rbinom(n, 1, 0.5)
w2 <- rbinom(n, 1, 0.5)
w3 <- round(runif(n, 0, 4), 3)
w4 <- round(runif(n, 0, 5), 3)
A <- rbinom(n, 1, plogis(-0.4 + 0.2*w2 + 0.15*w3 + 0.2*w4 + 0.15*w2*w4))
lin <- -1 - 0.1*w1 + 0.3*w2 + 0.25*w3 + 0.2*w4 + 0.15*w2*w4
p1 <- plogis(lin + 1)
p0 <- plogis(lin)
Y.1 <- rbinom(n, 1, p1)
Y.0 <- rbinom(n, 1, p0)
Y <- Y.1 * A + Y.0 * (1 - A)
# Two benchmarks, and they are not the same quantity. The first is the realized
# finite-sample ATE in this particular draw of the Bernoulli outcomes; the second
# averages the true individual probabilities over the sampled covariates, so it
# carries no outcome sampling noise.
true_ate <- mean(Y.1 - Y.0)
bench_ate <- mean(p1 - p0)
cat("Realized ATE (this draw):", round(true_ate, 4), "\n")
cat("Covariate-averaged ATE: ", round(bench_ate, 4), "\n")
```
### Train Frengression
Training has two stages: first the outcome model (`model_y` + `model_eta`), then the marginal model (`model_xz`).
```{r}
#| label: train
#| warning: false
#| cache: false
#| message: false
# torch keeps its own generator; R's set.seed() does not reach it.
torch::torch_manual_seed(1)
x_mat <- matrix(A, ncol = 1)
z_mat <- as.matrix(data.frame(w1, w2, w3, w4))
y_mat <- matrix(Y, ncol = 1)
model <- frengression(x_dim = 1, y_dim = 1, z_dim = 4,
x_binary = TRUE, y_binary = TRUE,
z_binary_dims = 2, noise_dim = 10)
# tol = 0 turns off train_y's default early stopping (tol = 0.01), which
# otherwise halts as soon as the two energy-loss terms move by less than 0.01
# between iterations -- after 67 iterations in this draw.
model <- train_y(model, x_mat, z_mat, y_mat,
num_iters = 1000, lr = 1e-3, print_every = 500, tol = 0)
model <- train_xz(model, x_mat, z_mat,
num_iters = 1000, lr = 1e-4, print_every = 500)
```
### Estimate ATE
For interventional prediction, `eta` is sampled from $N(0,1)$ instead of being generated from the observed confounding structure:
```{r}
#| label: ate
#| warning: false
#| cache: false
#| message: false
torch::torch_manual_seed(1)
y1 <- predict(model, matrix(1, ncol = 1), type = "mean", nsample = 2000, trim = 0)
y0 <- predict(model, matrix(0, ncol = 1), type = "mean", nsample = 2000, trim = 0)
cat("Frengression ATE:", round(y1 - y0, 4), "\n")
cat("True ATE:", round(true_ate, 4), "\n")
```
The realized ATE in this draw is $0.1935$, and averaging the true probabilities over the sampled covariates gives $0.2024$. The gap between those two is outcome sampling noise, not model error, and it is worth keeping them apart: the realized figure is the ATE of the potential outcomes actually drawn, while the covariate-averaged figure is the smoother target the estimator is really chasing. With early stopping turned off, frengression's 0.1895 lands 0.004 below the realized ATE and 0.013 below the covariate-averaged one.
The training chunks carry `cache: false`, so they re-run on every render, and
torch keeps a generator of its own that R's `set.seed()` does not reach. Seeding
it with `torch_manual_seed()` fixes the weight initialisation, the training
draws, and the sampling inside `predict()`, so the figure above is reproducible
from one render to the next. On a CUDA device some nondeterminism can survive
the seed, from cuDNN algorithm selection and atomic accumulation in the backward
pass.
## Frengression as DGP
Frengression can estimate an ATE, but that is not its main advantage. If I only want an ATE, I would usually use `npcausal`, TMLE, or DoubleML. The more interesting use is to train a data-generating process for benchmarking.
The idea is:
1. Train frengression on observational data, so it learns the confounding structure.
2. Replace the causal margin with a known function via `specify_causal()`.
3. Generate synthetic data with realistic confounding and known ground truth.
```{r}
#| label: dgp_bench
#| warning: false
#| cache: false
#| message: false
# Specify a known causal effect: Y = sigmoid(0.2*X + eta)
model_bench <- specify_causal(model, function(x, eta) {
torch::torch_sigmoid(0.2 * x + eta)
})
# Y is binary: Y = 1{sigmoid(0.2*x + eta) > 0.5} = 1{0.2*x + eta > 0}, eta ~ N(0,1),
# so P(Y = 1 | do(x)) = pnorm(0.2 * x) and the true ATE is pnorm(0.2) - 0.5.
true_ate_spec <- pnorm(0.2) - 0.5
y1_true <- predict(model_bench, matrix(1, ncol = 1), type = "mean", nsample = 5000, trim = 0)
y0_true <- predict(model_bench, matrix(0, ncol = 1), type = "mean", nsample = 5000, trim = 0)
cat("True ATE (specified, exact):", round(true_ate_spec, 4), "\n")
cat("Monte Carlo check from predict():", round(as.numeric(y1_true - y0_true), 4), "\n")
# The generator draws eta from the learned model_eta, whose marginal is trained
# toward N(0,1). The ATE in the generated population is P(eta > -0.2) - P(eta > 0)
# under that learned marginal; check it on a large draw.
eta_gen <- torch::with_no_grad({
xz <- model_bench$model_xz$forward(n = 100000)
x_g <- (xz[, 1, drop = FALSE] > 0)$to(dtype = torch::torch_float())
z_g <- xz[, 2:(1 + model_bench$z_dim), drop = FALSE]
zb <- model_bench$z_binary_dims
if (zb > 0) z_g[, 1:zb] <- (z_g[, 1:zb] > 0)$to(dtype = torch::torch_float())
as.numeric(as.array(model_bench$model_eta$forward(torch::torch_cat(list(x_g, z_g), dim = 2))))
})
cat(sprintf("Generator eta: mean %.3f, sd %.3f; implied ATE %.4f\n",
mean(eta_gen), sd(eta_gen), mean(eta_gen > -0.2) - mean(eta_gen > 0)))
```
The specified margin has an exact ATE of $\Phi(0.2) - 0.5 = 0.0793$, where $\Phi$ is
the standard normal distribution function, and `predict()` with `trim = 0`
reproduces it to Monte Carlo error. The population the generator actually draws
uses the learned $\eta$, whose mean is 0.044 and standard deviation 0.946 rather
than 0 and 1, and its ATE is 0.0785. We score the benchmark against the exact
0.0793. The 0.0008 gap is the generator's approximation error, small next to the
biases below.
Now we can generate synthetic data and benchmark any method:
```{r}
#| label: syn
#| warning: false
#| cache: false
#| message: false
syn <- sample_joint(model_bench, sample_size = 1000)
cat("Synthetic data: n =", nrow(syn$x), "\n")
cat("Treatment prevalence:", mean(syn$x), "\n")
cat("Outcome prevalence:", mean(syn$y), "\n")
```
## Real Data: LaLonde
This is most useful with real data. The LaLonde job-training data have many of the problems that make simulations hard to write by hand: zeros in prior earnings, uneven covariate distributions, and poor overlap.
```{r}
#| label: lalonde
#| warning: false
#| cache: false
#| message: false
library(MatchIt)
data("lalonde", package = "MatchIt")
lalonde$black <- as.integer(lalonde$race == "black")
lalonde$hispan <- as.integer(lalonde$race == "hispan")
x_lal <- matrix(lalonde$treat, ncol = 1)
y_lal <- matrix(lalonde$re78, ncol = 1)
# frengression's z_binary_dims assumes the FIRST z_binary_dims columns of z
# are the binary ones -- so the binary covariates (black, hispan, married,
# nodegree) must come first, followed by the continuous ones (age, educ,
# re74, re75). The original column order (age, educ first) put two
# continuous variables where binary ones were expected, and vice versa.
z_lal <- as.matrix(lalonde[, c("black", "hispan", "married", "nodegree",
"age", "educ", "re74", "re75")])
# Standardize for training
# Standardize only the continuous columns; the first four must stay 0/1.
z_sc <- z_lal
z_sc[, 5:8] <- scale(z_lal[, 5:8])
y_sc <- (y_lal - mean(y_lal)) / sd(y_lal)
model_lal <- frengression(x_dim = 1, y_dim = 1, z_dim = 8,
x_binary = TRUE, y_binary = FALSE,
z_binary_dims = 4, noise_dim = 10)
model_lal <- train_y(model_lal, x_lal, z_sc, y_sc,
num_iters = 1000, lr = 1e-3, print_every = 500)
model_lal <- train_xz(model_lal, x_lal, z_sc,
num_iters = 1000, lr = 1e-4, print_every = 500)
```
Now specify a known effect and generate data:
```{r}
#| label: lalonde_gen
#| warning: false
#| cache: false
#| message: false
model_lal_bench <- specify_causal(model_lal, function(x, eta) {
0.3 * x + eta
})
# Generate synthetic LaLonde-like data with known ATE = 0.3 (standardized)
syn_lal <- sample_joint(model_lal_bench, sample_size = 2000)
cat("Synthetic LaLonde: n =", nrow(syn_lal$x), "\n")
cat("Treatment prevalence:", round(mean(syn_lal$x), 3), "\n")
cat("True ATE:", 0.3, "(standardized) =", round(0.3 * sd(y_lal), 0), "dollars\n")
```
The synthetic data inherits LaLonde's confounding structure, but now the true effect is known. This is the part that is hard to do with a hand-written DGP.
## Comparison: causl vs frengression
Both packages use the same decomposition:
| Feature | causl | Frengression |
|---|---|---|
| Marginal $P(X,A)$ | Parametric families | Learned by neural net |
| Causal margin $P_a(Y)$ | Parametric families | Learned (or specified) |
| Copula | Gaussian, Frank, etc. | Learned by `model_eta` |
| Requires specification | Yes — families + params | No — learns from data |
| Can learn from real data | Limited (plasmode) | Yes — full joint |
| Distributional flexibility | Limited by family choice | Arbitrary |
The `causl` approach is more transparent because we know exactly what we specified. Frengression is more flexible because it can learn structure we did not write down. I would treat them as complements. Frengression is not the first neural generator for benchmarking: RealCause [@neal-huang-raghupathi-2020] fits flexible generative models to real data and then sets the treatment effect, to build benchmarks with known ground truth that look like real data. What the frugal parameterization adds is that the causal margin is specified directly and separately from the confounding, so the true effect is exact by construction.
## Benchmarking: Frengression vs Semiparametric Methods
Now compare frengression against standard semiparametric causal inference tools on the same data. The three comparison methods are:
- `npcausal`: AIPW estimator with SuperLearner nuisance models
- `tmle`: targeted minimum loss-based estimation with SuperLearner
- `DoubleML`: the interactive regression model (`DoubleMLIRM`) with `ranger`, the doubly robust ATE estimator for a binary treatment
These methods are built for ATE estimation. They should usually be better for this specific estimand. The comparison is still useful because frengression is trying to learn much more than the ATE.
```{r}
#| label: bench_libs
#| warning: false
#| cache: true
#| message: false
library(npcausal)
library(tmle)
library(SuperLearner)
library(DoubleML)
library(mlr3)
library(mlr3learners)
library(tidyverse)
library(knitr)
```
### Single-Dataset Comparison
First, run all four methods on the binary DGP data created above.
```{r}
#| label: npcausal_ate
#| warning: false
#| cache: true
#| message: false
W <- data.frame(w1, w2, w3, w4)
SL.library <- c("SL.earth", "SL.glm.interaction", "SL.mean",
"SL.ranger", "SL.glmnet")
set.seed(123)
aipw_fit <- ate(y = Y, a = A, x = W, nsplits = 2, sl.lib = SL.library)
ate_npcausal <- aipw_fit$res$est[3]
se_npcausal <- aipw_fit$res$se[3]
ci_npcausal <- c(aipw_fit$res$ci.ll[3], aipw_fit$res$ci.ul[3])
cat("npcausal ATE:", round(ate_npcausal, 4), "\n")
cat("SE:", round(se_npcausal, 4), "\n")
```
```{r}
#| label: tmle_ate
#| warning: false
#| cache: true
#| message: false
set.seed(123)
tmle_fit <- tmle(Y = Y, A = A, W = W, family = "binomial",
Q.SL.library = SL.library, g.SL.library = SL.library)
ate_tmle <- tmle_fit$estimates$ATE$psi
se_tmle <- sqrt(tmle_fit$estimates$ATE$var.psi)
ci_tmle <- tmle_fit$estimates$ATE$CI
cat("TMLE ATE:", round(ate_tmle, 4), "\n")
cat("SE:", round(se_tmle, 4), "\n")
```
```{r}
#| label: doubleml_ate
#| warning: false
#| cache: true
#| message: false
lgr::get_logger("mlr3")$set_threshold("warn")
data_obs <- data.frame(w1, w2, w3, w4, A, Y)
dml_data <- DoubleMLData$new(data_obs,
y_col = "Y", d_cols = "A",
x_cols = c("w1", "w2", "w3", "w4"))
# Binary treatment with heterogeneous effects: the interactive regression model
# (IRM) targets the ATE; the partially linear model would target a
# variance-weighted average of the effects instead.
learner_g <- lrn("regr.ranger", num.trees = 500, max.depth = 5, min.node.size = 2)
learner_m <- lrn("classif.ranger", num.trees = 500, max.depth = 5, min.node.size = 2,
predict_type = "prob")
set.seed(123)
dml_plr <- DoubleMLIRM$new(dml_data, ml_g = learner_g, ml_m = learner_m)
dml_plr$fit()
ate_dml <- dml_plr$coef
se_dml <- dml_plr$se
ci_dml <- c(dml_plr$confint()[1], dml_plr$confint()[2])
cat("DoubleML ATE:", round(ate_dml, 4), "\n")
cat("SE:", round(se_dml, 4), "\n")
```
```{r}
#| label: frengression_se
#| warning: false
#| cache: false
#| message: false
# Frengression ATE already computed above (y1 - y0)
ate_freng <- as.numeric(y1 - y0)
# Repeated prediction from the one fitted network. This measures Monte Carlo
# integration error in predict(), not sampling or training uncertainty: the data
# are not resampled and the network is not refitted. It is not a standard error.
set.seed(123)
ate_mc_draws <- replicate(200, {
predict(model, matrix(1, ncol = 1), type = "mean", nsample = 500, trim = 0) -
predict(model, matrix(0, ncol = 1), type = "mean", nsample = 500, trim = 0)
})
mc_error_freng <- sd(ate_mc_draws)
cat("Monte Carlo integration error of the frengression ATE:", round(mc_error_freng, 4), "\n")
```
```{r}
#| label: comparison_table
#| warning: false
#| cache: true
#| message: false
results <- data.frame(
Method = c("True ATE", "Frengression", "npcausal (AIPW)", "TMLE", "DoubleML (IRM)"),
ATE = c(true_ate, ate_freng, ate_npcausal, ate_tmle, ate_dml),
SE = c(NA, NA, se_npcausal, se_tmle, se_dml), # no SE for frengression
CI_lower = c(NA, NA, ci_npcausal[1], ci_tmle[1], ci_dml[1]),
CI_upper = c(NA, NA, ci_npcausal[2], ci_tmle[2], ci_dml[2])
)
results$Bias <- results$ATE - true_ate
results$Covers <- ifelse(is.na(results$CI_lower), NA,
results$CI_lower <= true_ate & true_ate <= results$CI_upper)
kable(results, digits = 4,
caption = "ATE Estimation: Frengression vs Semiparametric Methods")
```
On this single dataset all four are close. TMLE gives 0.1916 and npcausal
0.1911, within 0.003 of the true 0.1935; DoubleML's interactive model gives
0.1806, 0.013 below; frengression gives 0.1895, 0.004 below. We report no
standard error for frengression. The spread of repeated predictions from the one
fitted network, 0.0278, measures only the Monte Carlo error of the integration in
`predict()`: it does not resample the data or refit the network. The three
reported intervals all cover the truth.
The semiparametric estimators target the ATE directly. Frengression learns the joint distribution and then computes the ATE as one functional of that distribution. So I would not expect it to be the most precise ATE estimator in this table.
### Monte Carlo Benchmarking (Simulated DGP)
This is where frengression is more useful. Use the model trained above, plug in a known causal effect with `specify_causal()`, generate 10 synthetic datasets, and benchmark all four estimators.
```{r}
#| label: benchmark_sim
#| warning: false
#| cache: false
#| message: false
B <- 10
n_syn <- 2000
methods <- c("Frengression", "npcausal", "TMLE", "DoubleML")
ate_mat <- matrix(NA, nrow = B, ncol = length(methods),
dimnames = list(NULL, methods))
se_mat <- ate_mat
cover_mat <- ate_mat
SL.lib_fast <- c("SL.glm.interaction", "SL.ranger", "SL.mean")
# True ATE of the specified causal margin (exact, derived above)
true_ate_bench <- true_ate_spec
set.seed(2024)
for (b in seq_len(B)) {
syn <- sample_joint(model_bench, sample_size = n_syn)
x_syn <- as.numeric(syn$x)
y_syn <- as.numeric(syn$y)
z_syn <- as.data.frame(syn$z)
colnames(z_syn) <- paste0("z", 1:ncol(z_syn))
df_syn <- cbind(data.frame(A = x_syn, Y = y_syn), z_syn)
# --- Frengression ---
tryCatch({
torch::torch_manual_seed(1000 + b) # torch's own generator; set.seed() does not reach it
mod_f <- frengression(x_dim = 1, y_dim = 1, z_dim = ncol(z_syn),
x_binary = TRUE, y_binary = TRUE,
z_binary_dims = model_bench$z_binary_dims,
noise_dim = 10, hidden_dim = 100, num_layer = 3)
mod_f <- train_y(mod_f, matrix(x_syn, ncol=1), as.matrix(z_syn),
matrix(y_syn, ncol=1),
num_iters = 500, lr = 1e-3, silent = TRUE)
mod_f <- train_xz(mod_f, matrix(x_syn, ncol=1), as.matrix(z_syn),
num_iters = 500, lr = 1e-4, silent = TRUE)
y1_f <- predict(mod_f, matrix(1, ncol=1), type="mean", nsample=1000, trim=0)
y0_f <- predict(mod_f, matrix(0, ncol=1), type="mean", nsample=1000, trim=0)
ate_mat[b, "Frengression"] <- y1_f - y0_f
# No standard error or interval for frengression: SE and coverage stay NA.
}, error = function(e) message("Frengression failed on rep ", b, ": ", e$message))
# --- npcausal ---
tryCatch({
fit_np <- ate(y = y_syn, a = x_syn, x = z_syn,
nsplits = 2, sl.lib = SL.lib_fast)
ate_mat[b, "npcausal"] <- fit_np$res$est[3]
se_mat[b, "npcausal"] <- fit_np$res$se[3]
ci <- c(fit_np$res$ci.ll[3], fit_np$res$ci.ul[3])
cover_mat[b, "npcausal"] <- (ci[1] <= true_ate_bench & true_ate_bench <= ci[2])
}, error = function(e) message("npcausal failed on rep ", b, ": ", e$message))
# --- TMLE ---
tryCatch({
fit_tmle <- tmle(Y = y_syn, A = x_syn, W = z_syn, family = "binomial",
Q.SL.library = SL.lib_fast, g.SL.library = SL.lib_fast)
ate_mat[b, "TMLE"] <- fit_tmle$estimates$ATE$psi
se_mat[b, "TMLE"] <- sqrt(fit_tmle$estimates$ATE$var.psi)
ci_t <- fit_tmle$estimates$ATE$CI
cover_mat[b, "TMLE"] <- (ci_t[1] <= true_ate_bench & true_ate_bench <= ci_t[2])
}, error = function(e) message("TMLE failed on rep ", b, ": ", e$message))
# --- DoubleML ---
tryCatch({
dml_d <- DoubleMLData$new(df_syn, y_col = "Y", d_cols = "A",
x_cols = colnames(z_syn))
lr_g <- lrn("regr.ranger", num.trees = 300, max.depth = 5, min.node.size = 2)
lr_m <- lrn("classif.ranger", num.trees = 300, max.depth = 5, min.node.size = 2,
predict_type = "prob")
dml_obj <- DoubleMLIRM$new(dml_d, ml_g = lr_g, ml_m = lr_m)
dml_obj$fit()
ate_mat[b, "DoubleML"] <- dml_obj$coef
se_mat[b, "DoubleML"] <- dml_obj$se
ci_d <- c(dml_obj$confint()[1], dml_obj$confint()[2])
cover_mat[b, "DoubleML"] <- (ci_d[1] <= true_ate_bench & true_ate_bench <= ci_d[2])
}, error = function(e) message("DoubleML failed on rep ", b, ": ", e$message))
if (b %% 5 == 0) cat("Completed replication", b, "of", B, "\n")
}
```
```{r}
#| label: benchmark_results
#| warning: false
#| cache: true
#| message: false
bench_summary <- data.frame(
Method = colnames(ate_mat),
Mean_ATE = colMeans(ate_mat, na.rm = TRUE),
Bias = colMeans(ate_mat, na.rm = TRUE) - true_ate_bench,
SD = apply(ate_mat, 2, sd, na.rm = TRUE),
RMSE = sqrt(colMeans((ate_mat - true_ate_bench)^2, na.rm = TRUE)),
Mean_SE = colMeans(se_mat, na.rm = TRUE),
Coverage_95 = colMeans(cover_mat, na.rm = TRUE),
N_valid = colSums(!is.na(ate_mat))
)
bench_summary[, c("Mean_SE", "Coverage_95")][is.na(bench_summary[, c("Mean_SE", "Coverage_95")])] <- NA # no SE for frengression
kable(bench_summary, digits = 4,
caption = paste0("Monte Carlo Benchmarking (B=", B,
", n=", n_syn, ", True ATE=",
round(true_ate_bench, 4), ")"))
```
```{r}
#| label: benchmark_plot
#| warning: false
#| cache: true
#| message: false
#| fig-cap: "ATE Estimates Across Synthetic Datasets"
ate_long <- as.data.frame(ate_mat) |>
pivot_longer(everything(), names_to = "Method", values_to = "ATE") |>
filter(!is.na(ATE))
# Trim extreme outliers for readable plot
q_bounds <- quantile(ate_long$ATE, c(0.02, 0.98), na.rm = TRUE)
ate_long_trim <- ate_long |> filter(ATE >= q_bounds[1] & ATE <= q_bounds[2])
ggplot(ate_long_trim, aes(x = Method, y = ATE, fill = Method)) +
geom_boxplot(alpha = 0.7) +
geom_hline(yintercept = true_ate_bench, linetype = "dashed", color = "red",
linewidth = 1) +
annotate("text", x = 0.5, y = true_ate_bench, label = "True ATE",
hjust = 0, vjust = -0.5, color = "red") +
labs(title = "ATE Estimates Across Frengression-Generated Datasets",
subtitle = paste0("B=", B, " replications, n=", n_syn, " per dataset"),
y = "Estimated ATE") +
theme_minimal() +
theme(legend.position = "none")
```
### Monte Carlo Benchmarking (LaLonde)
Now do the same exercise with the LaLonde-trained model. Here the confounding structure comes from the real data rather than from my hand-written simulation.
```{r}
#| label: lalonde_bench
#| warning: false
#| cache: false
#| message: false
# Y = 0.3*x + eta, so Y(1) - Y(0) = 0.3 for every unit: the true ATE is exactly 0.3.
true_ate_lal <- 0.3
y1_lal_true <- predict(model_lal_bench, matrix(1, ncol=1), type="mean", nsample=5000, trim=0)
y0_lal_true <- predict(model_lal_bench, matrix(0, ncol=1), type="mean", nsample=5000, trim=0)
cat("Monte Carlo check from predict():", round(as.numeric(y1_lal_true - y0_lal_true), 4), "\n")
cat("True ATE (standardized):", round(true_ate_lal, 4), "\n")
cat("True ATE (dollars):", round(true_ate_lal * sd(y_lal), 0), "\n")
B_lal <- 10
n_syn_lal <- 2000
methods <- c("Frengression", "npcausal", "TMLE", "DoubleML")
ate_mat_lal <- matrix(NA, nrow = B_lal, ncol = length(methods),
dimnames = list(NULL, methods))
se_mat_lal <- ate_mat_lal
cover_mat_lal <- ate_mat_lal
SL.lib_fast <- c("SL.glm.interaction", "SL.ranger", "SL.mean")
set.seed(2024)
for (b in seq_len(B_lal)) {
syn <- sample_joint(model_lal_bench, sample_size = n_syn_lal)
x_syn <- as.numeric(syn$x)
y_syn <- as.numeric(syn$y)
z_syn <- as.data.frame(syn$z)
colnames(z_syn) <- paste0("z", 1:ncol(z_syn))
df_syn <- cbind(data.frame(A = x_syn, Y = y_syn), z_syn)
# --- Frengression ---
tryCatch({
torch::torch_manual_seed(2000 + b)
mod_f <- frengression(x_dim = 1, y_dim = 1, z_dim = ncol(z_syn),
x_binary = TRUE, y_binary = FALSE,
z_binary_dims = 4,
noise_dim = 10, hidden_dim = 100, num_layer = 3)
mod_f <- train_y(mod_f, matrix(x_syn, ncol=1), as.matrix(z_syn),
matrix(y_syn, ncol=1),
num_iters = 500, lr = 1e-3, silent = TRUE)
mod_f <- train_xz(mod_f, matrix(x_syn, ncol=1), as.matrix(z_syn),
num_iters = 500, lr = 1e-4, silent = TRUE)
y1_f <- predict(mod_f, matrix(1, ncol=1), type="mean", nsample=1000, trim=0)
y0_f <- predict(mod_f, matrix(0, ncol=1), type="mean", nsample=1000, trim=0)
ate_mat_lal[b, "Frengression"] <- y1_f - y0_f
# No standard error or interval for frengression: SE and coverage stay NA.
}, error = function(e) message("Frengression failed on rep ", b, ": ", e$message))
# --- npcausal ---
tryCatch({
fit_np <- ate(y = y_syn, a = x_syn, x = z_syn,
nsplits = 2, sl.lib = SL.lib_fast)
ate_mat_lal[b, "npcausal"] <- fit_np$res$est[3]
se_mat_lal[b, "npcausal"] <- fit_np$res$se[3]
ci <- c(fit_np$res$ci.ll[3], fit_np$res$ci.ul[3])
cover_mat_lal[b, "npcausal"] <- (ci[1] <= true_ate_lal & true_ate_lal <= ci[2])
}, error = function(e) message("npcausal failed on rep ", b, ": ", e$message))
# --- TMLE ---
tryCatch({
fit_tmle <- tmle(Y = y_syn, A = x_syn, W = z_syn, family = "gaussian",
Q.SL.library = SL.lib_fast, g.SL.library = SL.lib_fast)
ate_mat_lal[b, "TMLE"] <- fit_tmle$estimates$ATE$psi
se_mat_lal[b, "TMLE"] <- sqrt(fit_tmle$estimates$ATE$var.psi)
ci_t <- fit_tmle$estimates$ATE$CI
cover_mat_lal[b, "TMLE"] <- (ci_t[1] <= true_ate_lal & true_ate_lal <= ci_t[2])
}, error = function(e) message("TMLE failed on rep ", b, ": ", e$message))
# --- DoubleML ---
tryCatch({
dml_d <- DoubleMLData$new(df_syn, y_col = "Y", d_cols = "A",
x_cols = colnames(z_syn))
lr_g <- lrn("regr.ranger", num.trees = 300, max.depth = 5, min.node.size = 2)
lr_m <- lrn("classif.ranger", num.trees = 300, max.depth = 5, min.node.size = 2,
predict_type = "prob")
dml_obj <- DoubleMLIRM$new(dml_d, ml_g = lr_g, ml_m = lr_m)
dml_obj$fit()
ate_mat_lal[b, "DoubleML"] <- dml_obj$coef
se_mat_lal[b, "DoubleML"] <- dml_obj$se
ci_d <- c(dml_obj$confint()[1], dml_obj$confint()[2])
cover_mat_lal[b, "DoubleML"] <- (ci_d[1] <= true_ate_lal & true_ate_lal <= ci_d[2])
}, error = function(e) message("DoubleML failed on rep ", b, ": ", e$message))
if (b %% 5 == 0) cat("Completed replication", b, "of", B_lal, "\n")
}
```
```{r}
#| label: lalonde_results
#| warning: false
#| cache: true
#| message: false
bench_lal <- data.frame(
Method = colnames(ate_mat_lal),
Mean_ATE = colMeans(ate_mat_lal, na.rm = TRUE),
Bias = colMeans(ate_mat_lal, na.rm = TRUE) - true_ate_lal,
SD = apply(ate_mat_lal, 2, sd, na.rm = TRUE),
RMSE = sqrt(colMeans((ate_mat_lal - true_ate_lal)^2, na.rm = TRUE)),
Mean_SE = colMeans(se_mat_lal, na.rm = TRUE),
Coverage_95 = colMeans(cover_mat_lal, na.rm = TRUE),
N_valid = colSums(!is.na(ate_mat_lal))
)
bench_lal[, c("Mean_SE", "Coverage_95")][is.na(bench_lal[, c("Mean_SE", "Coverage_95")])] <- NA # no SE for frengression
kable(bench_lal, digits = 4,
caption = paste0("LaLonde-Based Benchmarking (B=", B_lal,
", n=", n_syn_lal,
", True ATE=", round(true_ate_lal, 4),
" [", round(true_ate_lal * sd(y_lal), 0), " dollars])"))
```
```{r}
#| label: lalonde_plot
#| warning: false
#| cache: true
#| message: false
#| fig-cap: "ATE Estimates from LaLonde-Based Synthetic Data"
ate_long_lal <- as.data.frame(ate_mat_lal) |>
pivot_longer(everything(), names_to = "Method", values_to = "ATE") |>
filter(!is.na(ATE))
q_bounds_lal <- quantile(ate_long_lal$ATE, c(0.02, 0.98), na.rm = TRUE)
ate_long_lal_trim <- ate_long_lal |>
filter(ATE >= q_bounds_lal[1] & ATE <= q_bounds_lal[2])
ggplot(ate_long_lal_trim, aes(x = Method, y = ATE, fill = Method)) +
geom_boxplot(alpha = 0.7) +
geom_hline(yintercept = true_ate_lal, linetype = "dashed", color = "red",
linewidth = 1) +
annotate("text", x = 0.5, y = true_ate_lal, label = "True ATE",
hjust = 0, vjust = -0.5, color = "red") +
labs(title = "ATE Estimates: LaLonde-Based Frengression DGP",
subtitle = paste0("B=", B_lal, " replications, n=", n_syn_lal,
" per dataset\n(confounding learned from real data)"),
y = "Estimated ATE (standardized)") +
theme_minimal() +
theme(legend.position = "none")
```
On the hand-written DGP (true ATE 0.0793), frengression does best, with a bias of
0.0027 and an RMSE of 0.0370. TMLE has a bias of 0.0434 and an RMSE of 0.0914,
DoubleML's interactive model 0.0922 and 0.1001, and npcausal 0.2004 and 0.2487,
with coverage of 50%, 40% and 20%. The generated data treat 90% of units, so
some propensity scores are close to one and the inverse-propensity terms in the
three doubly robust estimators are unstable. On the LaLonde-generated data (true
ATE 0.3, or \$2,241), only 3.2% of units are treated, about 64 of 2,000, against 30% in
the real LaLonde sample: the learned treatment model badly understates
treatment, and every method struggles. Frengression's bias is $-0.3487$ with an RMSE of 0.3917; TMLE's
is 0.2203 with an RMSE of 0.6867 and 0% coverage; npcausal and DoubleML are off by
$-0.7664$ and $-0.8070$, with 10% coverage. Frengression has no coverage entry
because we have no valid standard error for it.
The coverage column shows where reported standard errors fail. A method whose
interval covers the truth in 0 or 1 of 10 replications is not merely imprecise;
its reported standard error is wrong. TMLE's mean SE on the simulated benchmark is
0.0273 against an actual sampling SD of 0.0848, understating the uncertainty by a
factor of about three.
One caveat before drawing conclusions: $B = 10$ replications is a very small
Monte Carlo, so these coverage rates carry a standard error of about 0.15
themselves, and the ranking of the methods can change from one run of ten to
the next. An earlier run of this chapter, which used the partially linear
DoubleML model, scaled the binary covariates and stopped training early, ranked
DoubleML first on the hand-written DGP. What is stable across runs is that weak
overlap, 90% treated in one design and 3% in the other, makes the reported
standard errors of the doubly robust estimators far too small.
All methods show more bias on the LaLonde-generated data than on the hand-written simulation. That is the point of this exercise. The synthetic data has the real data's skewed prior-earnings distribution, and, because the learned treatment model understates treatment, far worse overlap than the real data. Before using such a generator as a benchmark, its treatment and covariate margins should be checked against the real data; here the treatment margin fails that check.
## Summary
Frengression uses the Evans and Didelez simulation decomposition, but learns the
pieces nonparametrically. The practical use is not that it beats TMLE or AIPW
for a simple ATE. The practical use is that it can learn a realistic
observational distribution, let us impose a known causal effect, and then
generate synthetic data where the truth is known.
That makes it useful for benchmarking. The simulation is still artificial, but
it is less artificial than writing down a clean logistic model and pretending
that it looks like real observational data.
---
<!-- see-also-footer -->
*Systematic treatment: [Julia](https://xiangao.github.io/causal_econometrics_julia/distributional-effects.html).*