The setting
An online retailer ran six weeks of display retargeting, and 40% of the 3,000 customers in the analysis file saw the ads. Over the next four weeks the exposed customers spent \$10.60 more than the others, and a regression that adjusts for tenure, distance to the nearest store and age still puts the effect at about \$8.50 per exposed customer. The campaign cost \$2.10 per exposed customer and the retailer keeps 40 cents of each dollar of sales, so it pays for itself only above \$5.25 of extra spend. At \$8.50 it clears that bar easily, and the plan on the table is to triple the budget.
The trouble is who saw the ads. The platform bid for people its signals marked as ready to buy, and those people spend more whether or not they see an ad. E107 asked how strong such a hidden confounder would have to be to overturn an estimate; here we try to remove it with proximal causal inference (Miao, Geng & Tchetgen Tchetgen 2018; Tchetgen Tchetgen et al. 2024). It needs two imperfect measurements of the confounder $U$: a treatment-side proxy $Z$, which may relate to who was treated but reaches the outcome only through $U$, and an outcome-side proxy $W$, which the treatment cannot touch and which relates to $Z$ only through $U$. These exclusion restrictions are a design judgment that no data can check. Completeness asks that the proxies move with every aspect of $U$; when it fails, the estimate is biased however large the sample.
The retailer has two candidates, both big. The site's tag kept a pre-campaign browsing log (page categories, search terms, dwell times: 150 columns), treatment side because the targeting may have used similar signals. The loyalty app kept pre-campaign telemetry (baskets, sessions, coupon views: another 150 columns), outcome side because the platform never sees it and a later ad cannot change it. Most of each log's variance has nothing to do with the customer. The browsing log changes with browser, tag version and consent banner, the app log with app version and operating system. This style dominates each log's covariance, and purchase intent is a small part of it.
Hong, Gao & Liu (2026), "Contrastive Proxy Forests: Completeness-Preserving Proxy Learning from Multimodal Records" (arXiv 2611.32708), start from one observation. Under the exclusion restrictions the two records are independent given the latent factors $L$ and the covariates $X$, so whatever they share beyond $X$ passes through $L$, and style, which lives in one record only, is not shared. They learn both proxies by contrasting the records given $X$ on a separate unlabeled pool, and the contrastive objective is minimised exactly by X-conditional ridge canonical correlation analysis (Theorem 1). A disjoint pool preserves exclusion exactly and the analysis sample does not (Theorem 2). In a linear factor model the top canonical variates carry everything a record holds about $L$, whatever the style (Theorem 3), while PCA can lose $L$ entirely (Proposition 2). Their proxies feed a proximal causal forest (NC-CSF and NC-CF, Gao et al. 2026, after Cui et al. 2023) for conditional effects on survival, learned from clinical notes and ECG waveforms. The ingredients are older: canonical correlation (Hotelling 1936), spectral contrastive learning as a matrix factorisation (HaoChen et al. 2021), and multiview learning that keeps the content two views share and drops view-specific style (von Kügelgen et al. 2021). Substitute confounders (Wang & Blei 2019) are usually adjusted for as covariates, which Proposition 4 shows leaves bias behind.
We keep the paper's first stage as it is and simplify the second. In place of the forest we fit a linear outcome bridge with a constant effect, as a Bayesian proximal instrumental-variable model in PyMC checked against closed-form proximal two-stage least squares. There are no conditional effects, no censoring and no treatment bridge, and Gaussian linear-factor logs stand in for note tokens and waveform spectra, the regime of Theorem 3. The forest itself is a poor fit for PyMC: NC-CF solves local moment equations with honest sample splitting and has no likelihood, and a Bayesian version would need nonparametric bridge functions inside an ill-posed inverse problem.
| part | question | tool |
|---|---|---|
| A | How wrong is the naive answer, and what is in the logs? | a simulated campaign with a known effect; regression with and without the hidden confounder |
| B | Which few numbers should stand in for 150 columns? | PCA against X-conditional ridge CCA on an unlabeled pool; held-out canonical correlations |
| C | How do proxies remove confounding? | proximal 2SLS; proxies as covariates; a relevance check without labels |
| D | The same estimate as a posterior | Bayesian proximal IV with LKJ errors on sufficient statistics; prior check; nutpie diagnostics; closed-form check |
| E | When does PCA break? | a sweep over style strength, 160 simulated campaigns |
| F | How can the CCA proxies break? | fitting them on the analysis sample (exclusion); keeping too few or too many directions |
| G | What to do with it | targeted exposure, holdouts and MMM calibration |
import os
for v_ in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ[v_] = "1" # nutpie runs chains as threads: a BLAS pool per chain would fight over the cores
import logging
import sys
import time
import warnings
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import nutpie
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
from scipy import stats
RANDOM_SEED = 136
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
sys.modules.pop("jax", None) # arviz leaves a lazy jax stub that makes matplotlib import all of JAX
pd.set_option("display.width", 160)
T_START = time.time()
BLUE, ORANGE, AQUA, PURPLE, RED = "#2a78d6", "#eb6834", "#1baf7a", "#8c5ac8", "#c8384e"
INK, MUTED, LIGHT = "#222222", "#8a8984", "#d9d8d3"
print(f"PyMC {pm.__version__}, ArviZ {az.__version__}, nutpie {nutpie.__version__}")
PyMC 6.3.2, ArviZ 1.3.0, nutpie 0.16.11
A · A campaign with a known answer
Every customer has three covariates $X$ (standardised tenure, distance and age) and three latent factors $L = (U_1, U_2, V)$: in-market intent $U_1$ and brand loyalty $U_2$, which drive exposure and spend and lean slightly on the covariates, and screen time $V$, which shows up in both logs and affects neither. Each log is a linear factor model,
$$M_z = \Lambda_z L + \Gamma_z X + s\,\Psi_z S_z + \varepsilon_z, \qquad M_w = \Lambda_w L + \Gamma_w X + s\,\Psi_w S_w + \varepsilon_w,$$
with 150 columns, five style factors per log (independent of everything else and of each other) and unit noise. The loadings on $U_1$, $U_2$ and $V$ have standard deviations 0.15, 0.10 and 0.20 per column, so summed over a log their signal variances are about 3.4, 1.5 and 6. The style ratio is the variance of one style factor, summed over the columns, divided by that of $V$: 4 in the main analysis, swept from 0 to 16 in part E. Exposure follows $\operatorname{logit} P(A=1) = -0.5 + U_1 + 0.6\,U_2 + 0.3\,x_1 - 0.2\,x_2$, and spend is
$$Y = 40 + 3A + 6\,U_1 + 3\,U_2 + \gamma^\top X + e, \qquad e \sim N(0, 8^2),$$
so the true effect is \$3 per exposed customer, below break-even. We draw a pool of 10,000 customers whose logs we use and whose exposure and spend we never look at, and an analysis sample of 3,000.
P = 150 # columns per log
N_POOL, N_ANA = 10_000, 3_000 # unlabeled pool, analysis sample
TAU = 3.0 # true effect of exposure on 4-week spend, $ per customer
BETA = np.array([6.0, 3.0]) # $ per sd of intent (U1) and of loyalty (U2)
GAMMA = np.array([2.0, -1.5, 1.0])
SHARED_SD = np.array([0.15, 0.10, 0.20]) # loading sd per column for U1, U2, V
N_STYLE = 5 # style factors per log
COST, MARGIN = 2.10, 0.40 # media cost per exposed customer, gross margin
BREAK_EVEN = COST / MARGIN
TOP_SHARED = P * SHARED_SD.max() ** 2 # variance of the strongest shared factor (V), summed over columns
def make_logs(seed):
"""Loadings of the two logs: on L = (U1, U2, V), on X, and on each log's own style factors."""
r = np.random.default_rng(seed)
return {side: {"L": r.normal(size=(P, 3)) * SHARED_SD, "X": r.normal(0, 0.3, (P, 3)),
"S": r.normal(size=(P, N_STYLE))} for side in ("z", "w")}
def simulate(logs, n, style, r, labelled=True):
"""n customers. style = variance of each style factor relative to the strongest shared factor."""
X = r.normal(size=(n, 3))
U1 = 0.3 * X[:, 0] + np.sqrt(1 - 0.09) * r.normal(size=n) # in-market intent
U2 = -0.2 * X[:, 1] + np.sqrt(1 - 0.04) * r.normal(size=n) # loyalty to the brand
V = r.normal(size=n) # screen time: shared, harmless
L = np.column_stack([U1, U2, V])
s_scale = np.sqrt(style * TOP_SHARED / P)
out = {"X": X, "L": L}
for side in ("z", "w"):
lg = logs[side]
out["M" + side] = (L @ lg["L"].T + X @ lg["X"].T
+ s_scale * r.normal(size=(n, N_STYLE)) @ lg["S"].T + r.normal(size=(n, P)))
if labelled:
eta = -0.5 + 1.0 * U1 + 0.6 * U2 + 0.3 * X[:, 0] - 0.2 * X[:, 1]
out["A"] = (r.uniform(size=n) < 1 / (1 + np.exp(-eta))).astype(float)
out["Y"] = 40 + TAU * out["A"] + L[:, :2] @ BETA + X @ GAMMA + r.normal(0, 8, n)
return out
def ols(y, R):
"""Least squares with HC1 standard errors; R includes the intercept column."""
b = np.linalg.lstsq(R, y, rcond=None)[0]
e = y - R @ b
XtXi = np.linalg.inv(R.T @ R)
V = XtXi @ ((R * e[:, None] ** 2).T @ R) @ XtXi * len(y) / (len(y) - R.shape[1])
return b, np.sqrt(np.diag(V))
def tsls(y, R, Q):
"""Two-stage least squares of y on regressors R with instruments Q (just identified); HC1 errors."""
b = np.linalg.solve(Q.T @ R, Q.T @ y)
e = y - R @ b
QRi = np.linalg.inv(Q.T @ R)
V = QRi @ ((Q * e[:, None] ** 2).T @ Q) @ QRi.T * len(y) / (len(y) - R.shape[1])
return b, np.sqrt(np.diag(V))
LOGS = make_logs(RANDOM_SEED)
STYLE = 4.0
r_main = np.random.default_rng(RANDOM_SEED + 1)
pool = simulate(LOGS, N_POOL, STYLE, r_main, labelled=False)
ana = simulate(LOGS, N_ANA, STYLE, r_main)
A, Y, X = ana["A"], ana["Y"], ana["X"]
one = np.ones((N_ANA, 1))
print(f"analysis sample: {N_ANA:,} customers, {A.mean():.0%} exposed; pool: {N_POOL:,} customers, logs only")
print(f"mean 4-week spend: exposed ${Y[A == 1].mean():.2f}, unexposed ${Y[A == 0].mean():.2f}, "
f"difference ${Y[A == 1].mean() - Y[A == 0].mean():.2f}")
b_naive, se_naive = ols(Y, np.hstack([one, A[:, None], X]))
b_orc, se_orc = ols(Y, np.hstack([one, A[:, None], X, ana["L"][:, :2]]))
print(f"regression on exposure and X: {b_naive[1]:5.2f} (se {se_naive[1]:.2f})")
print(f"oracle, also adjusting for U1, U2: {b_orc[1]:5.2f} (se {se_orc[1]:.2f}); truth {TAU:.2f}")
print(f"break-even incremental spend: ${BREAK_EVEN:.2f} per exposed customer")
analysis sample: 3,000 customers, 40% exposed; pool: 10,000 customers, logs only mean 4-week spend: exposed $47.36, unexposed $36.76, difference $10.60 regression on exposure and X: 8.50 (se 0.38) oracle, also adjusting for U1, U2: 2.90 (se 0.35); truth 3.00 break-even incremental spend: $5.25 per exposed customer
Exposure reaches 40% of the sample, and the exposed spend \$10.60 more. Adjusting for the three covariates brings that down to \$8.50 (robust se 0.38), still almost three times the truth. Only the oracle regression, which adjusts for intent and loyalty themselves, lands on the answer (\$2.90, se 0.35). The gap decides the campaign. At \$8.50 it returns about 60% more margin than it costs; at \$3 it loses about 90 cents of margin on every exposed customer.
How much of each log is about the customer? The next cell splits the variance of the raw columns, summed over all 150, into its sources, computed from the loadings.
def variance_shares(side, style):
lg = LOGS[side]
parts = {"style": style * TOP_SHARED / P * (lg["S"] ** 2).sum(),
"U1, U2 (confounder)": (lg["L"][:, :2] ** 2).sum(), "V (shared, harmless)": (lg["L"][:, 2] ** 2).sum(),
"X": (lg["X"] ** 2).sum(), "noise": float(P)}
tot = sum(parts.values())
return {k: v / tot for k, v in parts.items()}
print(pd.DataFrame({"browsing log": variance_shares("z", STYLE), "app log": variance_shares("w", STYLE)}).round(3))
browsing log app log style 0.387 0.365 U1, U2 (confounder) 0.016 0.016 V (shared, harmless) 0.017 0.017 X 0.111 0.124 noise 0.469 0.478
Style accounts for 37 to 39% of each log's variance at this setting, noise for nearly half and the covariates for 11 to 12%. The confounder, intent and loyalty together, is 1.6%. Any compression that ranks directions by variance will see style first.
B · Which few numbers should stand in for the logs?
Both methods first standardise each column and residualise it on $(1, X)$, with means, scales and coefficients estimated on the pool and applied unchanged to the analysis sample. Call the results $R_z$ and $R_w$, with covariances $\Sigma_{zz}$, $\Sigma_{ww}$ and cross-covariance $C$. PCA keeps the top $d$ eigenvectors of each log's own covariance. The paper's method (CPF) asks what the logs share. With linear heads $f = \Theta_z^\top R_z$ and $g = \Theta_w^\top R_w$, a customer's own two logs as a positive pair and an app log drawn at the same $X$ as a negative, the spectral contrastive loss is $-2\,E_\text{pos}[f^\top g] + E_\text{neg}[(f^\top g)^2]$. Theorem 1 shows that, with ridge noise $\lambda I$ added to each view, its minimisers are the top $d$ singular vectors of
$$K_\lambda = (\Sigma_{zz} + \lambda I)^{-1/2}\, C\, (\Sigma_{ww} + \lambda I)^{-1/2} = \Gamma\, \mathrm{diag}(\sigma)\, \Omega^\top,$$
mapped back by $\hat\Theta_z = (\Sigma_{zz}+\lambda I)^{-1/2}\Gamma_d$ and $\hat\Theta_w = (\Sigma_{ww}+\lambda I)^{-1/2}\Omega_d$. The contrastive learning is one SVD of a 150 by 150 matrix. Whitening is what makes it ignore style: a style direction has large variance in one log and no covariance with the other, so it contributes nothing to $K_\lambda$ however large it is. Residualising on $X$ keeps CCA from spending its first directions on the covariates, which both logs load on.
The ridge $\lambda$ and the number of proxies $d$ are chosen without exposure or spend: fit on 80% of the pool and compute the canonical correlations of the fitted directions on the other 20%.
class Prep:
"""Standardise each column and residualise it on (1, X), with statistics from the pool only."""
def __init__(self, M, X):
self.mu, self.sd = M.mean(0), M.std(0)
Xd = np.column_stack([np.ones(len(X)), X])
self.B = np.linalg.lstsq(Xd, (M - self.mu) / self.sd, rcond=None)[0]
def __call__(self, M, X):
return (M - self.mu) / self.sd - np.column_stack([np.ones(len(X)), X]) @ self.B
def inv_sqrt(S):
e, V = np.linalg.eigh(S)
return (V / np.sqrt(e)) @ V.T
def ridge_cca(Rz, Rw, lam, d):
"""X-conditional ridge CCA on residualised logs: maps (p x d) for each side and the d singular values."""
n = len(Rz)
Iz = inv_sqrt(Rz.T @ Rz / n + lam * np.eye(Rz.shape[1]))
Iw = inv_sqrt(Rw.T @ Rw / n + lam * np.eye(Rw.shape[1]))
G, s, Ht = np.linalg.svd(Iz @ (Rz.T @ Rw / n) @ Iw)
return Iz @ G[:, :d], Iw @ Ht.T[:, :d], s[:d]
def pca_map(R, d):
"""Top-d principal directions, scaled so each score has unit variance."""
e, V = np.linalg.eigh(R.T @ R / len(R))
idx = np.argsort(e)[::-1][:d]
return V[:, idx] / np.sqrt(e[idx]), e[np.argsort(e)[::-1]]
def heldout_cc(Rz, Rw, lam, d, seed=0):
"""Fit on 80% of the pool, return the d canonical correlations on the other 20%."""
idx = np.random.default_rng(seed).permutation(len(Rz))
tr, te = idx[: int(0.8 * len(Rz))], idx[int(0.8 * len(Rz)):]
Tz, Tw, _ = ridge_cca(Rz[tr], Rw[tr], lam, d)
a, b = Rz[te] @ Tz, Rw[te] @ Tw
return np.array([np.corrcoef(a[:, j], b[:, j])[0, 1] for j in range(d)])
def r2_of(target, P_):
"""Share of the variance of each target column explained by a linear fit on [1, P_]."""
D_ = np.column_stack([np.ones(len(P_)), P_])
T = target - target.mean(0)
fit = D_ @ np.linalg.lstsq(D_, T, rcond=None)[0]
return 1 - ((T - fit) ** 2).sum(0) / (T ** 2).sum(0)
prep_z, prep_w = Prep(pool["Mz"], pool["X"]), Prep(pool["Mw"], pool["X"])
Rz_pool, Rw_pool = prep_z(pool["Mz"], pool["X"]), prep_w(pool["Mw"], pool["X"])
LAMBDAS = [0.01, 0.1, 1.0, 10.0]
cc_grid = {lam: heldout_cc(Rz_pool, Rw_pool, lam, 10) for lam in LAMBDAS}
for lam, cc in cc_grid.items():
print(f"lambda {lam:5}: held-out canonical correlations {np.round(cc, 2)}")
lambda 0.01: held-out canonical correlations [ 0.84 0.73 0.59 -0.01 0.01 0.03 0.02 -0.01 -0.04 -0.01] lambda 0.1: held-out canonical correlations [ 0.84 0.73 0.59 0. 0.01 0.01 0.02 -0.02 -0. -0. ] lambda 1.0: held-out canonical correlations [ 0.83 0.73 0.6 -0.02 -0. -0. 0.01 0. 0.03 0.01] lambda 10.0: held-out canonical correlations [ 0.83 0.71 0.59 -0.01 -0. -0.01 0.01 0. 0.01 0.01]
At every ridge the held-out canonical correlations show three directions (about 0.84, 0.73 and 0.59) and then nothing, every later one within a few hundredths of zero. The sum of the first three is 2.16 at every $\lambda$ to two decimals, so the rule picks $\lambda = 1$ by a hair and nothing below depends on it. The drop after the third direction picks $d = 3$, without labels, and finds all three components of $L$.
We now fit both compressions on the whole pool, apply them to the analysis sample and, because this is a simulation, measure how much of each latent factor the proxies carry. The last column is the best linear summary of all 150 browsing columns, fitted on the pool with $L$ itself, which no real analyst could compute.
D = 3
LAM = max(LAMBDAS, key=lambda l_: cc_grid[l_][:D].sum())
Tz, Tw, cc_pool = ridge_cca(Rz_pool, Rw_pool, LAM, D)
Pz, eig_z = pca_map(Rz_pool, D)
Pw, eig_w = pca_map(Rw_pool, D)
Rz_ana, Rw_ana = prep_z(ana["Mz"], X), prep_w(ana["Mw"], X)
Zc, Wc = Rz_ana @ Tz, Rw_ana @ Tw # CCA proxies
Zp, Wp = Rz_ana @ Pz, Rw_ana @ Pw # PCA proxies
print(f"chosen lambda {LAM}, d = {D}")
# what each principal component of the browsing log carries (only a simulation can check this)
pcs_all, _ = pca_map(Rz_pool, 12)
pc_r2 = np.array([r2_of(pool["L"], (Rz_pool @ pcs_all[:, [j]])).max() for j in range(12)])
cc_full = cc_grid[LAM]
conf = ana["L"][:, :2] @ BETA # the part of U that moves sales
# Theorem 3(a): the best linear summary of L from the whole browsing log (needs L, so oracle only)
Bpost = np.linalg.lstsq(np.column_stack([np.ones(N_POOL), Rz_pool]), pool["L"], rcond=None)[0]
Lpost = np.column_stack([np.ones(N_ANA), Rz_ana]) @ Bpost
tab = pd.DataFrame({
"PCA W~": np.r_[r2_of(ana["L"], Wp), r2_of(conf[:, None], Wp)],
"CCA W~": np.r_[r2_of(ana["L"], Wc), r2_of(conf[:, None], Wc)],
"PCA Z~": np.r_[r2_of(ana["L"], Zp), r2_of(conf[:, None], Zp)],
"CCA Z~": np.r_[r2_of(ana["L"], Zc), r2_of(conf[:, None], Zc)],
"all 150 browsing cols": np.r_[r2_of(ana["L"], Lpost), r2_of(conf[:, None], Lpost)],
}, index=["U1 intent", "U2 loyalty", "V screen time", "6 U1 + 3 U2"])
print("R^2 of each latent from the proxies (analysis sample):")
print(tab.round(2).to_string())
chosen lambda 1.0, d = 3
R^2 of each latent from the proxies (analysis sample):
PCA W~ CCA W~ PCA Z~ CCA Z~ all 150 browsing cols
U1 intent 0.0 0.68 0.01 0.70 0.70
U2 loyalty 0.0 0.55 0.00 0.54 0.55
V screen time 0.0 0.85 0.01 0.84 0.84
6 U1 + 3 U2 0.0 0.66 0.01 0.68 0.68The PCA proxies carry none of the three factors ($R^2$ of 0.00 or 0.01): three directions, all style. The app-side CCA proxies carry 0.68 of intent, 0.55 of loyalty and 0.85 of screen time, and the browsing-side ones match the oracle summary of all 150 columns to within 0.01. That is Theorem 3(a) in numbers: the top canonical variates are an invertible transformation of $E_\text{lin}[L \mid R_z]$, whatever the style. They are still noisy. A third of the confounding score $6U_1 + 3U_2$ is left unexplained, which matters in part C. Figure 1 shows where the confounder sits in the PCA spectrum, and the held-out scree.
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
ax = axes[0]
cols_ = [ORANGE if v < 0.2 else BLUE for v in pc_r2]
ax.bar(np.arange(1, 13), eig_z[:12], color=cols_)
ax.set_xticks(np.arange(1, 13))
for j, v in enumerate(pc_r2):
ax.text(j + 1, eig_z[j] + 0.3, f"{v:.2f}", ha="center", fontsize=8, color=INK)
ax.set_xlabel("principal component of the browsing log")
ax.set_ylabel("variance (pool)")
ax.set_title("PCA: largest R² with any latent shown above each bar")
ax.legend(handles=[plt.Rectangle((0, 0), 1, 1, color=ORANGE), plt.Rectangle((0, 0), 1, 1, color=BLUE)],
labels=["style or noise (R² < 0.2)", "carries L"], frameon=False)
ax = axes[1]
noise_band = 2 / np.sqrt(0.2 * N_POOL)
ax.axhspan(-noise_band, noise_band, color=LIGHT, label="±2/√n, no shared signal")
ax.plot(np.arange(1, 11), cc_full, "o-", color=BLUE, label=f"ridge CCA, λ = {LAM}")
ax.set_xlabel("canonical direction")
ax.set_ylabel("held-out canonical correlation")
ax.set_title("CCA: what the two logs share")
ax.legend(frameon=False)
plt.show();

In the browsing log's spectrum (left) the five largest components are style, with $R^2$ of 0.00 against every latent factor. The three that carry $L$ come sixth to eighth ($R^2$ from 0.52 to 0.80), and noise follows. A three-component PCA keeps three style directions. The canonical correlations (right) do not see style at all.
C · Proxies inside the estimator, and proxies as covariates
Write $\tilde Z = a(M_z)$ and $\tilde W = b(M_w)$ for the learned proxies. Proximal identification looks for an outcome bridge $h(\tilde W, A, X)$ with
$$E\big[\,Y - h(\tilde W, A, X) \;\big|\; A, X, \tilde Z\,\big] = 0,$$
and the effect is then $E[h(\tilde W, 1, X) - h(\tilde W, 0, X)]$. With a linear bridge $h = c + \tau A + \gamma^\top X + \theta^\top \tilde W$ this is an instrumental-variable problem: regress $Y$ on $(1, A, X, \tilde W)$ with instruments $(1, A, X, \tilde Z)$. Think of errors in variables. $\theta^\top \tilde W$ stands in for $\beta^\top U$, but $\tilde W$ is $U$ plus noise, and adjusting for a noisy measurement adjusts only partly; $\tilde Z$, a second measurement with independent noise, is exactly the instrument $\tilde W$ needs. Proposition 4 of the paper shows that least squares with both proxies as covariates keeps a bias whenever they do not determine $U$, while proximal 2SLS is consistent at any level of proxy noise.
We fit the naive regression, proxies as covariates and proximal 2SLS with each set of proxies, plus the oracle. The last line is a relevance check: the canonical correlations of $\tilde Z$ and $\tilde W$ after removing $(1, A, X)$, which measure instrument strength without spend or the latent factors.
def relevance(Zt, Wt):
"""Canonical correlations between Z~ and W~ after removing (1, A, X): instrument strength, no labels."""
C_ = np.column_stack([one, A, X])
rz = Zt - C_ @ np.linalg.lstsq(C_, Zt, rcond=None)[0]
rw = Wt - C_ @ np.linalg.lstsq(C_, Wt, rcond=None)[0]
qz, qw = np.linalg.qr(rz)[0], np.linalg.qr(rw)[0]
return np.linalg.svd(qz.T @ qw, compute_uv=False)
def estimates(Zt, Wt, Y_=None, A_=None, X_=None, L_=None):
"""Treatment coefficient and HC1 se for each estimator."""
Y_, A_, X_ = (Y, A, X) if Y_ is None else (Y_, A_, X_)
o = np.ones((len(Y_), 1))
base = np.hstack([o, A_[:, None], X_])
out = {"naive (A, X)": ols(Y_, base),
"OLS, proxies as covariates": ols(Y_, np.hstack([base, Zt, Wt])),
"proximal 2SLS": tsls(Y_, np.hstack([base, Wt]), np.hstack([base, Zt]))}
if L_ is not None:
out["oracle (adjust for U)"] = ols(Y_, np.hstack([base, L_[:, :2]]))
return {k: (b[1], s[1]) for k, (b, s) in out.items()}
rows = []
for name, (Zt, Wt) in {"PCA": (Zp, Wp), "CCA": (Zc, Wc)}.items():
for k, (est, se) in estimates(Zt, Wt, L_=ana["L"]).items():
if name == "CCA" and k in ("naive (A, X)", "oracle (adjust for U)"):
continue
rows.append({"proxies": name if "proxies" in k or "2SLS" in k else "-", "estimator": k,
"estimate": est, "se": se, "error": est - TAU})
res_c = pd.DataFrame(rows).drop_duplicates(subset=["proxies", "estimator"])
print(res_c.round(2).to_string(index=False))
print(f"\nrelevance (canonical corr. of Z~ and W~ given 1, A, X): PCA {np.round(relevance(Zp, Wp), 3)} "
f"CCA {np.round(relevance(Zc, Wc), 3)}")
proxies estimator estimate se error
- naive (A, X) 8.50 0.38 5.50
PCA OLS, proxies as covariates 8.49 0.39 5.49
PCA proximal 2SLS 8.40 0.83 5.40
- oracle (adjust for U) 2.90 0.35 -0.10
CCA OLS, proxies as covariates 4.00 0.36 1.00
CCA proximal 2SLS 3.17 0.40 0.17
relevance (canonical corr. of Z~ and W~ given 1, A, X): PCA [0.047 0.024 0.005] CCA [0.849 0.736 0.557]With PCA proxies nothing happens: \$8.49 as covariates and \$8.40 by proximal 2SLS, the naive answer, since the proxies carry no intent. CCA proxies as covariates give \$4.00, removing 82% of the bias and leaving \$1.00, as Proposition 4 predicts. Proximal 2SLS with the same proxies gives \$3.17 (robust se 0.40), beside the oracle's \$2.90. The relevance check flags PCA before anyone looks at sales: canonical correlations of 0.05, 0.02 and 0.005, against CCA's 0.85, 0.74 and 0.56. Proxies that do not correlate across the logs, given exposure and covariates, cannot be measuring a common confounder. The covariate approach happens to get this decision right (\$4.00 is below \$5.25) with a number a third too high; closer to break-even, that leftover dollar decides the renewal.
D · A Bayesian proximal model in PyMC
A posterior for the effect is the form a media team needs to carry it into an MMM prior (E103) or a budget decision. We write the proximal IV as a triangular system, the Bayesian IV of Rossi, Allenby & McCulloch (2005) and Lopes & Polson (2014) used in E63, here with $d$ endogenous proxies:
$$\tilde W_i = \pi_0 + \pi_A A_i + \Pi_X^\top x_i + \Pi_Z^\top \tilde Z_i + v_i, \qquad y_i = c + \tau A_i + \gamma^\top x_i + \theta^\top \tilde W_i + u_i, \qquad (v_i, u_i) \sim N(0, \Sigma).$$
The correlation between $u$ and $v$ makes $\tilde W$ endogenous. It is learned through $\tilde Z$, with an LKJ(2) prior on the correlations and HalfNormal(1) scales. The map from $(v, u)$ to $(\tilde W, y)$ is triangular with a unit diagonal, so the MvNormal density of the residuals is the joint density of the data. Spend is standardised, and $\tau$ in dollars is $\tau_s$ times its sd, about \$9.6. The outcome coefficients get $N(0, 0.5)$ priors, the first-stage coefficients and the intercept $N(0, 1)$.
The likelihood needs only cross-products. With responses $O = [\tilde W, y]$, regressors $G = [1, A, X, \tilde Z, \tilde W]$ and one coefficient matrix $B$ with structural zeros ($\tilde W$ is absent from its own first stage, $\tilde Z$ from the bridge), the residual cross-product is $E^\top E = O^\top O - O^\top G B - B^\top G^\top O + B^\top G^\top G B$, and
$$\log p = -\tfrac{n}{2}\log|\Sigma| - \tfrac12 \operatorname{tr}\big(\Sigma^{-1} E^\top E\big) - \tfrac{n(d+1)}{2}\log 2\pi .$$
The 3,000 rows become an 11 by 11 and an 11 by 4 matrix in pm.Data, so nutpie compiles the model
once and with_data swaps in other proxies or other campaigns. The cell checks the potential
against a row-by-row MvNormal density at a random parameter point.
def suff_stats(Y_, A_, X_, Zt, Wt, y_mu, y_sd):
"""Cross-products that are all the likelihood needs: G'G, G'O, O'O, n."""
G = np.column_stack([np.ones(len(Y_)), A_, X_, Zt, Wt])
O = np.column_stack([Wt, (Y_ - y_mu) / y_sd])
return {"GG": G.T @ G, "GO": G.T @ O, "OO": O.T @ O, "n_obs": np.array(float(len(Y_))),
"y_sd": np.array(float(y_sd))}
Y_MU, Y_SD = Y.mean(), Y.std()
s_cca = suff_stats(Y, A, X, Zc, Wc, Y_MU, Y_SD)
coords = {"proxy": [f"p{j + 1}" for j in range(D)], "zproxy": [f"z{j + 1}" for j in range(D)],
"cov": ["x1", "x2", "x3"],
"eq": [f"W{j + 1}" for j in range(D)] + ["Y"]}
with pm.Model(coords=coords) as prox:
GG, GO, OO = pm.Data("GG", s_cca["GG"]), pm.Data("GO", s_cca["GO"]), pm.Data("OO", s_cca["OO"])
n_obs, y_sd = pm.Data("n_obs", s_cca["n_obs"]), pm.Data("y_sd", s_cca["y_sd"])
# first stage: each proxy W~_j on (1, A, X, Z~)
pi0 = pm.Normal("pi0", 0, 1, dims="proxy")
piA = pm.Normal("piA", 0, 1, dims="proxy")
piX = pm.Normal("piX", 0, 1, dims=("cov", "proxy"))
piZ = pm.Normal("piZ", 0, 1, dims=("zproxy", "proxy"))
# outcome bridge h(W~, A, X) = c + tau A + gamma'X + theta'W~, on standardised spend
c = pm.Normal("c", 0, 1)
tau_s = pm.Normal("tau_s", 0, 0.5)
gam = pm.Normal("gamma", 0, 0.5, dims="cov")
theta = pm.Normal("theta", 0, 0.5, dims="proxy")
chol, corr, sds = pm.LKJCholeskyCov("chol", n=D + 1, eta=2.0, sd_dist=pm.HalfNormal.dist(1.0),
compute_corr=True)
pm.Deterministic("tau", tau_s * y_sd)
pm.Deterministic("rho_WY", corr[-1, :-1], dims="proxy")
# coefficient matrix B, rows (1, A, x1..x3, Z~1..d, W~1..d), one column per equation
BW = pt.concatenate([pi0[None, :], piA[None, :], piX, piZ, pt.zeros((D, D))], axis=0)
BY = pt.concatenate([pt.stack([c, tau_s]), gam, pt.zeros(D), theta])[:, None]
B = pt.concatenate([BW, BY], axis=1)
EE = OO - GO.T @ B - B.T @ GO + B.T @ GG @ B # residual cross-product E'E
Linv = pt.linalg.solve_triangular(chol, pt.eye(D + 1), lower=True)
quad = pt.sum(Linv * (Linv @ EE)) # tr(Sigma^-1 E'E)
logdet = 2 * pt.sum(pt.log(pt.diag(chol)))
pm.Potential("loglik", -0.5 * n_obs * logdet - 0.5 * quad - 0.5 * n_obs * (D + 1) * np.log(2 * np.pi))
# check: the sufficient-statistic potential equals the row-by-row MvNormal log density
outs_ = prox.replace_rvs_by_values([pi0, piA, piX, piZ, c, tau_s, gam, theta, chol, prox["loglik"]])
pt_vals = prox.compile_fn(outs_, inputs=prox.value_vars, point_fn=True)
ip = prox.initial_point()
rr = np.random.default_rng(3)
ip = {k: v + 0.3 * rr.normal(size=np.shape(v)) for k, v in ip.items()}
v0, vA, vX, vZ, vc, vt, vg, vth, vchol, vlik = pt_vals(ip)
muW = v0 + A[:, None] * vA + X @ vX + Zc @ vZ
muY = vc + vt * A + X @ vg + Wc @ vth
resid = np.column_stack([Wc - muW, (Y - Y_MU) / Y_SD - muY])
direct = stats.multivariate_normal(np.zeros(D + 1), vchol @ vchol.T).logpdf(resid).sum()
print(f"log-likelihood at a random point: sufficient statistics {float(vlik):.4f}, row by row {direct:.4f}")
log-likelihood at a random point: sufficient statistics -22206.8773, row by row -22206.8773
The two log-likelihoods agree to four decimals. Before fitting, a prior check: draws of the effect in dollars, of the spread of simulated standardised spend given the observed exposures, covariates and proxies, and of one error correlation.
prior = pm.sample_prior_predictive(draws=1000, model=prox, random_seed=RANDOM_SEED)
pr = prior.prior
tau_prior = pr["tau"].values.ravel()
th_prior = pr["theta"].values.reshape(-1, D)
chol_prior = pr["chol"].values.reshape(-1, D + 1, D + 1)
sd_y_prior = np.array([np.std(pr["c"].values.ravel()[i] + pr["tau_s"].values.ravel()[i] * A
+ X @ pr["gamma"].values.reshape(-1, 3)[i] + Wc @ th_prior[i]
+ chol_prior[i, -1, -1] * rr.normal(size=N_ANA)) for i in range(200)])
print(f"prior tau ($): 5%, 50%, 95% = {np.round(np.quantile(tau_prior, [0.05, 0.5, 0.95]), 1)}")
print(f"prior sd of simulated standardised spend: 5%, 50%, 95% = "
f"{np.round(np.quantile(sd_y_prior, [0.05, 0.5, 0.95]), 2)} (data: 1.00)")
print(f"prior correlation between the W1 and Y errors: 5%, 95% = "
f"{np.round(np.quantile(pr['rho_WY'].values[..., 0].ravel(), [0.05, 0.95]), 2)}")
prior tau ($): 5%, 50%, 95% = [-9.9 -0.2 9.8] prior sd of simulated standardised spend: 5%, 50%, 95% = [0.67 1.15 1.88] (data: 1.00) prior correlation between the W1 and Y errors: 5%, 95% = [-0.55 0.55]
The prior puts 90% of the effect between about \$-10 and \$+10, wide enough for every answer on the table. Simulated standardised spend has a standard deviation between 0.67 and 1.88 (median 1.15), and the observed 1.00 sits well inside that range: the priors allow customer bases somewhat calmer or noisier than ours and nothing wild. The error correlation spans about ±0.55, which is the LKJ(2) prior at work.
t0 = time.time()
compiled = nutpie.compile_pymc_model(prox)
t_compile = time.time() - t0
def fit_prox(stats_, seed):
t0_ = time.time()
fit_ = nutpie.sample(compiled.with_data(**stats_), chains=4, draws=1000, tune=400, seed=seed,
progress_bar=False)
return fit_, time.time() - t0_
def diag(fit_):
s_ = az.summary(fit_, var_names=["pi0", "piA", "piX", "piZ", "c", "tau_s", "gamma", "theta"])
return int(fit_.sample_stats["diverging"].sum()), float(s_["r_hat"].max()), float(s_["ess_bulk"].min())
fit_cca, t_cca = fit_prox(s_cca, RANDOM_SEED)
print(f"compile {t_compile:.0f} s, sample {t_cca:.1f} s (nutpie, 4 chains x 1000 draws, 400 warm-up)")
print("divergences %d, max r_hat %.3f, min bulk ESS %.0f" % diag(fit_cca))
print(az.summary(fit_cca, var_names=["tau", "theta", "rho_WY"], ci_kind="hdi", ci_prob=0.94, round_to=3))
e_c, s_c = estimates(Zc, Wc)["proximal 2SLS"]
print(f"closed-form proximal 2SLS: {e_c:.3f} (HC1 se {s_c:.3f})")
compile 10 s, sample 0.5 s (nutpie, 4 chains x 1000 draws, 400 warm-up)
divergences 0, max r_hat 1.004, min bulk ESS 1378
mean sd hdi94_lb hdi94_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
tau 3.181 0.400 2.480 3.964 1599.712 2220.583 1.003 0.010 0.006
theta[p1] -0.103 0.019 -0.138 -0.068 3505.971 2870.955 1.001 0.000 0.000
theta[p2] 0.677 0.024 0.631 0.720 1761.755 2456.143 1.002 0.001 0.000
theta[p3] 0.287 0.035 0.222 0.353 1378.438 1845.570 1.003 0.001 0.001
rho_WY[p1] 0.052 0.021 0.008 0.090 3809.186 3436.303 1.001 0.000 0.000
rho_WY[p2] -0.243 0.023 -0.289 -0.202 2517.791 3021.882 1.001 0.000 0.000
rho_WY[p3] -0.140 0.033 -0.199 -0.075 1433.715 2054.776 1.003 0.001 0.001
closed-form proximal 2SLS: 3.170 (HC1 se 0.397)The model compiles once, in 10 to 20 seconds, and each fit then samples in about a second (4 chains of 1,000 draws after 400 warm-up steps under nutpie): no divergences, largest r_hat 1.004, smallest bulk ESS about 1,400. The effect's posterior mean is \$3.18, sd 0.40 (94% HDI \$2.48 to \$3.96), against closed-form 2SLS at \$3.17 with robust se 0.40, and the whole interval sits below break-even. The error correlations $\rho_{WY}$ of about $-0.24$ and $-0.14$ are the measurement error in $\tilde W$ that least squares ignores; the model learns them through $\tilde Z$, and that is where part C's leftover dollar went.
Now the same compiled model with the PCA proxies.
s_pca = suff_stats(Y, A, X, Zp, Wp, Y_MU, Y_SD)
fit_pca, t_pca = fit_prox(s_pca, RANDOM_SEED)
print(f"PCA proxies: sample {t_pca:.1f} s; divergences %d, max r_hat %.3f, min bulk ESS %.0f" % diag(fit_pca))
print(az.summary(fit_pca, var_names=["tau", "theta", "rho_WY"], ci_kind="hdi", ci_prob=0.94, round_to=3))
e_p, s_p = estimates(Zp, Wp)["proximal 2SLS"]
print(f"closed-form proximal 2SLS: {e_p:.2f} (HC1 se {s_p:.2f})")
PCA proxies: sample 1.6 s; divergences 0, max r_hat 1.021, min bulk ESS 392
mean sd hdi94_lb hdi94_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
tau 8.458 0.448 7.574 9.265 3001.249 2414.639 1.000 0.008 0.007
theta[p1] 0.014 0.259 -0.460 0.505 391.785 578.979 1.021 0.013 0.009
theta[p2] 0.003 0.244 -0.424 0.510 405.410 552.070 1.015 0.012 0.009
theta[p3] 0.005 0.253 -0.479 0.492 448.500 649.552 1.006 0.012 0.009
rho_WY[p1] -0.020 0.258 -0.498 0.454 384.466 564.697 1.021 0.013 0.007
rho_WY[p2] -0.009 0.241 -0.491 0.413 399.963 543.326 1.016 0.012 0.007
rho_WY[p3] 0.008 0.252 -0.481 0.460 453.351 582.240 1.005 0.012 0.007
closed-form proximal 2SLS: 8.40 (HC1 se 0.83)The posterior is confident and wrong: \$8.46, sd 0.45 (94% HDI \$7.57 to \$9.27), the naive answer. The bridge coefficients and error correlations sit at zero with sd about 0.25, half the prior sd for $\theta$; their r_hat reaches 1.02 and bulk ESS drops to about 400, while the effect itself mixes well. With instruments that carry nothing, the likelihood cannot tell "$\tilde W$ is exogenous and irrelevant" from "$\tilde W$ is relevant and its errors are correlated with spend's". Priors centred at zero choose the first reading, which is least squares. Closed-form 2SLS gives \$8.40 (robust se 0.83) here and swings far wider in other campaigns (part E). Neither flags the empty proxies; the relevance check of part C does.
tau_cca = fit_cca.posterior["tau"].values.ravel()
tau_pca = fit_pca.posterior["tau"].values.ravel()
fig, ax = plt.subplots(figsize=(9, 3.6))
grid = np.linspace(0, 12, 400)
for draws_, col, lab in [(tau_cca, BLUE, "CCA proxies"), (tau_pca, ORANGE, "PCA proxies")]:
ax.fill_between(grid, stats.gaussian_kde(draws_)(grid), color=col, alpha=0.35, label=lab)
ax.axvline(TAU, color=INK, lw=2, label=f"truth ${TAU:.0f}")
ax.axvline(b_naive[1], color=MUTED, ls="--", label=f"naive ${b_naive[1]:.1f}")
ax.axvline(BREAK_EVEN, color=RED, ls=":", lw=2, label=f"break-even ${BREAK_EVEN:.2f}")
ax.set_xlabel("effect of exposure on 4-week spend ($ per customer)")
ax.set_yticks([])
ax.set_title("Posterior of the ad effect, Bayesian proximal model, same customers and same logs")
ax.legend(frameon=False, loc="upper right")
plt.show();

Figure 2 puts the two posteriors side by side. Same customers, same logs, same model: the compression alone turns a campaign that loses money into an apparent winner.
E · When does PCA break?
Proposition 2 says that once style spans at least $d$ directions with more variance than the largest shared signal, PCA proxies are uncorrelated with $L$, while CCA's directions do not depend on the size of style. We sweep 8 style levels from 0 to 16, with 20 simulated campaigns at each. The pool has 5,000 customers here, since Theorem 3(c) puts the cost of a finite pool at second order, and $\lambda$ stays at 1. For the first campaign at each level we also fit the Bayesian model with both sets of proxies, by swapping their sufficient statistics into the compiled model.
RATIOS = [0.0, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0]
N_REP, N_POOL_SWEEP = 20, 5_000
sweep, bayes_pts = [], []
t0 = time.time()
for ratio in RATIOS:
for rep in range(N_REP):
r_ = np.random.default_rng([RANDOM_SEED, int(ratio * 100), rep])
pl = simulate(LOGS, N_POOL_SWEEP, ratio, r_, labelled=False)
an = simulate(LOGS, N_ANA, ratio, r_)
pz_, pw_ = Prep(pl["Mz"], pl["X"]), Prep(pl["Mw"], pl["X"])
rz_, rw_ = pz_(pl["Mz"], pl["X"]), pw_(pl["Mw"], pl["X"])
tz_, tw_, _ = ridge_cca(rz_, rw_, LAM, D)
az_, aw_ = pz_(an["Mz"], an["X"]), pw_(an["Mw"], an["X"])
prox_sets = {"CCA": (az_ @ tz_, aw_ @ tw_), "PCA": (az_ @ pca_map(rz_, D)[0], aw_ @ pca_map(rw_, D)[0])}
conf_ = an["L"][:, :2] @ BETA
row = {"ratio": ratio, "rep": rep}
for nm, (zt_, wt_) in prox_sets.items():
est_ = estimates(zt_, wt_, an["Y"], an["A"], an["X"], an["L"])
row["naive"], row["oracle"] = est_["naive (A, X)"][0], est_["oracle (adjust for U)"][0]
row[f"2SLS {nm}"], row[f"se {nm}"] = est_["proximal 2SLS"]
row[f"OLS+{nm}"] = est_["OLS, proxies as covariates"][0]
row[f"R2 {nm}"] = r2_of(conf_[:, None], wt_)[0]
if rep == 0:
mu_, sd_ = an["Y"].mean(), an["Y"].std()
f_, _ = fit_prox(suff_stats(an["Y"], an["A"], an["X"], zt_, wt_, mu_, sd_), RANDOM_SEED + rep)
dv_, rh_, _ = diag(f_)
bayes_pts.append({"ratio": ratio, "proxies": nm, "tau": float(f_.posterior["tau"].mean()),
"lo": float(np.quantile(f_.posterior["tau"], 0.05)),
"hi": float(np.quantile(f_.posterior["tau"], 0.95)),
"div": dv_, "rhat": rh_})
sweep.append(row)
sweep = pd.DataFrame(sweep)
bayes_pts = pd.DataFrame(bayes_pts)
print(f"{len(sweep)} simulated campaigns and {len(bayes_pts)} Bayesian fits in {time.time() - t0:.0f} s")
summ = sweep.groupby("ratio")[["naive", "OLS+CCA", "2SLS PCA", "2SLS CCA", "oracle", "R2 PCA", "R2 CCA"]].median()
summ["MAE 2SLS PCA"] = sweep.assign(e=lambda d_: (d_["2SLS PCA"] - TAU).abs()).groupby("ratio")["e"].median()
summ["MAE 2SLS CCA"] = sweep.assign(e=lambda d_: (d_["2SLS CCA"] - TAU).abs()).groupby("ratio")["e"].median()
print("medians over", N_REP, "campaigns per style level")
print(summ.round(2).to_string())
cov90 = (np.abs(sweep["2SLS CCA"] - TAU) < 1.645 * sweep["se CCA"]).mean()
print(f"90% Wald intervals of proximal 2SLS with CCA proxies cover the truth in {cov90:.0%} of {len(sweep)} campaigns")
print("\nBayesian proximal model, first campaign at each level (posterior mean, 90% interval)")
print(bayes_pts.round(2).to_string(index=False))
160 simulated campaigns and 16 Bayesian fits in 42 s
medians over 20 campaigns per style level
naive OLS+CCA 2SLS PCA 2SLS CCA oracle R2 PCA R2 CCA MAE 2SLS PCA MAE 2SLS CCA
ratio
0.00 8.78 4.01 2.92 2.91 2.87 0.67 0.67 0.21 0.21
0.25 8.80 4.16 3.13 2.95 3.05 0.61 0.67 0.74 0.29
0.50 8.88 4.16 2.64 2.98 3.06 0.02 0.66 2.56 0.14
1.00 8.70 4.11 8.55 3.06 3.06 0.00 0.66 5.72 0.25
2.00 8.77 4.20 9.04 3.13 2.98 0.00 0.66 6.04 0.19
4.00 8.81 4.08 9.63 2.98 3.01 0.00 0.66 6.63 0.35
8.00 8.73 4.11 8.62 2.93 2.99 0.00 0.65 5.62 0.25
16.00 8.58 4.14 8.38 3.01 2.82 0.00 0.65 5.38 0.24
90% Wald intervals of proximal 2SLS with CCA proxies cover the truth in 92% of 160 campaigns
Bayesian proximal model, first campaign at each level (posterior mean, 90% interval)
ratio proxies tau lo hi div rhat
0.00 CCA 2.70 2.03 3.36 0 1.00
0.00 PCA 2.67 1.99 3.36 0 1.00
0.25 CCA 2.76 2.08 3.41 0 1.00
0.25 PCA 3.57 2.87 4.26 0 1.03
0.50 CCA 3.04 2.34 3.71 0 1.00
0.50 PCA 4.61 2.83 6.37 0 1.01
1.00 CCA 3.26 2.58 3.92 0 1.00
1.00 PCA 8.50 7.70 9.29 0 1.01
2.00 CCA 3.81 3.17 4.44 0 1.00
2.00 PCA 8.60 7.68 9.48 0 1.01
4.00 CCA 2.90 2.25 3.57 0 1.00
4.00 PCA 8.40 7.34 9.42 0 1.01
8.00 CCA 2.72 2.07 3.36 0 1.00
8.00 PCA 8.70 7.90 9.49 0 1.01
16.00 CCA 2.82 2.15 3.48 0 1.00
16.00 PCA 7.88 7.08 8.67 0 1.01Without style the compressions agree: both explain 0.67 of the confounding score, and both 2SLS medians are \$2.9 with a median absolute error of \$0.21. At a style ratio of 0.25 PCA still mostly works ($R^2$ 0.61, error \$0.74 against CCA's \$0.29). At 0.5 its proxies explain 0.02 and its estimates scatter (error \$2.56), and from 1 upward its median sits between \$8.4 and \$9.6, the naive answer. CCA's median stays between \$2.9 and \$3.1 at every level (error \$0.14 to \$0.35, $R^2$ 0.65 to 0.67), and its 90% Wald intervals cover the truth in 92% of the 160 campaigns, so treating the pool-fitted maps as fixed costs nothing visible. Proxies as covariates sit at \$4.0 to \$4.2 throughout: the Proposition 4 bias comes from proxy noise, which style does not change.
PCA breaks earlier than Proposition 2's threshold, which is the condition for losing all of $L$. Intent and loyalty are the weakest shared signals here (about a half and a quarter of screen time's variance), so they are the first pushed out of the top three, and a compression can stay complete for the wrong factor.
The Bayesian fits agree. With CCA proxies the posterior means run from \$2.7 to \$3.8, and one of the eight 90% intervals (style ratio 2, \$3.17 to \$4.44) misses the truth, as 90% intervals will now and then. With PCA proxies, from a ratio of 1 upward every mean lies between \$7.9 and \$8.7 and every interval lies above break-even, with zero divergences and r_hat at most 1.03 throughout.
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2), gridspec_kw={"width_ratios": [1.5, 1]})
xs = np.arange(len(RATIOS))
ax = axes[0]
for col_name, col, off in [("naive", MUTED, -0.15), ("2SLS PCA", ORANGE, -0.05), ("OLS+CCA", PURPLE, 0.05),
("2SLS CCA", BLUE, 0.15)]:
g_ = sweep.groupby("ratio")[col_name]
med, lo, hi = g_.median().values, g_.quantile(0.1).values, g_.quantile(0.9).values
ax.errorbar(xs + off, med, yerr=[med - lo, hi - med], fmt="o-", color=col, capsize=2,
label={"naive": "naive", "2SLS PCA": "proximal 2SLS, PCA", "OLS+CCA": "CCA proxies as covariates",
"2SLS CCA": "proximal 2SLS, CCA"}[col_name])
for nm, col, mk in [("PCA", ORANGE, "s"), ("CCA", BLUE, "D")]:
b_ = bayes_pts[bayes_pts.proxies == nm]
ax.scatter(xs + (0.25 if nm == "CCA" else -0.25), b_.tau, marker=mk, facecolor="white", edgecolor=col,
zorder=5, label=f"Bayes, {nm} (one campaign)")
ax.axhline(TAU, color=INK, lw=1.5)
ax.axhline(BREAK_EVEN, color=RED, ls=":", lw=1.5)
ax.text(len(RATIOS) - 0.6, BREAK_EVEN + 0.2, "break-even", color=RED, fontsize=8, ha="right")
ax.set_ylim(-4, 14)
ax.set_xticks(xs, [f"{r_:g}" for r_ in RATIOS])
ax.set_xlabel("style variance / strongest shared signal")
ax.set_ylabel("estimated effect ($), median and 10-90%")
ax.legend(frameon=False, fontsize=8, ncol=3, loc="lower center")
ax.set_title("Estimates as each log's own style grows")
ax = axes[1]
for nm, col in [("PCA", ORANGE), ("CCA", BLUE)]:
ax.plot(xs, sweep.groupby("ratio")[f"R2 {nm}"].median().values, "o-", color=col, label=f"{nm} proxies W~")
ax.set_xticks(xs, [f"{r_:g}" for r_ in RATIOS])
ax.set_xlabel("style variance / strongest shared signal")
ax.set_ylabel("R² of 6 U1 + 3 U2 from W~")
ax.set_ylim(0, 1)
ax.legend(frameon=False)
ax.set_title("How much of the confounder the proxies carry")
plt.show();

Figure 3 shows the transition (left) and its cause (right): the share of the confounder in PCA's app-side proxies collapses between style ratios of 0.25 and 0.5, while CCA's stays flat.
F · Two ways to break the CCA proxies
F1 · Fitting the maps on the analysis sample
Why not fit CCA on the 3,000 analysis customers themselves? Theorem 2 says why not. Maps fitted on a disjoint pool are fixed functions of the logs, and conditional independence survives fixed maps, so exclusion holds for the proxies exactly. Maps fitted on the analysis rows are chosen to make these rows' $\tilde Z$ and $\tilde W$ agree, and in 150 dimensions part of that agreement is chance agreement between the two logs' noise, so the instrument ends up correlated with the error in $\tilde W$. The paper's example ($n = 400$, $p = 60$) gives a partial correlation of the proxies given $(L, X)$ of $+0.64$ in-sample and $-0.02$ from a pool. We measure the same quantity, averaged over the three pairs, and the 2SLS estimate for samples of 500 and 3,000 (20 campaigns each), and fit the Bayesian model to one 500-customer campaign both ways.
def partial_corr(a, b, C_):
Cd = np.column_stack([np.ones(len(C_)), C_])
ra = a - Cd @ np.linalg.lstsq(Cd, a, rcond=None)[0]
rb = b - Cd @ np.linalg.lstsq(Cd, b, rcond=None)[0]
return np.corrcoef(ra, rb)[0, 1]
ins_rows = []
ins_example = {}
t0 = time.time()
for n_a in (500, 3000):
for rep in range(N_REP):
r_ = np.random.default_rng([RANDOM_SEED, 7, n_a, rep])
pl = simulate(LOGS, N_POOL_SWEEP, STYLE, r_, labelled=False)
an = simulate(LOGS, n_a, STYLE, r_)
pz_, pw_ = Prep(pl["Mz"], pl["X"]), Prep(pl["Mw"], pl["X"])
tz_, tw_, _ = ridge_cca(pz_(pl["Mz"], pl["X"]), pw_(pl["Mw"], pl["X"]), LAM, D)
qz_, qw_ = Prep(an["Mz"], an["X"]), Prep(an["Mw"], an["X"]) # fitted on the analysis rows
rz_a, rw_a = qz_(an["Mz"], an["X"]), qw_(an["Mw"], an["X"])
uz_, uw_, _ = ridge_cca(rz_a, rw_a, LAM, D)
sets_ = {"pool": (pz_(an["Mz"], an["X"]) @ tz_, pw_(an["Mw"], an["X"]) @ tw_),
"in-sample": (rz_a @ uz_, rw_a @ uw_)}
Cl = np.column_stack([an["L"], an["X"]])
for nm, (zt_, wt_) in sets_.items():
ins_rows.append({"n": n_a, "rep": rep, "fit": nm,
"partial corr": np.mean([partial_corr(zt_[:, j], wt_[:, j], Cl) for j in range(D)]),
"estimate": estimates(zt_, wt_, an["Y"], an["A"], an["X"])["proximal 2SLS"][0]})
if n_a == 500 and rep == 0:
ins_example[nm] = (an, zt_, wt_)
ins = pd.DataFrame(ins_rows)
print(f"{len(ins) // 2} campaigns in {time.time() - t0:.0f} s")
print(ins.groupby(["n", "fit"]).agg(partial_corr=("partial corr", "mean"), median_est=("estimate", "median"),
q10=("estimate", lambda v: v.quantile(0.1)),
q90=("estimate", lambda v: v.quantile(0.9))).round(2).to_string())
for nm, (an, zt_, wt_) in ins_example.items():
f_, _ = fit_prox(suff_stats(an["Y"], an["A"], an["X"], zt_, wt_, an["Y"].mean(), an["Y"].std()), RANDOM_SEED)
q_ = np.quantile(f_.posterior["tau"], [0.05, 0.5, 0.95])
dv_, rh_, _ = diag(f_)
print(f"one 500-customer campaign, maps fitted on the {nm:9s}: Bayesian posterior median {q_[1]:.2f}, "
f"90% interval [{q_[0]:.2f}, {q_[2]:.2f}]; divergences {dv_}, max r_hat {rh_:.3f}")
40 campaigns in 5 s
partial_corr median_est q10 q90
n fit
500 in-sample 0.41 4.63 3.17 5.20
pool 0.01 3.34 2.17 4.44
3000 in-sample 0.08 3.37 2.88 3.97
pool 0.00 3.18 2.77 3.72one 500-customer campaign, maps fitted on the pool : Bayesian posterior median 3.43, 90% interval [1.93, 4.97]; divergences 0, max r_hat 1.003
one 500-customer campaign, maps fitted on the in-sample: Bayesian posterior median 4.82, 90% interval [3.37, 6.24]; divergences 0, max r_hat 1.004
From the pool, the partial correlation is 0.00 to 0.01, as exclusion requires; in-sample it is 0.41 with 500 customers and 0.08 with 3,000. With 500 customers the in-sample median is \$4.63 (10-90%: \$3.17 to \$5.20) against \$3.34 from the pool (\$2.17 to \$4.44), pulled toward the naive answer. With 3,000 the gap shrinks to \$3.37 against \$3.18, as 150 columns become a smaller share of the rows. One small campaign shows how it looks in practice: \$3.43 (90% interval \$1.93 to \$4.97) with pool maps and \$4.82 (\$3.37 to \$6.24) in-sample, an interval that excludes the truth with clean diagnostics. Small campaigns, where reusing one's own rows is most tempting, suffer most.
F2 · How many directions to keep
Completeness needs at least as many proxies as $L$ has dimensions (Proposition 1(c)). With fewer, the estimator adjusts for the part of the confounder the proxies carry and leaves the rest. Each extra direction is a pair of noise columns, one more endogenous regressor with an irrelevant instrument. We fit CCA up to $d = 6$ on 20 campaigns and run 2SLS with the first $d$ directions on each side.
D_GRID = range(1, 7)
d_rows = []
t0 = time.time()
for rep in range(N_REP):
r_ = np.random.default_rng([RANDOM_SEED, 11, rep])
pl = simulate(LOGS, N_POOL_SWEEP, STYLE, r_, labelled=False)
an = simulate(LOGS, N_ANA, STYLE, r_)
pz_, pw_ = Prep(pl["Mz"], pl["X"]), Prep(pl["Mw"], pl["X"])
tz_, tw_, _ = ridge_cca(pz_(pl["Mz"], pl["X"]), pw_(pl["Mw"], pl["X"]), LAM, max(D_GRID))
az_, aw_ = pz_(an["Mz"], an["X"]) @ tz_, pw_(an["Mw"], an["X"]) @ tw_
for d_ in D_GRID:
d_rows.append({"d": d_, "rep": rep,
"estimate": estimates(az_[:, :d_], aw_[:, :d_], an["Y"], an["A"], an["X"])["proximal 2SLS"][0]})
dsw = pd.DataFrame(d_rows)
g_ = dsw.groupby("d")["estimate"]
print(f"{N_REP} campaigns in {time.time() - t0:.0f} s")
print(pd.DataFrame({"median": g_.median(), "q10": g_.quantile(0.1), "q90": g_.quantile(0.9),
"median |error|": (dsw.estimate - TAU).abs().groupby(dsw.d).median()}).round(2).to_string())
20 campaigns in 2 s median q10 q90 median |error| d 1 8.84 8.47 9.46 5.84 2 4.10 3.77 4.57 1.10 3 3.09 2.83 3.35 0.20 4 3.17 1.78 4.94 0.53 5 3.35 2.34 6.63 0.64 6 3.35 1.77 4.87 1.00
One direction gives \$8.84, the naive answer. The strongest thing the two logs share is screen time, which is harmless, so the single proxy is a good measurement of the wrong factor. Two directions give \$4.10: screen time and intent are in, loyalty is out, and its share of the confounding remains. Three give \$3.09, with a 10-90% range of \$2.83 to \$3.35. Beyond three the medians stay near the truth (\$3.17 to \$3.35), but the 10-90% range grows six to eight times wider, because the extra proxy coefficients are not identified and their noise leaks into $\tau$. The number of proxies acts as a regularisation level, and the held-out scree of part B, which used no labels, picked the right value.
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
ax = axes[0]
for k_, (n_a, nm) in enumerate([(500, "pool"), (500, "in-sample"), (3000, "pool"), (3000, "in-sample")]):
v_ = ins[(ins.n == n_a) & (ins.fit == nm)].estimate.values
ax.scatter(np.full(len(v_), k_) + rr.uniform(-0.12, 0.12, len(v_)), v_, s=14,
color=BLUE if nm == "pool" else ORANGE, alpha=0.8)
ax.plot([k_ - 0.25, k_ + 0.25], [np.median(v_)] * 2, color=INK, lw=2)
ax.axhline(TAU, color=INK, lw=1)
ax.axhline(BREAK_EVEN, color=RED, ls=":", lw=1.5)
ax.set_xticks(range(4), ["n = 500\npool", "n = 500\nin-sample", "n = 3,000\npool", "n = 3,000\nin-sample"])
ax.set_ylabel("proximal 2SLS estimate ($)")
ax.set_title("Where the CCA maps are fitted")
ax = axes[1]
med, lo, hi = g_.median().values, g_.quantile(0.1).values, g_.quantile(0.9).values
ax.errorbar(list(D_GRID), med, yerr=[med - lo, hi - med], fmt="o-", color=BLUE, capsize=3)
ax.axhline(TAU, color=INK, lw=1)
ax.axhline(BREAK_EVEN, color=RED, ls=":", lw=1.5)
ax.axvspan(2.6, 3.4, color=LIGHT)
ax.set_xlabel("number of CCA proxies per side, d (dim L = 3)")
ax.set_ylabel("proximal 2SLS estimate ($), median, 10-90%")
ax.set_ylim(-4, 14)
ax.set_title("How many directions to keep")
plt.show();

Figure 4 shows both failures: in-sample maps (orange, left) push small-campaign estimates toward break-even, and the estimate reaches the truth as the third direction enters, then loses precision (right).
G · What this means for ad-lift and MMM work
Targeted exposure is the normal case in digital media: retargeting, platform-optimised delivery and addressable TV all choose people by signals of intent. A holdout experiment remains the cleanest answer and should anchor the analysis when one exists (E103). When none does, proximal inference can remove a confounder nobody measured, and many advertisers already hold its two records: what the targeting system could see before the campaign (browsing, search, earlier ad engagement) on the treatment side, and first-party pre-campaign behaviour the platform never sees (loyalty-app or point-of-sale records) on the outcome side. The exclusion restrictions fail in recognisable ways. If the retailer uploaded purchase-based audiences to the platform, the app log has become a targeting input; if the browsing log runs past the campaign start, it contains the ad's own effects.
Three working rules follow for the step between the logs and the estimator. Compress by what the two records share given the covariates; ranking by variance is what failed here, where the confounder was under 2% of each log's variance. Fit the compression on customers who play no part in the estimate, such as a previous quarter or customers outside the eligible population, logged by the same systems. And check before estimating: held-out canonical correlations choose the number of proxies, and cross-log canonical correlations given exposure and covariates show whether the proxies can act as instruments. Then put the proxies inside a bridge, whose posterior an MMM can take as a calibration prior for a targeted channel.
Summary
- A naive regression on targeted exposure overstated the effect almost threefold. Adjusting for three covariates gave \$8.50 per exposed customer against a true \$3, on the wrong side of the \$5.25 break-even. Limit: one simulated world, with a linear outcome and a constant effect.
- PCA of a rich log kept its style and lost the confounder. With style four times the strongest shared signal, the PCA proxies explained 0.00 of intent and loyalty, and proximal 2SLS returned \$8.40. Across 160 simulated campaigns PCA matched CCA without style and failed from a style ratio of 0.5 upward, because the confounder's directions were the weakest shared ones.
- X-conditional ridge CCA on an unlabeled pool recovered what the logs hold about the confounder. Three directions (held-out canonical correlations 0.84, 0.73, 0.59, then zero) explained 0.68, 0.55 and 0.85 of intent, loyalty and screen time, as much as the best linear summary of all 150 columns, at every style level; the ridge made no visible difference. Limit: Gaussian linear-factor features, the regime of Theorem 3.
- Proxies belong inside a bridge. As covariates the CCA proxies left about \$1 of bias at every style level; proximal 2SLS gave \$3.17 (se 0.40), and its 90% intervals covered the truth in 92% of 160 campaigns.
- The Bayesian proximal IV matched 2SLS, and it was confidently wrong with empty proxies. On sufficient statistics, compiled once with nutpie: \$3.18 (sd 0.40), no divergences, r_hat at most 1.004. With PCA proxies the posterior was \$8.46 (sd 0.45), because the priors resolve an unidentified bridge toward least squares. Cross-log canonical correlations of 0.05 or less, against 0.56 or more for CCA, flag it without labels.
- Fitting the maps on the analysis sample broke exclusion. The proxies' partial correlation given the latent factors rose from 0.01 to 0.41 with 500 customers, and the median estimate from \$3.34 to \$4.63; with 3,000 customers the damage was small (0.08, \$3.37 against \$3.18).
- The number of proxies sets completeness and precision. One proxy captured only the harmless shared factor (\$8.84), two missed loyalty (\$4.10), three were right (\$3.09), and more widened the 10-90% range from about \$0.5 to \$3 or more. Limit: no forest, no conditional effects, no censoring and no treatment bridge, the part of the paper's second stage we left out.
Try it yourself
- Drop the conditioning on X. Replace the residualisation in
Prepby plain standardisation, and multiply the loadings"X"inmake_logsby three. How many of the first six canonical directions does unconditional CCA spend on the covariates (the paper's Corollary 1), and what happens to proximal 2SLS with $d = 3$ and with $d = 6$? - Break exclusion by design. Let the platform target on an audience built from the app log:
add 0.5 times the mean of the first ten columns of $M_w$ to the exposure logit in
simulate. No compression can repair this. Watch the CCA estimate move, and check whether the relevance check or the held-out scree notices anything. - Let the effect vary. Make the effect $3 + 2x_1$, and add $A \times x_1$ to both the regressors and the instruments of the bridge, with a matching coefficient in the PyMC model. Does the Bayesian bridge recover the slope with CCA proxies, and what does PCA do to it? This is the first step toward the conditional effects that the paper's forest estimates.
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 67 s