Skip to main content

Canary variable

Causes, samples and populations
Method or technique
Advanced
Like the canary in the coal mine, a canary variable is something with a known distribution that was not adjusted for in your model.
Published

November 9, 2026

Modified

November 13, 2026

Entry #117 in Andrew Gelman’s Handy Statistical Lexicon. Original discussion: Checking survey representativeness by looking at canary variables.

Filed under Causes, samples and populations · Method or technique · Advanced.

Related terms: nonresponse bias, survey weighting, validation variable.

Source check: ✓ The explanation was checked against the source.

What it is

Miners once carried canaries underground. If the bird stopped singing, there was gas. For surveys, a canary variable is a quantity whose population distribution you know from an outside source, such as census figures, election returns or administrative records, but which you deliberately did not use in weighting or modeling. After adjusting the survey, estimate the canary. If the adjusted estimate is off, your adjustment hasn’t fixed the non-representativeness, and the estimates you actually care about are probably off too.

Why it matters

Weighting or MRP corrects a survey on the variables you adjust for. By construction, it reproduces their population distribution perfectly, so checking them tells you nothing. The real risk is selection on variables you didn’t adjust for. A canary is an honest out-of-sample check: it can fail, and when it does, it warns you about hidden bias.

How it works

Let an unobserved trait \(U\) affect both survey response and the outcome of interest. Adjusting on demographics \(X\) removes only the part of the bias explained by \(X\). A canary \(C\) that is correlated with \(U\) will also show residual bias after adjustment. Across surveys, the canary’s error tracks the target’s error, so a large canary miss is a red flag.

Simulated example

Simulate 200 surveys. Response depends on demographics, which we adjust for, and on a hidden trait, which we can’t. For each survey, compare the canary’s error after weighting with the target estimate’s error.

Show simulation code

The R version uses base R, and the Python version uses NumPy and Matplotlib. Where the simulation draws random numbers, each language draws its own, so exact numbers differ slightly but show the same pattern. The numbered markers in the R code are explained under it.

import {rng, range, mean, sum, cor, fmt, debounce} from "../js/stats.js"

viewof hidden = debounce(Inputs.range([0, 2], {value: 1, step: 0.05, label: "Strength of hidden selection"}))
viewof canaryLink = debounce(Inputs.range([0, 1], {value: 0.7, step: 0.05, label: "Canary's correlation with the hidden trait"}))
viewof seed = debounce(Inputs.range([1, 500], {value: 117, step: 1, label: "Random seed"}))

canary = {
  const r = rng(seed);
  return range(200).map(s => {
    const h = hidden * r.uniform(0.2, 1.2);            // selection strength varies by survey
    const resp = [];
    for (let i = 0; i < 4000; i++) {
      const old = r.bernoulli(0.5), u = r.normal();
      const target = r.bernoulli(1 / (1 + Math.exp(-(-0.2 + 0.4 * old + 0.8 * u))));
      const can = r.bernoulli(1 / (1 + Math.exp(-(canaryLink * 1.5 * u + 0.3 * old))));
      const pResp = 1 / (1 + Math.exp(-(-2 + 0.8 * old + h * u)));
      if (r() < pResp) resp.push({old, target, can});
    }
    // Weight to the known 50/50 age split.
    const wOld = 0.5 / mean(resp.map(d => d.old)), wYoung = 0.5 / (1 - mean(resp.map(d => d.old)));
    const w = resp.map(d => d.old ? wOld : wYoung), W = sum(w);
    const est = k => sum(resp.map((d, i) => w[i] * d[k])) / W;
    return {canaryErr: est("can") - 0.5 - 0.0, targetErr: est("target"), raw: resp};
  });
}
truth = {
  // Population values computed by simulation without selection.
  const r = rng(seed + 1000);
  let t = 0, c = 0; const N = 40000;
  for (let i = 0; i < N; i++) { const old = r.bernoulli(0.5), u = r.normal();
    t += r.bernoulli(1 / (1 + Math.exp(-(-0.2 + 0.4 * old + 0.8 * u)))); c += r.bernoulli(1 / (1 + Math.exp(-(canaryLink * 1.5 * u + 0.3 * old)))); }
  return {target: t / N, canary: c / N};
}
pts = canary.map(d => ({canaryErr: d.canaryErr + 0.5 - truth.canary, targetErr: d.targetErr - truth.target}))

Plot.plot({
  ariaLabel: "Canary variable: simulation chart",
  ariaDescription: "Horizontal axis: Error in the canary after weighting (known truth). Vertical axis: Error in the target estimate. The chart updates with the controls above it, and the summary below the charts states the result in words.",
  height: 300,
  grid: true,
  x: {label: "Error in the canary after weighting (known truth)"},
  y: {label: "Error in the target estimate"},
  marks: [Plot.dot(pts, {x: "canaryErr", y: "targetErr", r: 3, fill: "#2166ac", fillOpacity: 0.6}), Plot.linearRegressionY(pts, {x: "canaryErr", y: "targetErr", stroke: "#d6604d"}), Plot.ruleX([0]), Plot.ruleY([0])]
})
# Canary variable: a known quantity that warns of hidden selection.
1hidden <- 1 # strength of hidden selection
canary_link <- 0.7 # canary's correlation with the hidden trait
2set.seed(117)

3population <- function(n) {
  old <- rbinom(n, 1, 0.5)
  u <- rnorm(n) # u: trait we can't adjust for
  data.frame(old, u,
    target = rbinom(n, 1, plogis(-0.2 + 0.4 * old + 0.8 * u)),
    canary = rbinom(n, 1, plogis(canary_link * 1.5 * u + 0.3 * old))
  )
}
truth <- colMeans(population(40000)[, c("target", "canary")])

errors <- t(replicate(200, {
  h <- hidden * runif(1, 0.2, 1.2) # selection strength varies by survey
  d <- population(4000)
4  resp <- d[runif(4000) < plogis(-2 + 0.8 * d$old + h * d$u), ]
5  w <- ifelse(resp$old == 1, 0.5 / mean(resp$old), 0.5 / mean(1 - resp$old))
  c(
    canary = weighted.mean(resp$canary, w) - truth[["canary"]],
    target = weighted.mean(resp$target, w) - truth[["target"]]
  )
}))

cat(
  "Correlation of canary error with target error:",
  round(cor(errors[, "canary"], errors[, "target"]), 2), "\n"
)
cat(
  "Average target error after weighting:",
  round(mean(errors[, "target"]), 3), "\n"
)

6plot(errors[, "canary"], errors[, "target"],
  pch = 19, col = "#2166ac",
  xlab = "Canary's error after weighting",
  ylab = "Target's error after weighting"
)
abline(h = 0, v = 0, lty = 2)
1
The page’s controls: how strongly a hidden trait drives survey response, and how closely the canary variable tracks that trait.
2
Fixes the random numbers so the run is reproducible.
3
A population with age, a hidden trait, the target outcome and the canary. The canary’s true population value is known from outside.
4
Who responds depends on age, which we adjust for, and on the hidden trait, which we can’t.
5
Weight the respondents so the age mix matches the population. This fixes age and nothing else.
6
Across 200 surveys, the canary’s error after weighting against the target’s. When the canary is off, the target is off too.
# Canary variable: a known quantity that warns of hidden selection.
import numpy as np
import matplotlib.pyplot as plt

hidden = 1         # strength of hidden selection
canary_link = 0.7  # canary's correlation with the hidden trait
rng = np.random.default_rng(117)


def logistic(x):
    return 1 / (1 + np.exp(-x))


def population(n):
    old = rng.binomial(1, 0.5, n)
    u = rng.normal(size=n)  # trait we can't adjust for
    target = rng.binomial(1, logistic(-0.2 + 0.4 * old + 0.8 * u))
    canary = rng.binomial(1, logistic(canary_link * 1.5 * u + 0.3 * old))
    return old, u, target, canary


_, _, t_pop, c_pop = population(40000)
truth_target, truth_canary = t_pop.mean(), c_pop.mean()

canary_err, target_err = [], []
for _ in range(200):
    h = hidden * rng.uniform(0.2, 1.2)  # selection strength varies
    old, u, target, canary = population(4000)
    resp = rng.uniform(size=4000) < logistic(-2 + 0.8 * old + h * u)
    o = old[resp]
    w = np.where(o == 1, 0.5 / o.mean(), 0.5 / (1 - o.mean()))
    canary_err.append(np.average(canary[resp], weights=w) - truth_canary)
    target_err.append(np.average(target[resp], weights=w) - truth_target)

print(f"Correlation of canary error with target error: "
      f"{np.corrcoef(canary_err, target_err)[0, 1]:.2f}")
print(f"Average target error after weighting: {np.mean(target_err):.3f}")

plt.scatter(canary_err, target_err, color="#2166ac")
plt.axhline(0, color="black", linestyle="--")
plt.axvline(0, color="black", linestyle="--")
plt.xlabel("Canary's error after weighting")
plt.ylabel("Target's error after weighting")
plt.show()

Key takeaways

  • Hold back a variable with a known distribution and use it to check your adjustment.
  • Adjusted variables always look right by construction. Canaries can fail, which is what makes them useful.
  • Choose canaries likely to share whatever hidden factors drive non-response.

Source

Back to top