---
title: "Conditional Independence Testing, in Pictures"
pubDate: 2026-12-02T00:00:00.000Z
tags:
  - Statistics
  - Math
  - Data
math: true
image: /images/blog/generalised-covariance-measure/featured.png
---

import GcmFigure from '../../components/GcmFigure.astro';
import LoopAnimation from '../../components/LoopAnimation.astro';

## TL;DR
To test whether $X$ and $Y$ are linked once $Z$ is known, replace both by their residuals given $Z$, $\varepsilon_X$ and $\varepsilon_Y$, multiply them and average the products. Divided by its standard error, that average is close to standard normal if $X$ and $Y$ are independent given $Z$. The idea is that of the partial correlation, whose test goes back to [Fisher (1924)](http://hdl.handle.net/2440/15182). In simulated factory data, temperature and scrap look unrelated: the best line through all orders is flat. Replace scrap by $\varepsilon_Y$, then temperature by $\varepsilon_X$, and the same orders show a clear trend.

## The question

A factory makes footballs, volleyballs and basketballs. Some balls come off the line below standard and are thrown away: the scrap. For each order we know its ball type $Z$, the temperature at one machine, M2, which we call $X$, and the share of balls thrown away, $Y$. The factory and its 90 orders, 30 per ball type, are simulated.

The ball type affects both: each type runs at its own temperature and has its own scrap rate. That alone links temperature and scrap, but it is no news, and no one can change the ball type of an order. The question is whether temperature tells us anything about scrap beyond the ball type:

$$
X \perp\!\!\!\perp Y \mid Z \;?
$$

<GcmFigure name="graph" />

*The ball type drives both temperature and scrap. Is there more between them?*

## The answer first

Let $f(z) = \mathbb E[Y \mid Z = z]$ be the average scrap and $g(z) = \mathbb E[X \mid Z = z]$ the average temperature of ball type $z$. The residuals are what is left of scrap and temperature once the ball type is taken out:

$$
\varepsilon_Y = Y - f(Z), \qquad \varepsilon_X = X - g(Z).
$$

In the data, $f$ and $g$ are estimated, here by the averages of each type, $\hat f$ and $\hat g$. Type averages are the simplest regression on $Z$; any regression that predicts $X$ and $Y$ from $Z$ will do, which matters once $Z$ holds many columns (more [at the end](#when-the-ball-type-is-not-enough)). For order $i$, that gives $\varepsilon_{Y,i} = Y_i - \hat f(Z_i)$ and $\varepsilon_{X,i} = X_i - \hat g(Z_i)$. The test multiplies the two residuals, and divides the mean of the products by its standard error:

$$
R_i = \varepsilon_{X,i}\,\varepsilon_{Y,i}, \qquad T = \frac{\sqrt{n}\,\bar R}{\hat\sigma}, \qquad \bar R = \frac1n\sum_{i=1}^n R_i, \qquad \hat\sigma^2 = \frac1n\sum_{i=1}^n \big(R_i - \bar R\big)^2.
$$

Up to the denominator, $T$ is the covariance of $\varepsilon_X$ and $\varepsilon_Y$. The rest of this post builds it up in pictures, from $X$ against $Y$ to $\varepsilon_X$ against $\varepsilon_Y$, one axis at a time: first $Y$ becomes $\varepsilon_Y$, then $X$ becomes $\varepsilon_X$.

## Ignoring the ball type: $X$ against $Y$

Plot temperature against scrap for all 90 orders:

<GcmFigure name="raw" />

*All orders, both variables standardised.*

A round cloud, the kind two independent normal variables give. Draw the best straight line through it:

<GcmFigure name="raw-line" />

*The best straight line through all orders.*

It is flat, with slope +0.02. The same statistic with the overall averages in place of the type averages is $T = 0.2$. Nothing to see.

Colour the same orders by ball type:

<GcmFigure name="types" />

*The same orders, coloured by ball type.*

The types sit in different places. Footballs run hot and scrap little, basketballs run cool and scrap more, volleyballs lie in between. Across types, hotter means less scrap. Within each colour, the orders rise from left to right: hotter means more scrap. The two cancel, and the flat line of the first picture is what is left.

## Step 1: replace $Y$ by $\varepsilon_Y$

Mark each type's average scrap, $\hat f(z)$, with a dashed line in its colour:

<GcmFigure name="type-scrap" />

*The dashed lines mark each type's average scrap, $\hat f(z)$.*

Footballs scrap least, basketballs most. That difference is what the ball type alone explains, so take it out: move each type's line to zero, and its orders with it.

<GcmFigure name="shift-y" />

*Each arrow moves a type's line, and all its orders, to zero: footballs up, basketballs down.*

Every order moves by its type's average: its scrap $Y_i$ becomes $\varepsilon_{Y,i} = Y_i - \hat f(Z_i)$.

<GcmFigure name="y-moved" />

*$X$ against $\varepsilon_Y$.*

The colours now share one height. Within each colour, the orders still rise from left to right; nothing within a type has moved. Draw the best line through all orders again:

<GcmFigure name="y-adjusted" />

*$X$ against $\varepsilon_Y$, with the best line through all orders.*

It rises, with slope +0.42. Three reasons why $\varepsilon_Y$ is the right thing to put on the y-axis:

- **It is what is new.** $\hat f(Z_i)$ is the scrap we expect from the ball type alone, known before anyone looks at the temperature. $\varepsilon_{Y,i}$ is the surprise: how much more or less order $i$ scraps than its type usually does. "Does temperature tell us anything about scrap beyond the ball type?" becomes "Does temperature predict $\varepsilon_Y$?"
- **Without a link, the cloud is flat.** If $X \perp\!\!\!\perp Y \mid Z$, the temperature adds nothing to what the ball type says about scrap: $\mathbb E[Y \mid X, Z] = \mathbb E[Y \mid Z] = f(Z)$. So $\varepsilon_Y$ averages to zero at every temperature, $\mathbb E[\varepsilon_Y \mid X, Z] = 0$, and the best line is flat up to noise, whatever the ball types do. In $X$ against $Y$ there is no such guarantee: the differences between types alone can tilt the line either way, or, as here, hide a trend. Its slope says nothing either way.
- **Only the relation within each type is left.** The covariance of $X$ with $\varepsilon_Y$ is the average of the covariances within each type: $\operatorname{Cov}(X, \varepsilon_Y) = \mathbb E\big[\operatorname{Cov}(X, Y \mid Z)\big]$. The pull between types is gone.

## Step 2: replace $X$ by $\varepsilon_X$

The colours now share one height, but still sit side by side along the temperature axis. Mark each type's average temperature, $\hat g(z)$:

<GcmFigure name="type-temperature" />

*The dashed lines mark each type's average temperature, $\hat g(z)$.*

Move each type's line to zero, and its orders with it:

<GcmFigure name="shift-x" />

*Each arrow moves a type's line, and all its orders, to zero: footballs left, basketballs right.*

Every order's temperature $X_i$ becomes $\varepsilon_{X,i} = X_i - \hat g(Z_i)$:

<GcmFigure name="both-moved" />

*$\varepsilon_X$ against $\varepsilon_Y$.*

The three colours merge into one cloud, centred on zero, that runs from bottom left to top right. The best line through it:

<GcmFigure name="both-line" />

*$\varepsilon_X$ against $\varepsilon_Y$, with the best line.*

It rises steeply, with slope +0.73: an order that runs hotter than usual for its ball type scraps more than usual for its ball type. That is the finding, and the first picture hid it.

Step 1 alone already gives a flat line without a link. Step 2 is still worth taking:

- **It removes noise.** How far the types sit apart in temperature has nothing to do with $\varepsilon_Y$. That spread flattens the line, from +0.73 to +0.42, and adds noise to the products.
- **Errors in $\hat f$ stop mattering.** $\hat f$ is estimated, not known. Whatever error it carries is a function of the ball type, and $\varepsilon_X$ is uncorrelated with every function of the ball type. So an error in $\hat f$ alone doesn't bias $\bar R$, nor does one in $\hat g$ alone; only the two errors multiplied do.
- **It is the familiar regression.** The slope of $\varepsilon_Y$ on $\varepsilon_X$ is the coefficient of temperature in a linear regression of scrap on temperature and ball type ([Frisch–Waugh–Lovell](https://en.wikipedia.org/wiki/Frisch%E2%80%93Waugh%E2%80%93Lovell_theorem)).

Last, the products $R_i = \varepsilon_{X,i}\,\varepsilon_{Y,i}$ that $T$ averages. Their sign depends only on the quadrant an order lies in:

<GcmFigure name="both-adjusted" />

*The products $R_i$ are positive in the green quadrants, negative in the red ones.*

An order in the top right is hotter and scrappier than its type's average, one in the bottom left cooler and cleaner: both give a positive product. Orders in the other two quadrants give negative ones. Without a link, the quadrants would balance and $\bar R$ would be near zero. Here most orders sit in the green ones.

## From an average to a decision

Without a link, the products average to zero. That follows from step 1: $\varepsilon_Y$ averages to zero at every temperature and ball type, and $\varepsilon_X$ depends on nothing else, so

$$
\mathbb E[\varepsilon_X\,\varepsilon_Y] = \mathbb E\big[\varepsilon_X\;\mathbb E[\varepsilon_Y \mid X, Z]\big] = 0.
$$

The mean $\bar R$ then scatters around zero, by an amount that shrinks as orders accumulate. The central limit theorem says by how much: $\sqrt n\,\bar R$ is close to normal, with the standard deviation of a single product, $\sigma$. Dividing by its estimate $\hat\sigma$ is the quotient in $T$, and it puts every test on the same scale:

$$
T \approx \mathcal N(0, 1) \quad \text{if } X \perp\!\!\!\perp Y \mid Z.
$$

That gives the decision rule. A standard normal lands beyond $\pm 1.96$ only 5% of the time, so we reject independence at the 5% level if $|T| > 1.96$. The p-value is $p = 2\,\big(1 - \Phi(|T|)\big)$, with $\Phi$ the standard normal distribution function.

<GcmFigure name="null" />

*The distribution of $T$ under independence. The shaded tails beyond ±1.96 hold 5%.*

Ignoring the ball type, the statistic is $T = 0.2$:

<GcmFigure name="null-raw" />

*$T$ ignoring the ball type.*

It lies in the middle of the bell: no reason to doubt independence. Given the ball type, the statistic is $T = 5.5$:

<GcmFigure name="null-both" />

*$T$ given the ball type.*

It lies far out in the tail, where a standard normal lands less than once in ten million draws.

## When the ball type is not enough

Three ball types make $\hat f$ and $\hat g$ easy: an average per type. In practice $Z$ holds more, such as the material, the season and the machine settings, some of it continuous, often dozens of columns. There is no average per combination of all of them, so the averages become regressions: any model that predicts $X$ or $Y$ from $Z$, such as a random forest or gradient boosting. The regressions are fitted on one part of the data and give residuals on another, so that a model that memorises its training orders doesn't leave residuals that are too small. Everything after the residuals stays as above: their products, $T$ and the decision rule.

With any regression in place of the averages, the test is known as the generalised covariance measure. [Shah and Peters](https://arxiv.org/abs/1804.07203) work out when $T$ stays close to standard normal: as long as the errors of $\hat f$ and $\hat g$, multiplied, shrink faster than $1/\sqrt n$. That is the second reason for step 2, in general: each regression only has to be fairly good, because their errors multiply. With three ball types and 30 orders each, the type averages are good enough.

### Some assumption is needed

The same paper shows that a condition of this kind can't be avoided. A test keeps its level if, without a link, it rejects at most 5% of the time; it has power if, with a link, it rejects more often than that. Once $Z$ is continuous, a test that keeps its level for every distribution without a link has no power against any distribution with one.

The reason is that $Z$ can hide anything. Say $Z$ is the time an order starts, to the second, and temperature and scrap both follow a pattern that flips every few seconds. Given $Z$, they are independent: knowing the second, the pattern is known. But 90 orders never land on the same second twice, so no regression can learn the pattern from them. The residuals keep it, they move together, and $T$ is large, although there is no link given $Z$. A test that is never fooled by such a pattern, however fine, must also ignore every real link, because the data can't tell the two apart. So every test rests on an assumption about $Z$; here, that the regressions can learn $f$ and $g$.

## All steps at once

<LoopAnimation
  name="gcm-shift"
  description="The 90 orders, temperature against scrap, in one colour, with a flat best line. They take on the colours of their ball types. A dashed line appears at each type's average scrap, and each type's orders move up or down with it to zero; the best line tilts up. Then a dashed line appears at each type's average temperature, and the orders move left or right with it to zero. The three colours merge into one cloud, and the best line ends steep, with slope +0.73."
/>

*From $X$ against $Y$ to $\varepsilon_X$ against $\varepsilon_Y$: colour by ball type, move each type's scrap to zero, then its temperature. The best line is refitted as the orders move.*

## Caveats

$T$ measures one thing: the covariance of $\varepsilon_X$ and $\varepsilon_Y$, averaged over all orders. A link whose products cancel or thin out in that average goes unseen. That comes from the covariance, not from conditioning on $Z$: any test built on a covariance or a straight line shares it, the plain correlation test of the first picture included. The first three caveats are links of that kind, each drawn with a flat best line.

### U-shapes

<GcmFigure name="u-shape" />

If orders that run much hotter or much cooler than usual both scrap more, the products in the four quadrants cancel. $T$ sees only the straight-line part of a link.

### Links that depend on $Z$

Another set of orders, as residuals, with a flat best line:

<GcmFigure name="by-type-flat" />

*Simulated residuals with a flat best line. $T$ finds nothing.*

The points form an X, not a round cloud. Colour them by ball type:

<GcmFigure name="by-type" />

*The same residuals by ball type.*

Hotter means more scrap for footballs and less for basketballs, and the products cancel across types. If temperature matters for footballs alone, the other types add products without signal, and the link thins out. $\hat f$ and $\hat g$ take the ball type out of each variable on its own; nothing in $T$ lets the link between them change with the ball type.

### Links that depend on another signal

This post keeps to one signal and one kind of scrap. A real line records many signals, scrap has several reasons, and a test like this one takes one signal at a time. The same X can hide behind a flat line:

<GcmFigure name="by-signal-flat" />

*Simulated residuals with a flat best line.*

This time the colours that split it are not the ball type but another signal, whether the line runs fast:

<GcmFigure name="by-signal" />

*The same residuals, by line speed.*

If temperature raises scrap when the line runs fast and lowers it when it runs slow, the products cancel, as for the ball types. If it raises scrap only when the line runs fast, slow orders thin the link out. A test of temperature alone sees neither, and neither does a test of speed alone.

### A link, not a cause

A large $T$ says that temperature and scrap are linked beyond the ball type, not how. Something unobserved, $U$, such as a raw-material batch that heats the machine and weakens the balls, links them as well:

<GcmFigure name="graph-u" />

*An unobserved $U$ drives both temperature and scrap.*

It gives the same pictures and the same $T$ as a direct effect of temperature on scrap. The test can't tell the two apart; only knowledge of the process, or an experiment, can.

### Significant is not relevant

$T$ grows with $\sqrt n$, so with enough orders even a tiny link gives a large $T$. A link that raises scrap by 0.1 percentage points can be real and significant, and still too small to act on. How much it matters is a question of size, not of $T$: the slope of $\varepsilon_Y$ on $\varepsilon_X$, in scrap per degree, says how much scrap a degree costs, and belongs next to $T$.

### Independent orders

The step to a standard normal assumes that the products of different orders are independent. Orders that follow each other in time, sharing a shift or a batch, are not, and $\hat\sigma$ then understates the noise, so $T$ comes out too large. A standard error computed over whole shifts or batches rather than single orders accounts for that. [Scrap Hypotheses, Evidence at a Glance](/post/scrap-conditional-independence) runs the test on many signals at once, next to feature importance.
