Causality, kernels, and deep networks

Double machine learning, kernels, networks, and ablation

This note goes with the course’s final lecture. Its four sections are: estimating the effect of a treatment with flexible fits (double machine learning); kernels, which use many features without writing them down; networks, which fit their features to the outcome; and ablation, a way to find out which parts of a method are needed. Boxes marked [optional] hold proofs and other details; the rest of the note can be read without them, and in the HTML version each box can be hidden. Most numbers are from the lecture’s simulations and figures; a figure that draws new data says so. The code for every figure is in the HTML version, and the simulations are in sims.R. Full references are at the end.

Show the setup code
library(tidyverse)
library(patchwork)
library(ggdag)
# The lecture's simulations and the life-expectancy fits, shared with the lecture's slides. The first run
# takes a few minutes.
source("sims.R", chdir = TRUE)
# Course palette (theme/st310.scss): viridis for the primary scale, magma for the second.
v_dark <- "#440154"; v_blue <- "#31688e"; v_teal <- "#21918c"; m_pink <- "#b73779"; m_orange <- "#fc8961"
light_blue <- "#cfe1ec"
theme_set(theme_minimal(base_size = 11))
f2 <- function(x) sprintf("%.2f", x)
f3 <- function(x) sprintf("%.3f", x)
big <- function(x) format(round(x), big.mark = ",")
lt <- function(v, col) learner_tab[[col]][learner_tab$version == v]

ML for causality: Double Machine Learning (DML)

Reference: CausalML, sections 9.1 and 9.2, which write \(D\), \(X\), and \(\beta\) for this note’s \(T\), \(Z\), and \(\theta\); Chernozhukov et al. (2018), section 1.

A flexible model, such as a forest, can predict an outcome well. Can it also say how much a treatment changes that outcome? A forest has no coefficient to read off, and its fit is biased on purpose: smoothing and shrinkage trade bias for variance. Double machine learning uses flexible fits for everything except the effect, and combines them so that their errors do little harm to it.

Prediction and intervention

Show the code
dag_plot <- function(spec, hidden = character(0)) {
  dag(spec) |> tidy_dagitty() |>
    mutate(hid = name %in% hidden, lt = ifelse(name %in% hidden, "dashed", "solid")) |>
    ggplot(aes(x = x, y = y, xend = xend, yend = yend)) +
    geom_dag_edges(aes(edge_linetype = lt), edge_width = 0.9) +
    geom_dag_point(aes(colour = hid), size = 11, show.legend = FALSE) +
    geom_dag_text(size = 4.5, colour = v_dark) +
    scale_colour_manual(values = c(`FALSE` = "#e5ecf6", `TRUE` = "grey80")) +
    coord_cartesian(clip = "off") +
    theme_dag_blank()
}
dag_plot('{ Z [pos="1,1"] T [pos="0,0"] Y [pos="2,0"] Z -> T Z -> Y T -> Y }') +
  dag_plot('{ Z [pos="1,1"] U [pos="1,-0.6"] T [pos="0,0"] Y [pos="2,0"] Z -> T Z -> Y T -> Y U -> T U -> Y }', hidden = "U")
Figure 1: Left: the inputs \(Z\) hold every common cause of the treatment \(T\) and the outcome \(Y\). Right: a common cause \(U\) that is not observed (gray) acts on \(T\) and \(Y\) other than through \(Z\), and no adjustment for \(Z\) blocks it.

There is a treatment \(T\), an outcome \(Y\), and inputs \(Z\). Two questions can be asked of the same data:

  1. How does the predicted \(Y\) change when \(T\) rises by one unit and \(Z\) is held fixed?
  2. How would \(Y\) change if we intervened to raise \(T\) by one unit?

The method below answers the first question under either graph of Figure 1. It answers the second only under the adjustment condition of the adjustment theorem: \(Z\) holds every common cause of \(T\) and \(Y\) and no consequence of \(T\), and every value of \(T\) is possible at every value of \(Z\). The left graph meets it; the right graph does not. Then \[ \mathbb E[Y \mid do(T = t)] = \mathbb E_Z\big[\mathbb E[Y \mid T = t, Z]\big], \] and if the effect of \(T\) is the same for every unit and linear in \(t\), the effect is one number, \(\theta\). One extension: a common cause may be left out of \(Z\) if all of its effect on \(T\), or all of its effect on \(Y\), passes through variables in \(Z\), which then block it. A set of inputs for which the formula above gives the effect of \(T\) is called a valid adjustment set: that is the name to look up for the general condition, of which the adjustment condition is a special case.

The partially linear model

\[ \begin{aligned} Y &= \theta\, T + g(Z) + \varepsilon_Y, &\qquad \mathbb E[\varepsilon_Y \mid T, Z] &= 0,\\ T &= m(Z) + \varepsilon_T, & \mathbb E[\varepsilon_T \mid Z] &= 0. \end{aligned} \] Here \(m(Z) = \mathbb E[T \mid Z]\) is how \(Z\) moves the treatment, and \(g(Z)\) is how \(Z\) moves the outcome other than through \(T\). The prediction of \(Y\) from \(Z\) alone is \[ \ell(Z) = \mathbb E[Y \mid Z] = \theta\, m(Z) + g(Z). \] The functions \(m\), \(g\), and \(\ell\) are nuisance functions: needed to get \(\theta\), but not wanted for themselves.

The lecture’s simulation uses this model with \(\theta = 1\), \(n = 500\) rows, five independent standard normal inputs in \(Z\), standard normal noises, and \[ m(Z) = \sin(2Z_1) + Z_2^2/2 - 1/2, \qquad g(Z) = \cos(2Z_1) + Z_2^2 + Z_3/2. \] Both functions are curved in \(Z_1\) and \(Z_2\), so \(Z\) confounds the effect of \(T\) in a way that a linear model of \(Z\) does not capture.

Residual on residual

Claim: if \(m\) and \(\ell\) were known, the slope of \(Y - \ell(Z)\) on \(T - m(Z)\) would be \(\theta\), provided \(T\) still varies given \(Z\).

Subtracting \(\ell(Z) = \theta\, m(Z) + g(Z)\) from \(Y\) leaves \[ Y - \ell(Z) = \theta\,\big(T - m(Z)\big) + \varepsilon_Y, \] a regression through the origin of one residual on the other, whose error \(\varepsilon_Y\) has mean zero given \(T\) and \(Z\). Among units with the same \(Z\), the treatment still varies by \(T - m(Z)\), and the slope uses only that variation. With linear regressions on \(Z\) in place of \(m\) and \(\ell\), this is the partialling-out theorem; the coefficient then estimates \(\theta\) when \(g\) is linear.

The method

In practice \(m\) and \(\ell\) are unknown, so learners estimate them, each from other rows than the ones it predicts. Double machine learning, for the partially linear model:

  1. Split the rows at random into five folds.
  2. For each fold, fit a learner of \(Y\) on \(Z\) and a learner of \(T\) on \(Z\) to the other four folds, and use them to predict the rows of this fold: \(\hat\ell(Z_i)\) and \(\hat m(Z_i)\) (Figure 2).
  3. Compute every row’s residuals, \(Y_i - \hat\ell(Z_i)\) and \(T_i - \hat m(Z_i)\).
  4. Regress the first residual on the second, through the origin: \[ \hat\theta = \frac{\sum_i \big(T_i - \hat m(Z_i)\big)\big(Y_i - \hat\ell(Z_i)\big)}{\sum_i \big(T_i - \hat m(Z_i)\big)^2}. \]
  5. Report \(\hat\theta \pm 1.96\,\widehat{\mathrm{se}}\), with the standard error in “The interval”.
Show the code
expand_grid(round = 1:5, fold = 1:5) |>
  mutate(role = ifelse(round == fold, "residuals computed", "learners fitted")) |>
  ggplot(aes(fold, round, fill = role)) +
  geom_tile(colour = "white", linewidth = 1.2) +
  scale_fill_manual(values = c("learners fitted" = light_blue, "residuals computed" = m_pink), name = NULL) +
  scale_y_reverse(breaks = 1:5, labels = paste("round", 1:5)) +
  scale_x_continuous(breaks = 1:5, labels = paste("fold", 1:5), position = "top") +
  coord_equal() +
  labs(x = NULL, y = NULL) +
  theme(panel.grid = element_blank())
Figure 2: Cross-fitting with five folds. In each round the learners are fitted to four folds (light) and predict the fifth (pink). After five rounds, every row has residuals from fits that did not use it, and every row has been used for fitting.
Show the code
d1 <- plm(n_dml)
fold1 <- sample(rep(1:5, length.out = n_dml))
r_y <- d1$Y - crossfit(d1$Z, d1$Y, fold1); r_t <- d1$T - crossfit(d1$Z, d1$T, fold1)
slope_raw <- unname(coef(lm(d1$Y ~ d1$T))[2]); slope_ror <- unname(ror(r_y, r_t)["est"])
p_raw <- ggplot(tibble(T = d1$T, Y = d1$Y), aes(T, Y)) +
  geom_point(colour = "grey60", size = 0.8) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = m_pink, linewidth = 1) +
  geom_abline(slope = theta, intercept = mean(d1$Y) - theta * mean(d1$T), colour = v_teal, linetype = "dashed", linewidth = 0.9) +
  labs(title = "Y on T", x = "T", y = "Y")
p_ror <- ggplot(tibble(rt = r_t, ry = r_y), aes(rt, ry)) +
  geom_point(colour = "grey60", size = 0.8) +
  geom_abline(slope = slope_ror, intercept = 0, colour = m_pink, linewidth = 1) +
  geom_abline(slope = theta, intercept = 0, colour = v_teal, linetype = "dashed", linewidth = 0.9) +
  labs(title = "residual on residual", x = expression(T - hat(m)(Z)), y = expression(Y - hat("ℓ")(Z)))
p_raw + p_ror
Figure 3: A new data set from the model of the lecture’s simulation (\(\theta = 1\), \(n = 500\)). Left: \(Y\) against \(T\), with the least-squares line (solid) and a line of slope \(\theta = 1\) (dashed). Right: the residuals of \(Y\) and of \(T\), each from bagged trees fitted to the other four folds, with the regression through the origin (solid) and a line of slope 1 (dashed).

Figure 3 shows the method on one simulated data set. The slope of \(Y\) on \(T\) is 1.50, because \(Z\) moves both; the slope of residual on residual is 1.01.

The learners’ errors

A simpler idea would be to subtract an estimate of \(g\) from \(Y\) and regress what is left on \(T\).

Claim: subtracting a fitted \(\hat g\) and regressing on \(T\) gives an estimate whose error is first order in the error of \(\hat g\): proportional to it, for small errors.

NoteDerivation [optional]

Suppose a learner, fitted on other rows, gave us \(\hat g\). Subtract it and regress on \(T\) through the origin: \[ \hat\theta_0 = \frac{\sum_i T_i\big(Y_i - \hat g(Z_i)\big)}{\sum_i T_i^2}. \] Substituting \(Y_i = \theta T_i + g(Z_i) + \varepsilon_{Y,i}\), \[ \hat\theta_0 - \theta = \frac{\sum_i T_i\,(g - \hat g)(Z_i)}{\sum_i T_i^2} + \frac{\sum_i T_i\,\varepsilon_{Y,i}}{\sum_i T_i^2}. \] The second term has mean zero. Since \(T = m(Z) + \varepsilon_T\) with \(\mathbb E[\varepsilon_T \mid Z] = 0\), the first term is close to \[ \frac{\mathbb E\big[m(Z)\,(g - \hat g)(Z)\big]}{\mathbb E[T^2]}, \] which is first order in the error of \(\hat g\). It vanishes only when \(\mathbb E[m(Z)(g - \hat g)(Z)] = 0\), which randomizing \(T\) does not guarantee: if \(T\) is \(0\) or \(1\) with probability one half, independent of \(Z\), and \(\hat g = g + c\), then \(\hat\theta_0\) tends to \(\theta - c\).

Learners’ errors shrink more slowly than \(n^{-1/2}\), so this error can be larger than the standard error. And for a continuous \(T\) there is no direct way to fit \(g\): it equals \(\ell - \theta m\), which involves \(\theta\) itself.

Residualizing \(T\) as well changes how the learners’ errors enter. Write the errors of the two learners as \(a = \hat\ell - \ell\) and \(b = \hat m - m\), and the noise variance of the treatment as \(\mathbb E[\varepsilon_T^2]\).

Claim: with \(\hat\ell\) and \(\hat m\) fitted on other rows, \[ \hat\theta - \theta \approx \frac{\mathbb E[ab] - \theta\,\mathbb E[b^2]}{\mathbb E[\varepsilon_T^2]} + \big(\text{noise with mean zero, of order } n^{-1/2}\big). \] The learners’ errors enter only as products, \(ab\) and \(b^2\), which are much smaller than the errors when both are small. It is enough that both learners’ root mean squared errors, over a new \(Z\), shrink faster than \(n^{-1/4}\) as \(n\) grows: their products then shrink faster than \(n^{-1/2}\), the size of the noise.

Show the code
n_big <- 1e6
Zb <- matrix(rnorm(n_big * q_z), n_big)
mb <- sin(2 * Zb[, 1]) + Zb[, 2]^2 / 2 - 1 / 2; gb <- cos(2 * Zb[, 1]) + Zb[, 2]^2 + Zb[, 3] / 2
Tb <- mb + rnorm(n_big); Yb <- theta * Tb + gb + rnorm(n_big); lb <- theta * mb + gb
shrink <- function(h, s) mean(h) + (1 - s) * (h - mean(h))
bias_s <- map_dfr(seq(0, 0.5, by = 0.01), function(s) {
  ghat <- shrink(gb, s); lhat <- shrink(lb, s); mhat <- shrink(mb, s)
  tibble(s = s,
         first = sum(Tb * (Yb - ghat)) / sum(Tb^2) - theta,
         ror = sum((Tb - mhat) * (Yb - lhat)) / sum((Tb - mhat)^2) - theta)
})
se_500 <- dt("dml", "se")
bias_at <- function(s0, col) bias_s[[col]][which.min(abs(bias_s$s - s0))]
bias_s |> pivot_longer(-s, names_to = "estimate", values_to = "error") |>
  ggplot(aes(s, error, colour = estimate)) +
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = -se_500, ymax = se_500, fill = "grey88") +
  geom_hline(yintercept = 0, colour = "grey50") +
  geom_line(linewidth = 1.2) +
  scale_colour_manual(values = c(first = m_pink, ror = v_dark),
                      labels = c(first = "first try: subtract ĝ", ror = "residual on residual"), name = NULL) +
  labs(x = "shrinkage s of each learner", y = "error of the estimate") +
  theme(legend.position = "top")
Figure 4: How a learner’s error enters each estimate, computed on \(10^6\) new rows from the model of the lecture’s simulation, with no learner fitted. Each nuisance function is replaced by a shrunken version, its mean plus \((1 - s)\) times its deviation from the mean, as a learner that shrinks toward the mean might return. The first try’s error grows in proportion to \(s\). The error of residual on residual is here \(s^2/(1 + s^2\,\mathrm{Var}(m(Z)))\), close to \(s^2\) for small \(s\). The gray band is plus or minus the average standard error of \(\hat\theta\) in the simulation, with \(n = 500\).

Figure 4 shows the difference, with learners that shrink each nuisance function toward its mean by a factor \(1 - s\). With \(s = 0.2\) the first try is off by 0.10, about 1.7 standard errors, and residual on residual by 0.04.

NoteDerivation, a seminar exercise [optional]

On the rows being scored, \(\hat\ell\) and \(\hat m\) are fixed functions of \(Z\), because they were fitted on other rows. Then \[ \begin{aligned} T - \hat m(Z) &= \varepsilon_T - b, \\ Y - \hat\ell(Z) &= \theta\,\varepsilon_T + \varepsilon_Y - a, \\ Y - \hat\ell(Z) - \theta\,\big(T - \hat m(Z)\big) &= \varepsilon_Y - a + \theta\, b. \end{aligned} \] Multiplying out the definition of \(\hat\theta\) gives the exact identity \[ \hat\theta - \theta = \frac{\sum_i \psi_i}{\sum_i \big(T_i - \hat m(Z_i)\big)^2}, \] where \(\psi\), the score, is each row’s contribution at the true \(\theta\): \[ \psi = \big(T - \hat m(Z)\big)\big(Y - \hat\ell(Z) - \theta\,(T - \hat m(Z))\big) = (\varepsilon_T - b)(\varepsilon_Y - a + \theta\, b). \] Averaged over a new row with the fits held fixed, \[ \mathbb E_{T, Y, Z}[\psi] = \mathbb E[\varepsilon_T\varepsilon_Y] - \mathbb E[\varepsilon_T\, a] + \theta\,\mathbb E[\varepsilon_T\, b] - \mathbb E[b\,\varepsilon_Y] + \mathbb E[ab] - \theta\,\mathbb E[b^2] = \mathbb E[ab] - \theta\,\mathbb E[b^2]. \] The four terms with a noise in them are zero: \(\mathbb E[\varepsilon_Y \mid T, Z] = 0\) removes the first and fourth, and \(\mathbb E[\varepsilon_T \mid Z] = 0\) removes the second and third, because \(a\) and \(b\) are functions of \(Z\) alone. The denominator, divided by \(n\), is close to \(\mathbb E[\varepsilon_T^2] + \mathbb E[b^2]\), and \(\mathbb E[b^2]\) is small beside \(\mathbb E[\varepsilon_T^2]\) when \(\hat m\) is accurate. That gives the claim.

The first try had one error to the first power; here the expected score has no first-order term in the learners’ errors. Chernozhukov et al. call the property behind this Neyman orthogonality: the expected score does not change, to first order, when the nuisance functions move a little from their true values. CausalML (section 9.2, Remark 9.2.4) computes the corresponding derivative for the first try and finds that it is not zero in general.

Cross-fitting

The claims above assume that, on the rows being scored, \(\hat\ell\) and \(\hat m\) are fixed functions of \(Z\). A learner fitted to the same rows would have absorbed part of each row’s own noise, and the products above would no longer be the whole error. Cross-fitting (Figure 2) gives every row residuals from fits that did not use it, and still uses every row for fitting.

For the bagged trees of the lecture’s simulation, which stop splitting a node once it holds 20 rows or fewer, removing cross-fitting changed little (see “Ablation”). A learner that overfits its own rows does break the in-sample version; CausalML’s Figure 9.2 shows an example.

NoteCross-fitting and the zero terms [optional]

The derivation used that \(\mathbb E[\varepsilon_T\, a]\), \(\mathbb E[\varepsilon_T\, b]\), and \(\mathbb E[b\,\varepsilon_Y]\) are zero, which holds when \(a\) and \(b\) are fixed functions of \(Z\) on the rows being scored. If \(\hat\ell\) were fitted to the same rows, \(\hat\ell(Z_i)\) would have absorbed some of row \(i\)’s noise \(\theta\varepsilon_{T,i} + \varepsilon_{Y,i}\), and \(\frac1n\sum_i \varepsilon_{T,i}\, a(Z_i)\) would no longer average to zero. Learners that follow their own rows closely, such as fully grown trees or boosting run for many iterations, give biased in-sample estimates. At the extreme, a learner that fits its own rows exactly makes every residual \(T_i - \hat m(Z_i)\) zero, and \(\hat\theta\) is not defined.

Step 4 runs one regression on all the residuals, as CausalML does; averaging one estimate per fold is the other common version.

NoteChoosing the learners [optional]

The bias of \(\hat\theta\) depends on how well \(\hat\ell\) and \(\hat m\) predict, and the cross-fitted residuals measure that error on rows the learners were not fitted to. So choose the learner for \(Y\) and the learner for \(T\) separately, each by its cross-fitted prediction error, from a few candidates, and before looking at \(\hat\theta\). The two tasks can have different winners. Choosing among many candidates on the same rows overfits the choice (CausalML, section 9.2, Corollary 9.2.3; its gun-ownership example compares ten learners in Tables 9.1 and 9.2).

In the lecture’s simulation, with the same learner for both predictions (root mean squared error of the cross-fitted residuals, and the mean of \(\hat\theta\), over the 100 data sets; the first row predicts each fold by the mean of the other four):

Learner Error predicting \(Y\) Error predicting \(T\) Mean \(\hat\theta\)
the mean (no adjustment) 2.75 1.41 1.48
linear regression 2.72 1.39 1.51
bagged trees 1.67 1.10 1.01

No learner can do better than the noise: \(\sqrt 2 \approx 1.41\) for \(Y\), since \(Y - \ell(Z) = \theta\varepsilon_T + \varepsilon_Y\), and 1 for \(T\). Linear regression predicts barely better than the mean, because the confounding is curved.

Double lasso

With the lasso as the learner for both \(Y\) and \(T\), residual on residual is the double lasso (CausalML, section 4.2). It suits data where \(Z\) has many inputs, perhaps nearly as many as there are rows, and each prediction needs only a few of them: least squares on all the inputs is then noisy or impossible, and the lasso keeps the ones that predict. The second lasso is what protects the estimate. A single lasso of \(Y\) on \(T\) and \(Z\) keeps the inputs that predict \(Y\), and can drop one that predicts \(Y\) only weakly but \(T\) strongly; leaving out such a confounder biases \(\hat\theta\), and the lasso of \(T\) on \(Z\) keeps it. In CausalML’s example, with 90 countries and about 60 controls, the least-squares interval for how fast poorer countries catch up includes zero, and the double lasso’s excludes it.

The interval

The standard error comes from the residual regression and allows the variance of the noise to differ across rows. With \(\tilde t_i = T_i - \hat m(Z_i)\) and \(\hat e_i = Y_i - \hat\ell(Z_i) - \hat\theta\,\tilde t_i\), \[ \widehat{\mathrm{se}}(\hat\theta) = \frac{\sqrt{\sum_i \tilde t_i^{\,2}\,\hat e_i^{\,2}}}{\sum_i \tilde t_i^{\,2}}. \] The default standard error of lm() assumes equal variances and is not this one. In the lecture’s simulation the interval covered \(\theta\) in 94 of 100 data sets (Figure 5, bottom row), and the standard error averaged 0.058, against a standard deviation of 0.059 for \(\hat\theta\). The guarantee holds as \(n\) grows, when the learners’ errors shrink fast enough.

Show the code
lab <- c(none = "Y on T, no adjustment", linear = "no learners: linear partialling out",
         y_only = "T not residualized", insample = "no cross-fitting", dml = "all parts: double ML")
d_est <- as_tibble(t(dml_runs[, "est", ]), .name_repair = "minimal") |>
  pivot_longer(everything(), names_to = "version", values_to = "est") |>
  filter(version %in% names(lab)) |>
  mutate(version = factor(lab[version], levels = rev(lab)))
d_sum <- dml_tab |> filter(version %in% names(lab)) |>
  mutate(version = factor(lab[version], levels = rev(lab)), txt = paste0(cover, " of ", R_dml))
ggplot(d_est, aes(est, version)) +
  geom_vline(xintercept = theta, colour = v_teal, linewidth = 0.9) +
  geom_jitter(height = 0.15, width = 0, alpha = 0.35, colour = v_blue, size = 1) +
  geom_point(data = d_sum, aes(mean, version), colour = m_pink, size = 3.5, shape = 18) +
  scale_y_discrete(sec.axis = dup_axis(name = NULL, labels = setNames(d_sum$txt, d_sum$version)[levels(d_sum$version)])) +
  scale_x_continuous(breaks = seq(0.5, 1.75, 0.25)) +
  labs(x = "estimate of θ (true value 1, vertical line)", y = NULL)
Figure 5: The estimate in each of 100 simulated data sets, for double machine learning (bottom row) and for four versions with one part removed (the diamond is the mean; the right axis counts the intervals that cover \(\theta\)). The section on ablation explains each row.

Limits

  • No causal claim unless \(Z\) is a valid adjustment set, for example by meeting the adjustment condition: \(Z\) holds every common cause of \(T\) and \(Y\) (or variables through which all of its effect on \(T\), or on \(Y\), passes) and no consequence of \(T\), and every value of \(T\) is possible at every value of \(Z\). A common cause of \(T\) and \(Y\) that acts on both of them other than through \(Z\) (the right graph of Figure 1) biases \(\hat\theta\) however good the learners are, and nothing in the data reveals it.
  • Weak overlap. If \(Z\) nearly determines \(T\), then \(T - \hat m(Z)\) is close to zero for most rows, and \(\hat\theta\) divides by almost nothing.
  • An effect that varies. If the effect of \(T\) differs between units, \(\hat\theta\) estimates a weighted average of the effects, weighted toward units whose treatment varies most given \(Z\). It generally differs from the average effect, and one number cannot say who a treatment helps most: that needs an estimate of the effect as a function of \(Z\).
  • [optional] The weighted average: if \(Y = \theta(Z)\,T + g(Z) + \varepsilon_Y\), then \(Y - \ell(Z) = \theta(Z)\,\varepsilon_T + \varepsilon_Y\), and residual on residual estimates \[ \frac{\mathbb E\big[\theta(Z)\,\mathrm{Var}(T \mid Z)\big]}{\mathbb E\big[\mathrm{Var}(T \mid Z)\big]}. \] This equals the average effect \(\mathbb E[\theta(Z)]\) when \(\mathrm{Var}(T \mid Z)\) does not depend on \(Z\). For a binary \(T\), \(\mathrm{Var}(T \mid Z) = m(Z)\big(1 - m(Z)\big)\), and these are called overlap weights (CausalML, Remark 9.3.3).

Takeaways

  • With the two means \(m\) and \(\ell\) known, the slope of the outcome’s residual on the treatment’s residual is \(\theta\). Double machine learning estimates both means with learners.
  • Fit each learner on other rows than the ones it predicts (cross-fitting).
  • Residualizing both makes the learners’ errors enter only as products, so learners whose root mean squared errors shrink faster than \(n^{-1/4}\), which can be far slower than \(n^{-1/2}\), still give a valid interval for \(\theta\).
  • The slope answers a question about prediction under any graph. It is a causal effect only when \(Z\) is a valid adjustment set, which neither a learner nor a prediction score can check.

Kernels and feature transformations

Reference: ISLR, section 9.3 (kernels, introduced there for support vector machines; the classifiers of sections 9.1 and 9.2 are not part of this course) and section 7.6 (local regression).

A model that is linear in a list of features of \(x\) can be curved in \(x\). With many inputs, useful lists of features are long: millions of features, or infinitely many. A kernel lets ridge regression use such a list without ever computing it.

Features

A feature map \(\varphi\) sends an input \(x \in \mathbb R^p\) to a list of features, and a model linear in the features, \(f(x) = \beta_0 + \beta^T\varphi(x)\), can be curved in \(x\) (Figure 6). Splines are one example. Another is all the monomials of degree up to \(d\), of which there are \(\binom{p+d}{d}\): with \(p = 100\) inputs and \(d = 4\), that is 4,598,126 features. Ridge regression on them, computed directly, solves a system with that many unknowns.

Show the code
x6 <- seq(-2, 2, length.out = 41); y6 <- 1 + x6^2 + rnorm(41, sd = 0.4)
fit6 <- lm(y6 ~ I(x6^2))
p6a <- ggplot(tibble(x = x6, y = y6), aes(x, y)) +
  geom_point(colour = "grey50", size = 1.2) +
  geom_line(aes(y = fitted(fit6)), colour = m_pink, linewidth = 1.1) +
  labs(title = "against x", x = "x", y = "y")
p6b <- ggplot(tibble(x2 = x6^2, y = y6), aes(x2, y)) +
  geom_point(colour = "grey50", size = 1.2) +
  geom_abline(intercept = coef(fit6)[1], slope = coef(fit6)[2], colour = m_pink, linewidth = 1.1) +
  labs(title = "against the feature", x = "x²", y = "y")
p6a + p6b
Figure 6: Least squares on one feature, \(\varphi(x) = x^2\), for 41 points from \(y = 1 + x^2\) plus noise. Against \(x\) the fit is a curve; against the feature it is a line.

Ridge, computed two ways

Center \(\mathbf y\) and the columns of the \(n \times p\) matrix \(\mathbf X\) (the columns can be features), so that there is no intercept. For \(\lambda > 0\), multiplying out both sides shows that \[ \mathbf X^T\,\underline{(\mathbf X\mathbf X^T + \lambda \mathbf I_n)} = \mathbf X^T\mathbf X\mathbf X^T + \lambda\mathbf X^T = \underline{(\mathbf X^T\mathbf X + \lambda\mathbf I_p)}\,\mathbf X^T. \]

Claim: both underlined matrices are invertible.

NoteProof sketch, a seminar exercise [optional]

\(\mathbf X^T\mathbf X\) is positive semi-definite: for any vector \(v\), \(v^T\mathbf X^T\mathbf X v = \|\mathbf X v\|^2 \ge 0\), so its eigenvalues are at least 0. Adding \(\lambda \mathbf I_p\) adds \(\lambda\) to every eigenvalue, so every eigenvalue of \(\mathbf X^T\mathbf X + \lambda \mathbf I_p\) is at least \(\lambda > 0\), and a symmetric matrix whose eigenvalues are all nonzero is invertible. The same argument, with \(\|\mathbf X^T v\|^2\), applies to \(\mathbf X\mathbf X^T + \lambda\mathbf I_n\).

Multiplying the identity on the left by \((\mathbf X^T\mathbf X + \lambda\mathbf I_p)^{-1}\) and on the right by \((\mathbf X\mathbf X^T + \lambda\mathbf I_n)^{-1}\), and then applying both sides to \(\mathbf y\), \[ \hat\beta_\lambda = (\mathbf X^T\mathbf X + \lambda\mathbf I_p)^{-1}\mathbf X^T\mathbf y = \mathbf X^T(\mathbf X\mathbf X^T + \lambda\mathbf I_n)^{-1}\mathbf y. \] The first form solves a \(p \times p\) system, the second an \(n \times n\) one (Figure 7). A prediction at a new \(x\), centered by the training means, is \[ \bar y + x^T\hat\beta_\lambda = \bar y + (\mathbf X x)^T(\mathbf X\mathbf X^T + \lambda\mathbf I_n)^{-1}\mathbf y, \] and the second form uses the inputs only through inner products: \(x_i^T x_j\) in \(\mathbf X\mathbf X^T\), and \(x_i^T x\) in \(\mathbf X x\).

Show the code
shapes <- tibble(lab = c("X:  n × p = 50 × 200", "XᵀX + λI:  p × p = 200 × 200", "XXᵀ + λI:  n × n = 50 × 50"),
                 x0 = c(0, 240, 470), w = c(200, 200, 50), h = c(50, 200, 50), fill = c("grey85", light_blue, "#f3d5e3"))
ggplot(shapes) +
  geom_rect(aes(xmin = x0, xmax = x0 + w, ymin = 0, ymax = h, fill = fill), colour = "grey40") +
  geom_text(aes(x = x0, y = -18, label = lab), hjust = 0, size = 3.1) +
  scale_fill_identity() +
  coord_equal(clip = "off") +
  theme_void()
Figure 7: The matrices of the two forms of ridge, drawn to scale for \(n = 50\) rows and \(p = 200\) inputs. The first form solves a system with the \(p \times p\) matrix, the second with the \(n \times n\) one.

Kernels

A kernel is a function \(K(x, x')\) of two inputs that is symmetric, \(K(x, x') = K(x', x)\), and positive semi-definite: for every \(n\) and every \(x_1, \ldots, x_n\), the \(n \times n\) matrix \(\mathbf K\) with entries \(K(x_i, x_j)\) satisfies \[ c^T\mathbf K c = \sum_{i,j} c_i c_j K(x_i, x_j) \ge 0 \quad\text{for every } c \in \mathbb R^n. \]

Claim: for any feature map \(\varphi\), the inner product of the features, \(K(x, x') = \langle \varphi(x), \varphi(x') \rangle\), is a kernel.

NoteProof [optional]

It is symmetric because inner products are. And \(c^T\mathbf K c = \sum_{i,j} c_i c_j \langle \varphi(x_i), \varphi(x_j)\rangle = \big\|\sum_i c_i\varphi(x_i)\big\|^2 \ge 0\).

The feature maps of the converse, stated after this box, live in what is called a reproducing kernel Hilbert space, the space of functions that the kernel defines.

The converse also holds, though its proof is beyond this course: every kernel is the inner product of some feature map, possibly with infinitely many features. So a kernel computes the inner products of a feature map directly. Three common kernels:

  • linear, \(K(x, x') = x^T x'\): the features are the inputs themselves;
  • polynomial of degree \(d\), \(K(x, x') = (1 + x^T x')^d\): the features are all \(\binom{p+d}{d}\) monomials of degree up to \(d\), each with a weight, computed from one \(p\)-dimensional inner product;
  • Gaussian, \(K(x, x') = \exp\big(-\|x - x'\|^2/2h^2\big)\), with bandwidth \(h\): infinitely many features.

For \(p = 2\) and the polynomial kernel of degree 2, \[ \begin{aligned} (1 + x^Tx')^2 &= 1 + 2x_1x'_1 + 2x_2x'_2 + x_1^2x_1'^2 + 2x_1x_2x'_1x'_2 + x_2^2x_2'^2 = \langle \varphi(x), \varphi(x') \rangle,\\ \varphi(x) &= \big(1, \sqrt2\,x_1, \sqrt2\,x_2, x_1^2, \sqrt2\,x_1x_2, x_2^2\big). \end{aligned} \]

A kernel can be read as a similarity between two inputs (Figure 8). The Gaussian kernel is largest when \(x' = x\) and falls toward zero as they move apart, over a distance set by \(h\).

Show the code
x8 <- seq(-2, 2, length.out = 401); x0 <- 0.5
k8 <- map_dfr(c(0.25, 0.5, 1), function(h) tibble(x = x8, K = exp(-(x8 - x0)^2 / (2 * h^2)), h = paste("h =", h)))
p8a <- ggplot(k8, aes(x, K, colour = h)) +
  geom_vline(xintercept = x0, colour = "grey60", linetype = "dashed") +
  geom_line(linewidth = 1) +
  scale_colour_viridis_d(end = 0.85, name = NULL) +
  labs(title = "Gaussian", x = "x", y = "K(x, 0.5)")
p8b <- ggplot(tibble(x = x8, K = (1 + x8 * x0)^2), aes(x, K)) +
  geom_vline(xintercept = x0, colour = "grey60", linetype = "dashed") +
  geom_line(linewidth = 1, colour = m_pink) +
  labs(title = "polynomial, degree 2", x = "x", y = "K(x, 0.5)")
xg <- seq(-1, 1, length.out = 25)
kg <- bind_rows(
  expand_grid(i = 1:25, j = 1:25) |> mutate(K = exp(-(xg[i] - xg[j])^2 / (2 * 0.25^2)), kind = "Gaussian, h = 0.25"),
  expand_grid(i = 1:25, j = 1:25) |> mutate(K = (1 + xg[i] * xg[j])^2, kind = "polynomial, degree 2")) |>
  group_by(kind) |> mutate(K = K / max(K)) |> ungroup()
p8c <- ggplot(kg, aes(xg[j], xg[i], fill = K)) +
  geom_tile() +
  facet_wrap(~ kind) +
  scale_fill_viridis_c(name = "K / max") +
  scale_y_reverse() +
  coord_equal() +
  labs(x = expression(x[j]), y = expression(x[i])) +
  theme(axis.text = element_blank())
(p8a + p8b) / p8c
Figure 8: Top: \(K(x, x_0)\) as a function of \(x\), for \(x_0 = 0.5\) (dashed line), for the Gaussian kernel with three bandwidths and the polynomial kernel of degree 2. Bottom: the matrix of \(K(x_i, x_j)\) for 25 points from \(-1\) to \(1\), each divided by its largest entry.
NoteThe feature weights, and a function that is not a kernel [optional]

ISLR writes the Gaussian kernel as \(\exp\big(-\gamma\|x - x'\|^2\big)\), so \(\gamma = 1/(2h^2)\). The polynomial kernel is not a similarity in the Gaussian kernel’s sense: it grows with the size of the inputs.

The weights \(\sqrt2\) in the feature map above are part of the map: ridge on the unweighted monomials penalizes the coefficients differently, and is a different estimator.

Not every function of \(\langle x, x'\rangle\) is a kernel. The “neural network kernel” \(\tanh(\kappa_1\langle x, x'\rangle + \kappa_2)\) is not positive semi-definite in general. At \(x = 0\) it gives \(K(0, 0) = \tanh(\kappa_2) < 0\) whenever \(\kappa_2 < 0\), but \(K(0, 0)\) is the \(1 \times 1\) matrix of the single point 0, which must be at least 0. It fails with \(\kappa_2 = 0\) too: for \(p = 1\) and \(\kappa_1 = 1\), the inputs 1 and 2 give a \(2 \times 2\) matrix with determinant \(\tanh(1)\tanh(4) - \tanh(2)^2 = -0.17\), so one of its eigenvalues is negative.

Kernel ridge

Replace every inner product in the second form of ridge by the kernel: the \(n \times n\) matrix \(\mathbf K\) with entries \(K(x_i, x_j)\), and \(\mathbf k(x) = \big(K(x, x_1), \ldots, K(x, x_n)\big)\). With \(\mathbf y\) centered, \[ \hat f(x) = \bar y + \mathbf k(x)^T(\mathbf K + \lambda\mathbf I)^{-1}\mathbf y = \bar y + \sum_{i=1}^n \hat\alpha_i\, K(x, x_i), \qquad \hat\alpha = (\mathbf K + \lambda\mathbf I)^{-1}\mathbf y. \] This is ridge regression on the kernel’s features, computed without writing them down. The fit is \(\bar y\) plus a combination of \(n\) functions, one centered at each training point (Figure 9).

Show the code
x9 <- c(0.3, 0.9, 1.6, 2.2, 2.9, 3.4, 4.1, 4.7); y9 <- sin(1.3 * x9) + rnorm(8, sd = 0.2)
h9 <- 0.5; lam9 <- 0.1
alpha9 <- solve(exp(-outer(x9, x9, "-")^2 / (2 * h9^2)) + lam9 * diag(8), y9 - mean(y9))
xs9 <- seq(0, 5, length.out = 400)
bumps <- map_dfr(1:8, function(i) tibble(x = xs9, i = i, positive = alpha9[i] > 0,
                                         b = alpha9[i] * exp(-(xs9 - x9[i])^2 / (2 * h9^2))))
fit9 <- bumps |> group_by(x) |> summarise(f = mean(y9) + sum(b))
ggplot() +
  geom_hline(yintercept = mean(y9), colour = "grey60", linetype = "dashed") +
  geom_line(data = bumps, aes(x, mean(y9) + b, group = i, colour = positive), linewidth = 0.6) +
  geom_line(data = fit9, aes(x, f), colour = v_dark, linewidth = 1.3) +
  geom_point(aes(x9, y9), size = 2.2) +
  scale_colour_manual(values = c(`TRUE` = v_teal, `FALSE` = m_orange), guide = "none") +
  labs(x = "x", y = "y")
Figure 9: Kernel ridge with the Gaussian kernel (\(h = 0.5\), \(\lambda = 0.1\)) on eight points. Each thin curve is one term \(\hat\alpha_i K(x, x_i)\), drawn about \(\bar y\) (dashed): teal where \(\hat\alpha_i > 0\), orange where \(\hat\alpha_i < 0\). The fit (thick) is \(\bar y\) plus their sum.

Claim (the representer theorem, stated without proof): with \(\mathbf y\) centered, among all functions in the space of functions that \(K\) defines (a space built from the functions \(K(\cdot, x)\)), the one that minimizes the sum of squared errors plus \(\lambda\) times its squared norm in that space is \(\sum_i \hat\alpha_i K(\cdot, x_i)\), with \(\hat\alpha\) as above. Kernel ridge then adds \(\bar y\) back.

ISLR’s support vector machine has a fit of the same form (section 9.3.2, equation 9.23), with a different loss (section 9.5).

NoteThe intercept [optional]

The ridge section above centered the columns of \(\mathbf X\) and fitted no intercept. Kernel ridge as written does not center the features: in place of a fitted intercept, the mean \(\bar y\) is added back. For the polynomial kernel, whose features include the constant 1, the constant is one more penalized feature. Centering the features as well would mean centering \(\mathbf K\).

Fits as weighted sums of the outcomes

Kernel ridge, \(k\)-nearest neighbors, and the kernel-weighted average all predict with a weighted sum of the training outcomes (Figure 10, for 142 countries in 2007, life expectancy against \(\log_{10}\) GDP per capita). Kernel ridge’s weights sum to one, but some are negative: at \(\log_{10}\) GDP per capita 3.5, 40 of the 142.

For the kernel-weighted average, the bandwidth plays the part of \(k\): a larger \(h\) averages over more points.

Show the code
meth <- c(paste(k_g, "nearest neighbors"), "kernel-weighted average", "kernel ridge")
cols_g <- setNames(c(m_pink, v_dark, v_teal), meth)
knn_w <- replace(numeric(nrow(gm)), order(abs(gm$lgdp - 3.5))[1:k_g], 1 / k_g)
nw_w <- exp(-0.5 * ((gm$lgdp - 3.5) / h_g)^2); nw_w <- nw_w / sum(nw_w)
wts <- tibble(lgdp = rep(gm$lgdp, 3), w = c(knn_w, nw_w, w_raw), method = factor(rep(meth, each = nrow(gm)), levels = meth)) |>
  mutate(colour = ifelse(w < 0, "negative", as.character(method)))
fits_g <- tibble(lgdp = rep(grid_g$lgdp, 3), fit = c(knn_g, nw_g, kr_g), method = factor(rep(meth, each = nrow(grid_g)), levels = meth))
p10a <- ggplot(gm, aes(lgdp, lifeExp)) +
  geom_point(colour = "grey60", size = 1) +
  geom_vline(xintercept = 3.5, colour = "grey40", linetype = "dashed") +
  geom_line(data = fits_g, aes(y = fit, colour = method), linewidth = 0.9) +
  scale_colour_manual(values = cols_g, name = NULL) +
  labs(x = NULL, y = "life expectancy") +
  theme(legend.position = "top")
p10b <- ggplot(wts, aes(lgdp, w)) +
  geom_hline(yintercept = 0, colour = "grey50") +
  geom_segment(aes(xend = lgdp, y = 0, yend = w, colour = colour), linewidth = 0.6) +
  facet_wrap(~ method, ncol = 1) +
  scale_colour_manual(values = c(cols_g, negative = m_orange), guide = "none") +
  labs(x = "log10 GDP per capita, 2007", y = "weight at 3.5") +
  theme(strip.text = element_text(hjust = 0))
p10a / p10b + plot_layout(heights = c(1.1, 1.6))
Figure 10: Top: life expectancy against \(\log_{10}\) GDP per capita for 142 countries in 2007, with three fits: the 20 nearest neighbors, and a kernel-weighted average and kernel ridge, both with the Gaussian kernel, \(h = 0.15\) (kernel ridge with \(\lambda = 1\)). Bottom: the weight each method gives each country’s life expectancy in its prediction at 3.5 (dashed line, top). Kernel ridge’s negative weights are in orange.
NoteWeights and rates [optional]

\(k\)-nearest neighbors gives weight \(1/k\) to each of the \(k\) nearest training points. The kernel-weighted average gives row \(i\) the weight \(K(x, x_i)/\sum_j K(x, x_j)\), which for the Gaussian kernel is never negative.

The kernel-weighted average fits a weighted constant around each \(x\); the local regression of ISLR, section 7.6, fits a weighted line.

Kernel ridge gives the weights \(\mathbf w(x) = (\mathbf K + \lambda\mathbf I)^{-1}\mathbf k(x)\) to the centered outcomes. With the mean added back, the weight on \(y_i\) is \(w_i(x) + \big(1 - \sum_j w_j(x)\big)/n\), and these sum to one.

A window of width \(h\) in \(p\) dimensions holds about \(nh^p\) training points, so the kernel-weighted average with bandwidth \(h\) behaves like \(k\)-nearest neighbors with \(k \approx nh^p\), that is \(h \asymp (k/n)^{1/p}\). The \(k\)-NN rate’s terms \((k/n)^{2/p} + 1/k\) become \(h^2 + 1/(nh^p)\), balanced at \(h \asymp n^{-1/(p+2)}\), with the same rate \(n^{-2/(p+2)}\). Kernel ridge is a different estimator, and its analysis is beyond this course.

Cost and the curse

Kernel ridge solves an \(n \times n\) system, about \(n^3\) operations: with \(n = 10^5\) rows, about \(10^{15}\), and it keeps every training row to predict. And with many inputs nothing is near (Figure 11). From a new point to 1,000 standard normal points, the nearest distance divided by the farthest has median 0.0003 with \(p = 1\), 0.24 with \(p = 10\), and 0.67 with \(p = 100\). With \(p = 100\) even the nearest training point is about two-thirds as far away as the farthest. A narrow kernel can still put almost all its weight on the nearest point, but that point is not near, so the prediction is not local.

Show the code
ggplot(curse, aes(p, median)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = light_blue) +
  geom_line(colour = v_dark, linewidth = 1) +
  geom_point(colour = v_dark, size = 1.8) +
  scale_x_log10(breaks = c(1, 2, 5, 10, 20, 50, 100)) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "number of inputs p (log scale)", y = "nearest / farthest")
Figure 11: From a new point to 1,000 standard normal points in \(p\) dimensions, the nearest distance divided by the farthest: the median over 100 new points (line), and the 10th to 90th percentiles (band).

Takeaways

  • A kernel is a symmetric, positive semi-definite function of two inputs. It equals the inner product of some features, which it computes without computing the features.
  • Ridge regression needs only inner products, so kernel ridge is ridge on the kernel’s features, at the cost of an \(n \times n\) system.
  • Kernel ridge, like \(k\)-nearest neighbors, predicts with a weighted sum of the training outcomes, and the bandwidth is the knob.
  • Choosing a kernel and its bandwidth fixes the feature map, and with many inputs no training point is near.

Deep networks and feature learning

Reference: ISLR, sections 10.1 and 10.2; Rahimi and Recht (2007) for random features; Cybenko (1989) for universal approximation.

Kernel ridge’s features are fixed once the kernel and its bandwidth are chosen. A network with one hidden layer is also a linear model on features, but training moves each hidden unit’s direction using the outcomes.

One hidden layer

A network with one hidden layer of \(M\) units has features \[ h_k(x) = g^{-1}(w_{k0} + w_k^T x), \qquad k = 1, \ldots, M, \] with \(g^{-1}\) the logistic function (the inverse link on the slide “A GLM of GLMs”, not the \(g(Z)\) of the first section), and output \(f(x) = \beta_0 + \sum_{k=1}^M \beta_k h_k(x)\). Each unit is a smoothed step in one direction of the input space, and weighted sums of steps can make bumps and curves (Figure 12).

Show the code
sg <- function(z) 1 / (1 + exp(-z)); x13 <- seq(-3, 3, length.out = 400)
units13 <- tibble(x = x13, h1 = sg(4 * (x13 + 1.5)), h2 = sg(4 * x13), h3 = sg(4 * (x13 - 1.5)))
ggplot(pivot_longer(units13, -x), aes(x, value)) +
  geom_line(aes(group = name), colour = "grey55", linewidth = 0.7) +
  geom_line(data = tibble(x = x13, value = with(units13, 0.2 + h1 - 1.6 * h2 + 1.2 * h3)), colour = v_dark, linewidth = 1.3) +
  labs(x = "x", y = NULL)
Figure 12: Three logistic units with one input (gray), and one weighted sum of them, \(\beta_0 + \sum_k \beta_k h_k(x)\) (dark).

The first layer frozen

Draw the hidden weights \(w_{k0}, w_k\) at random and never train them (Figure 13). What is left is linear regression on \(M\) fixed features, and with a penalty on the squared output weights it is ridge regression.

Claim: a network whose first layer is drawn at random and frozen, fitted with a penalty on its output weights, the constant \(\beta_0\) included, is kernel ridge applied to \(\mathbf y\) without centering it, with the kernel \[ K(x, x') = 1 + \sum_{k=1}^M h_k(x)\, h_k(x'), \] where the 1 is the feature that goes with \(\beta_0\). This is the idea of random features.

Show the code
net_picture <- function(cols, first_colour = v_blue, first_type = "solid", heads = NULL) {
  nodes <- imap_dfr(cols, function(lab, j) tibble(col = j, x = 1.6 * (j - 1), lab = lab,
    y = if (length(lab) == 1) 1.5 else seq(3, 0, length.out = length(lab))))
  real <- filter(nodes, lab != "...")
  edges <- map_dfr(seq_len(length(cols) - 1), function(j) {
    a <- filter(real, col == j); b <- filter(real, col == j + 1)
    expand_grid(i = seq_len(nrow(a)), k = seq_len(nrow(b))) |>
      transmute(x = a$x[i], y = a$y[i], xend = b$x[k], yend = b$y[k], layer = j)
  })
  last <- length(cols)
  ggplot() +
    geom_segment(data = filter(edges, layer == 1), aes(x, y, xend = xend, yend = yend),
                 colour = first_colour, linetype = first_type, alpha = 0.7, linewidth = 0.6) +
    geom_segment(data = filter(edges, layer > 1), aes(x, y, xend = xend, yend = yend),
                 colour = m_pink, alpha = 0.7, linewidth = 0.6) +
    geom_point(data = filter(real, col == 1), aes(x, y), size = 10, colour = "grey35", fill = "white", shape = 21, stroke = 0.9) +
    geom_point(data = filter(real, col > 1, col < last), aes(x, y), size = 11, colour = v_blue, fill = "#e8f0f7", shape = 21, stroke = 1) +
    geom_point(data = filter(real, col == last), aes(x, y), size = 11, colour = m_pink, fill = "#fbe9f1", shape = 21, stroke = 1) +
    geom_text(data = nodes, aes(x, y, label = lab), parse = TRUE, size = 2.9) +
    { if (!is.null(heads)) annotate("text", x = 1.6 * (seq_along(heads) - 1), y = 3.75, label = heads, size = 3.2, colour = "grey30") } +
    coord_cartesian(xlim = c(-0.4, 1.6 * (last - 1) + 0.4), ylim = c(-0.5, 4), clip = "off") +
    theme_void()
}
net_picture(list(c("x[1]", "x[2]", "...", "x[p]"), c("h[1]", "h[2]", "h[M]"), "f(x)"),
            first_colour = "grey55", first_type = "dashed", heads = c("inputs", "M hidden units", "output"))
Figure 13: A network with one hidden layer. With the first layer’s weights (dashed) drawn at random and never trained, only the output weights are fitted.
NoteRidge on random features [optional]

With the first layer fixed, the network is linear regression on the features \((1, h_1(x), \ldots, h_M(x))\). A penalty on the squared output weights makes it ridge regression on these features, and by the kernels section ridge on any features is kernel ridge with the inner product of the features as the kernel: here \(1 \cdot 1 + \sum_k h_k(x) h_k(x')\). In R’s nnet, the penalty (decay) also penalizes \(\beta_0\), so the constant is one more penalized feature, with no separate intercept and \(\mathbf y\) not centered.

The name random features is from Rahimi and Recht (2007), who drew random cosines designed to approximate a chosen kernel; logistic units drawn at random are the same idea, not their construction.

Training the first layer

Training the first layer as well fits the features to \(y\). The fit is no longer linear in the parameters, the training loss can have many local minima, and where the optimizer stops depends on the starting weights.

The lecture compared the two on simulated data (Figure 14). The excess risk of a fit \(\hat f\) is \(\mathbb E\big[(\hat f(X) - f^\star(X))^2\big]\) over a new \(X\), with the fit held fixed: the expected squared error of a prediction, minus the noise variance (0.25 here), which no method can remove. There were two truths:

  • one direction: \(f^\star(x) = \sin(2u) + u^2/2\) with \(u = v^T x\), which depends on \(x\) only through one direction \(v\);
  • radial: \(f^\star(x) = 2\cos\|x\|\), which has no such direction.
Show the code
method_cols <- c(linear = "grey50", kernel = v_teal, frozen200 = m_orange, frozen10 = m_pink, trained10 = v_dark)
plot_feat <- function(tn) {
  d <- feat_mean |> filter(truth == tn) |> pivot_longer(linear:trained10, names_to = "method", values_to = "excess") |>
    mutate(method = factor(method, levels = names(method_names)))
  ggplot(d, aes(n, excess, colour = method)) +
    geom_line(linewidth = 0.9) + geom_point(size = 1.8) +
    scale_x_log10(breaks = ns, labels = big) +
    scale_y_continuous(limits = c(0, NA)) +
    scale_colour_manual(values = method_cols, labels = method_names, name = NULL) +
    labs(title = tn, x = "training rows n", y = "excess risk")
}
plot_feat("one direction") + plot_feat("radial") + plot_layout(guides = "collect")
Figure 14: Excess risk against the number of training rows (log scale), the mean of three data sets at each size, on the two truths: \(p = 10\) standard normal inputs, noise standard deviation 0.5, and each penalized method’s penalty (and the kernel’s bandwidth) chosen on 500 tuning rows.

On the one-direction truth (Figure 14, left), at \(n = 2{,}000\), training the first layer cut the excess risk of the network with 10 units from 0.99 (frozen) to 0.054; 200 frozen units reached 0.55, kernel ridge 0.26, and linear regression 0.97.

The frozen and trained networks with 10 units started from the same weights. In one data set with \(n = 1{,}000\), after training, 3 of the ten units pointed almost along \(v\), with \(|\cos| > 0.99\) between \(w_k\) and \(v\); at the start the closest had \(|\cos| = 0.71\) (Figure 15). Here, where the truth depends on one direction, training found it.

Show the code
align |> mutate(unit = fct_reorder(factor(unit), after)) |>
  ggplot(aes(y = unit)) +
  geom_segment(aes(x = before, xend = after, yend = unit), colour = "grey70", linewidth = 0.7) +
  geom_point(aes(x = before), colour = "grey55", size = 2) +
  geom_point(aes(x = after), colour = v_dark, size = 2.5) +
  scale_x_continuous(limits = c(0, 1)) +
  labs(x = "|cos| between the unit's weights and v", y = "hidden unit")
Figure 15: One data set from the one-direction truth, \(n = 1{,}000\): for each of the ten hidden units of the trained network, \(|\cos|\) of the angle between its input weights \(w_k\) and the direction \(v\), at the start (gray) and after training (dark).

On the radial truth (Figure 14, right), kernel ridge had the lowest excess risk (0.18 to 0.22 across the four sample sizes), and every network, frozen or trained, came within 0.02 of linear regression (about 0.31), which here is close to a constant. Kernel ridge did best on one truth and the trained network on the other, consistent with the no free lunch theorem: no method does best on every distribution.

Deeper networks

A deep network composes layers, \(f = f_L \circ \cdots \circ f_1\): each layer’s units are features of the layer below (Figure 16). Gradients with respect to every weight come from the chain rule applied from the output backward (backpropagation). Large networks are fitted by stochastic gradient descent, whose minibatch gradient is unbiased for the gradient of the training loss.

  • [optional] Backpropagation reuses, at each layer, the derivatives already computed for the layer above, so all the gradients together cost a small multiple of one evaluation of the network.
Show the code
net_picture(list(c("x[1]", "x[2]", "...", "x[p]"), c("h[1]^{(1)}", "h[2]^{(1)}", "h[M[1]]^{(1)}"),
                 c("h[1]^{(2)}", "h[2]^{(2)}", "h[M[2]]^{(2)}"), "f(x)"),
            heads = c("inputs", "layer 1", "layer 2", "output"))
Figure 16: A network with two hidden layers: the units of layer 2 are features of the units of layer 1.

Universal approximation

With enough units, one hidden layer can approximate any continuous function on a closed, bounded set, such as \([0, 1]^p\), as closely as we like (Figure 17). The result says that such weights exist. It says nothing about how many rows are needed to find them, or whether a fit will.

Show the code
target <- function(x) sin(3 * x) + x / 3
xt <- seq(-3, 3, length.out = 200); yt <- target(xt)
best_net <- function(M) {
  fits <- lapply(1:10, function(r) nnet(matrix(xt), yt, size = M, linout = TRUE, maxit = 3000, trace = FALSE, abstol = 1e-10, reltol = 1e-12))
  fits[[which.min(sapply(fits, `[[`, "value"))]]
}
approx_fits <- map_dfr(c(2, 3, 6), function(M) tibble(x = xt, f = drop(predict(best_net(M), matrix(xt))), M = M)) |>
  mutate(M = factor(paste("M =", M), levels = paste("M =", c(2, 3, 6))))
ggplot(approx_fits, aes(x, f)) +
  geom_line(aes(colour = M), linewidth = 1.1) +
  geom_line(data = tibble(x = xt, f = yt), colour = "black", linetype = "dashed", linewidth = 0.7) +
  scale_colour_viridis_d(end = 0.85, name = NULL) +
  labs(x = "x", y = NULL)
Figure 17: A curve (black, dashed) and the closest fits by networks with \(M = 2\), 3, and 6 logistic units, each the best of ten fits to 200 points on the curve, without noise.
NoteStatement [optional]

Universal approximation (Cybenko 1989). For any continuous \(f\) on \([0, 1]^p\), any continuous sigmoidal function \(\sigma\) (such as \(g^{-1}\)), and any \(\epsilon > 0\), there are \(M\) and weights such that \(\big|f(x) - \sum_{k=1}^M \beta_k\,\sigma(w_{k0} + w_k^T x)\big| < \epsilon\) for every \(x\) in \([0, 1]^p\).

Takeaways

  • A network is a linear model on features, and it fits the features to the outcome.
  • With its first layer frozen at random, it is kernel ridge on random features. Training the features helped when the truth depended on one direction they could find, and did not on the radial truth.
  • Depth composes features of features. Fitting is by gradients, and where it stops depends on the start.
  • Universal approximation says that good weights exist, not that data and an optimizer will find them.

Ablation

Reference: Tao (2007), for the last part.

An ablation removes or replaces one part of a method, holds everything else fixed, runs it again on the same data, and compares. Figure 18 shows the parts of double machine learning that the lecture removed.

Show the code
bx <- tribble(~x, ~y, ~lab,
  0, 1, "data\nY, T, Z",
  2.4, 1.75, "learner for ℓ: Y on Z,\nfitted on other folds",
  2.4, 0.25, "learner for m: T on Z,\nfitted on other folds",
  4.9, 1, "residuals\nof Y and of T",
  7.2, 1, "estimate of θ: residual\non residual, ± 1.96 se")
arr <- tribble(~x, ~y, ~xend, ~yend,
  0.55, 1.15, 1.3, 1.6,   0.55, 0.85, 1.3, 0.4,
  3.5, 1.6, 4.0, 1.2,     3.5, 0.4, 4.0, 0.8,
  5.85, 1, 6.25, 1)
tags <- tribble(~x, ~y, ~lab,
  2.4, 2.45, "no cross-fitting: fit on all rows",
  2.4, 1.0, "no learners: linear regressions instead",
  2.4, -0.45, "T not residualized: skip this one",
  0, 0.25, "Y on T, no adjustment:\nskip both learners")
ggplot() +
  geom_segment(data = arr, aes(x, y, xend = xend, yend = yend), arrow = arrow(length = unit(1.8, "mm")), colour = "grey40") +
  geom_label(data = bx, aes(x, y, label = lab), size = 2.9, label.padding = unit(2, "mm"), fill = "#eef3f8") +
  geom_text(data = tags, aes(x, y, label = lab), size = 2.8, colour = m_pink, fontface = "italic") +
  coord_cartesian(xlim = c(-0.5, 8), ylim = c(-0.6, 2.6), clip = "off") +
  theme_void()
Figure 18: Double machine learning as a pipeline, and the part that each row of the lecture’s ablation removed (italic).

The course has run several without the name: permutation importance, leaving one covariate out, every leaderboard’s baseline, and a random forest against bagging.

The lecture’s ablation of double machine learning

The lecture ran each version on the same 100 data sets from the simulation of the first section (Figure 5):

Version Mean \(\hat\theta\) Interval covers \(\theta\) (of 100)
\(Y\) on \(T\), no adjustment 1.48 0
no learners: linear regressions, same folds 1.51 0
\(T\) not residualized 0.67 0
no cross-fitting 1.00 95
all parts: double machine learning 1.01 94

The first two rows keep the confounding: as \(n\) grows they tend to 1.50 and 1.52. The confounding comes through \(Z_2^2\), which has no linear part, so linear partialling out removes none of it; it removes only some of \(T\)’s variation, which makes the bias slightly larger. Without residualizing \(T\), the estimate falls toward 0.50, even with a perfect learner, because it subtracts \(\hat\ell(Z)\), not \(\hat g(Z)\).

Removing cross-fitting changed little for these trees. Paired over the 100 data sets, the in-sample estimate was on average 0.008 lower than the cross-fitted one (standard error 0.003), small beside the estimates’ spread of 0.06. Other learners do need it (see “Cross-fitting”).

NoteLimits with the true functions [optional]

The version without \(T\) residualized subtracts \(\hat\ell(Z)\), and \(\ell\) still contains \(\theta\, m(Z)\).

With the true functions in place of the learners: regressing \(Y\) on \(T\) gives \(\theta + \mathrm{Cov}(T, g)/\mathrm{Var}(T)\), and here \(\mathrm{Cov}(T, g) = \mathrm{Cov}(m, g) = 1\) and \(\mathrm{Var}(T) = 1 + \mathrm{Var}(m) \approx 2\). Linear partialling out gives \(\theta\) plus the same ratio for the parts of \(T\) and \(g\) that a linear regression on \(Z\) leaves, which is 0.52 here. Without residualizing \(T\), the estimate is \(\sum_i T_i\big(Y_i - \ell(Z_i)\big)/\sum_i T_i^2\), and since \(Y - \ell(Z) = \theta\varepsilon_T + \varepsilon_Y\) and \(\mathbb E[T\varepsilon_T] = \mathbb E[\varepsilon_T^2]\), it tends to \(\theta\,\mathbb E[\varepsilon_T^2]/\mathbb E[T^2] = 1/(1 + \mathrm{Var}(m))\).

Rules for an ablation

An ablation is an experiment, and the course’s rules for comparing models apply to it:

  • compare the two versions on the same rows, with paired losses and the standard error of their difference;
  • choose the ablations before the test rows are opened;
  • say whether the reduced version was tuned again;
  • when a method has random starting points, run several.

In the lecture, twenty starting weights for two trained networks on one data set gave median excess risks of 0.058 with 10 units and 0.105 with 20 (Figure 19). But 1 of the twenty starts with 10 units scored worse than every run with 20 (the worst, 0.129): with one run of each, the network with 20 units would have looked better in 5% of pairings. The frozen network with 200 units, drawn for comparison, scored between 0.42 and 0.81, never close to either.

Show the code
seed_lab <- c(trained10 = "trained, M = 10", trained20 = "trained, M = 20", frozen200 = "frozen, M = 200")
seed_runs |> pivot_longer(-start, names_to = "version", values_to = "excess") |>
  mutate(version = factor(seed_lab[version], levels = rev(seed_lab))) |>
  ggplot(aes(excess, version, colour = version)) +
  geom_jitter(height = 0.12, width = 0, size = 2, alpha = 0.75) +
  scale_colour_manual(values = c(m_orange, v_teal, v_dark), guide = "none") +
  scale_x_continuous(limits = c(0, NA)) +
  labs(x = "excess risk, one run per starting point", y = NULL)
Figure 19: Excess risk of three networks on one data set (one direction, \(n = 1{,}000\)), each fitted from twenty random starting weights, with its penalty held fixed.

An ablation answers for one pipeline on one distribution. And whether one part is needed can depend on another part, so removing parts one at a time can mislead.

Working without the tool

Tao’s advice to mathematicians is that once a favorite tool has proved a result, one should try to rewrite the argument without it; a tool that is understood allows this, though the argument becomes longer and messier. The same question applies to methods: how could the job be done without the tool you usually reach for? This lecture’s answers:

Tool Without it What that showed
learners in double machine learning linear partialling out biased here: the confounding is curved
the polynomial kernel explicit features, then ridge the same predictions; more arithmetic once features outnumber rows
a trained first layer frozen random features far worse on one truth, about the same on the other
cross-fitting in-sample residuals little change here, for these trees

Takeaways

  • To learn whether a part of a method is needed, remove it, hold everything else fixed, and run again on the same data.
  • An ablation is an experiment: compare paired results, against their variation across data sets or starting points.
  • A part whose removal changed little in one setting (cross-fitting, for these trees) may be needed in another.
  • Ask how the job could be done without the tool you usually reach for.

References

  • Chernozhukov, V., Chetverikov, D., Demirer, M., Duflo, E., Hansen, C., Newey, W. and Robins, J. (2018). Double/debiased machine learning for treatment and structural parameters. The Econometrics Journal 21(1), C1–C68. doi:10.1111/ectj.12097.
  • CausalML: Chernozhukov, V., Hansen, C., Kallus, N., Spindler, M. and Syrgkanis, V. (2024). Applied Causal Inference Powered by ML and AI. causalml-book.org; arXiv:2403.02467. Chapter 4, section 4.2, and chapter 9, sections 9.1 to 9.3, version 0.1.2 (3 May 2026) of the chapters, as on the site on 4 December 2026.
  • Cybenko, G. (1989). Approximation by superpositions of a sigmoidal function. Mathematics of Control, Signals and Systems 2(4), 303–314. doi:10.1007/BF02551274
  • ISLR: James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021). An Introduction to Statistical Learning with Applications in R, 2nd edition. Springer Texts in Statistics. Springer, New York. doi:10.1007/978-1-0716-1418-1. Sections 7.6, 9.3, 9.5, 10.1, and 10.2.
  • Rahimi, A. and Recht, B. (2007). Random features for large-scale kernel machines. Advances in Neural Information Processing Systems 20, 1177–1184. papers.nips.cc/paper/3182
  • Tao, T. (2007). Learn the limitations of your tools. What’s new (blog), career advice. terrytao.wordpress.com/career-advice/learn-the-limitations-of-your-tools