Simple Algorithm
Machine Learning · Convergence · 26 min

Splines & Additive Models

Smoothing splines, GAMs and interpretable nonlinearity.

Among all functions with a square-integrable second derivative, which one best trades closeness to the data against roughness? The question ranges over an infinite-dimensional space, yet the answer is a natural cubic spline with a knot at every data point. This lesson builds the B-spline machinery, proves that theorem, turns smoothing into a generalized ridge regression with an effective number of parameters, and scales up to additive models and the explainable boosting machines built on them.

What you’ll learn

  • Build regression splines in the B-spline basis with the Cox–de Boor recursion, and explain their local support, partition of unity and banded systems.
  • Prove that the minimizer of ∑i(yi−f(xi))2+λ∫f′′2\sum_i(y_i-f(x_i))^2+\lambda\int f''^2 is a natural cubic spline with knots at the data, and analyze the fit as a linear smoother with effective degrees of freedom tr⁡Sλ\operatorname{tr}S_\lambda.
  • Choose λ\lambda by generalized cross-validation or REML, and state the optimal rate n−2m/(2m+d)n^{-2m/(2m+d)} and the equivalent-kernel view of smoothing splines.
  • Fit additive models by backfitting, explain why they escape the curse of dimensionality, and assess GA²M models and explainable boosting machines, including what they cannot tell you.

Regression splines and B-splines

A regression spline is least squares on a spline basis with knots fixed in advance, for example at quantiles of xx, so that each piece sees about the same amount of data. The truncated power basis (x−ξk)+3(x-\xi_k)_+^3 of Basis Functions & Generalized Linear Models spans the right space but is numerically poor: each function is nonzero from its knot to the end of the range, and functions with nearby knots are nearly collinear. The B-spline basis spans exactly the same space with functions that are local, nonnegative and well conditioned.

DerivationThe Cox–de Boor recursion
  1. Bi,0(x)=1{ξi≤x<ξi+1}B_{i,0}(x)=\mathbf 1\{\xi_i\le x<\xi_{i+1}\}

    Start from indicators of the knot intervals (degree 0):

  2. Bi,k(x)=x−ξiξi+k−ξi Bi,k−1(x)+ξi+k+1−xξi+k+1−ξi+1 Bi+1,k−1(x)B_{i,k}(x)=\frac{x-\xi_i}{\xi_{i+k}-\xi_i}\,B_{i,k-1}(x)+\frac{\xi_{i+k+1}-x}{\xi_{i+k+1}-\xi_{i+1}}\,B_{i+1,k-1}(x)

    Raise the degree by blending two neighbors with linear weights that rise across one's support and fall across the other's:

  3. ∑iBi,k(x)=1(partition of unity)\sum_iB_{i,k}(x)=1\qquad(\text{partition of unity})

    By induction, Bi,kB_{i,k} is a piecewise polynomial of degree kk, nonnegative, zero outside [ξi,ξi+k+1)[\xi_i,\xi_{i+k+1}), that is on all but k+1k+1 consecutive intervals, and k−1k-1 times continuously differentiable at simple knots. Away from the ends of the knot sequence the functions sum to one:

Local support has two payoffs. Each row of the design matrix has at most k+1k+1 nonzero entries (four for cubics), so Φ⊤Φ\Phi^\top\Phi is banded: fitting costs O(n)\order{n} to form it and O(K)\order{K} to solve, and moving one data point changes the fit only nearby. And the coefficients act like control points of the curve, which makes penalties on their differences natural: the P-splines of Eilers & Marx (1996) use many equally spaced B-splines and penalize differences between neighboring coefficients.

Near the boundary, the polynomial pieces are fitted from one side only and their variance balloons. Natural splines force linearity beyond the outermost knots, trading a little bias at the edges for much less variance there.

python
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import SplineTransformer
from sklearn.linear_model import RidgeCV

# 19 cubic B-splines (17 knots at quantiles of x), each row summing to 1;
# a ridge penalty on their coefficients, chosen by efficient leave-one-out CV
spline = make_pipeline(
    SplineTransformer(n_knots=17, degree=3, knots="quantile"),
    RidgeCV(alphas=np.logspace(-4, 2, 30)),
)
spline.fit(x.reshape(-1, 1), y)

A penalized regression spline in a few lines. The ridge penalty here shrinks the coefficients toward zero; P-splines and smoothing splines penalize roughness instead, which leaves straight lines unpenalized.

Smoothing splines: the variational theorem

DerivationProof
  1. ∫abg′′2=∫abs′′2+2∫abs′′h′′+∫abh′′2\int_a^bg''^2=\int_a^bs''^2+2\int_a^bs''h''+\int_a^bh''^2

    Take any admissible gg, and let ss be the natural cubic spline that interpolates gg at the nn knots (it exists and is unique). The two functions agree at the data, so they have the same fit term. It suffices to show ∫s′′2≤∫g′′2\int s''^2\le\int g''^2, with equality only when g=sg=s. Put h=g−sh=g-s, which vanishes at every knot, and expand:

  2. ∫abs′′h′′=[s′′h′]x1xn−∫x1xns′′′h′=−∫x1xns′′′h′\int_a^bs''h''=\big[s''h'\big]_{x_1}^{x_n}-\int_{x_1}^{x_n}s'''h'=-\int_{x_1}^{x_n}s'''h'

    Integrate the middle term by parts. Since ss is linear outside [x1,xn][x_1,x_n], s′′s'' vanishes there and at x1x_1 and xnx_n, so the boundary term disappears:

  3. ∫x1xns′′′h′=∑j=1n−1cj(h(xj+1)−h(xj))=0\int_{x_1}^{x_n}s'''h'=\sum_{j=1}^{n-1}c_j\big(h(x_{j+1})-h(x_j)\big)=0

    Between consecutive knots ss is a cubic, so s′′′s''' is a constant cjc_j on (xj,xj+1)(x_j,x_{j+1}), and hh vanishes at both ends of each interval:

  4. ∫abg′′2 ≥ ∫abs′′2,with equality iff g=s\int_a^bg''^2\ \ge\ \int_a^bs''^2,\quad\text{with equality iff }g=s

    So ∫g′′2=∫s′′2+∫h′′2≥∫s′′2\int g''^2=\int s''^2+\int h''^2\ge\int s''^2. Equality forces h′′≡0h''\equiv0: hh is linear and vanishes at n≥2n\ge2 points, so h≡0h\equiv0. Replacing any candidate by its interpolating natural spline never increases the objective, and the minimization reduces to the nn-dimensional space of natural cubic splines, where the objective is strictly convex.

In a basis N1,…,NnN_1,\dots,N_n of natural splines with these knots, f=∑jθjNjf=\sum_j\theta_jN_j, the problem is a generalized ridge regression with penalty matrix Ωjk=∫Nj′′Nk′′\Omega_{jk}=\int N_j''N_k'':

θ^=(N⊤N+λΩ)−1N⊤y,f^=Sλy,Sλ=N(N⊤N+λΩ)−1N⊤.\hat{\boldsymbol\theta}=(N^\top N+\lambda\Omega)^{-1}N^\top\mathbf y,\qquad\hat{\mathbf f}=S_\lambda\mathbf y,\qquad S_\lambda=N(N^\top N+\lambda\Omega)^{-1}N^\top.

SλS_\lambda is symmetric with eigen-decomposition Sλ=∑k11+λdkukuk⊤S_\lambda=\sum_k\frac{1}{1+\lambda d_k}\mathbf u_k\mathbf u_k^\top, where 0=d1=d2<d3≤⋯≤dn0=d_1=d_2<d_3\le\dots\le d_n. The two zero eigenvalues belong to the straight lines, which the penalty does not see; the eigenvectors uk\mathbf u_k oscillate faster as kk grows, so the smoother is a low-pass filter. The effective degrees of freedom

df(λ)=tr⁡Sλ=∑k=1n11+λdk\mathrm{df}(\lambda)=\operatorname{tr}S_\lambda=\sum_{k=1}^n\frac{1}{1+\lambda d_k}

fall from nn (interpolation, λ→0\lambda\to0) to 22 (the least-squares line, λ→∞\lambda\to\infty). Reinsch's algorithm exploits banded structure to compute the fit in O(n)\order{n} operations.

Check your understanding

What does the smoothing spline converge to as λ→∞\lambda\to\infty?

  1. The constant function yˉ\bar y
  2. The least-squares straight line
  3. The zero function
  4. The natural cubic spline that interpolates the data
Show the answer

B. The least-squares straight line

The penalty ∫f′′2\int f''^2 is zero exactly for straight lines, so an infinitely heavy penalty restricts ff to lines, and among lines the fit term picks least squares. That is why df→2\mathrm{df}\to2, not 11 or 00.

Choosing λ, rates and equivalent kernels

Choosing λ\lambda. Smoothing splines are linear smoothers, so leave-one-out costs one fit, and generalized cross-validation, GCV(λ)=n∥(I−Sλ)y∥2/(n−tr⁡Sλ)2\mathrm{GCV}(\lambda)=n\norm{(I-S_\lambda)\mathbf y}^2/(n-\operatorname{tr}S_\lambda)^2, was in fact introduced for splines (Craven & Wahba, 1978); Ridge Regression in Depth derives both. A popular alternative treats the curvy part of ff as a random effect and maximizes the restricted likelihood (REML), the marginal likelihood of the Bayesian view; it is often preferred in practice because the GCV criterion can be flat or have several minima and occasionally undersmooths badly.

How fast can any method learn a curve? Stone (1982) showed that if the regression function has mm bounded derivatives in dd dimensions, the best achievable rate for the mean squared error is n−2m/(2m+d)n^{-2m/(2m+d)}. Cubic smoothing splines (m=2m=2, d=1d=1) attain n−4/5n^{-4/5} when λ\lambda shrinks like n−4/5n^{-4/5} (for the objective normalized by 1/n1/n), slower than the parametric n−1n^{-1} but with no shape assumed beyond smoothness. The exponent collapses as dd grows: the curse of dimensionality in its sharpest form.

Predict before you look

With the optimal rate n−2m/(2m+d)n^{-2m/(2m+d)} and m=2m=2, halving the mean squared error in one dimension takes 25/4≈2.42^{5/4}\approx2.4 times more data. How many times more data does it take in d=10d=10 dimensions?

Show the answer

11.3

The error scales as n−4/14=n−2/7n^{-4/14}=n^{-2/7}, so halving it needs nn multiplied by 27/2≈11.32^{7/2}\approx11.3. Every further halving costs another factor 11.3: a hundredfold error reduction would need about 27/2⋅log⁡2100≈1072^{7/2\cdot\log_2100}\approx10^{7} times the data.

The equivalent kernel. Silverman (1984) showed that for large nn a smoothing spline behaves like a kernel smoother with a variable bandwidth: the fit at xx is approximately a kernel-weighted average of the nearby yiy_i, with kernel KK and a bandwidth hh that varies with xx, where

K(u)=12 e−∣u∣/2sin⁡ ⁣(∣u∣2+π4),h(x)∝λ1/4fX(x)−1/4,K(u)=\tfrac12\,e^{-\abs u/\sqrt2}\sin\!\Big(\frac{\abs u}{\sqrt2}+\frac\pi4\Big),\qquad h(x)\propto\lambda^{1/4}f_X(x)^{-1/4},

and fXf_X is the density of the inputs. KK integrates to one, has small negative side lobes, and its Fourier transform is exactly 1/(1+ω4)1/(1+\omega^4), the frequency response of the penalty ∫f′′2\int f''^2. The spline adapts its window to the data automatically, narrower where inputs are dense, though only through the fourth root of the density.

Additive models and backfitting

A generalized additive model (Hastie & Tibshirani, 1986, 1990) keeps the curse at bay by assuming no interactions:

g(E[y∣x])=α+f1(x1)+f2(x2)+⋯+fd(xd),Efj(xj)=0,g\big(\E[y\mid\mathbf x]\big)=\alpha+f_1(x_1)+f_2(x_2)+\dots+f_d(x_d),\qquad\E f_j(x_j)=0,

where each fjf_j is a smooth function, usually a penalized spline, and the centering makes the decomposition identifiable. If the truth is additive, each fjf_j can be estimated at the one-dimensional rate, and so can the whole model: Stone (1985) proved the rate n−2m/(2m+1)n^{-2m/(2m+1)} whatever the dimension dd.

text
BACKFIT(y, x_1..x_d, smoothers S_1..S_d)        # identity link, squared error
  alpha <- mean(y);  f_j <- 0 for every j
  repeat until no f_j changes:
      for j = 1..d:
          r   <- y - alpha - sum over k != j of f_k     # partial residual
          f_j <- S_j(r against x_j)                     # smooth it in one variable
          f_j <- f_j - mean(f_j)                        # keep the components centered
  return alpha, f_1..f_d

Backfitting is block coordinate descent on the penalized least-squares problem, the same idea as the lasso's coordinate descent with one-dimensional smoothers in place of soft thresholding. For a non-Gaussian response, local scoring wraps it in the IRLS loop of Generalized Linear Models: compute working responses and weights, backfit, repeat.

Buja, Hastie & Tibshirani (1989) studied when backfitting converges: for symmetric smoothers with eigenvalues in [0,1][0,1], such as smoothing splines, it converges to a solution of the penalized problem. They also named the main failure mode, concurvity, the nonlinear analogue of collinearity: when some combination of smooth functions of different inputs is nearly zero, the components are poorly determined even though their sum is fine. Modern software, such as the R package described by Wood (2017), fits all components jointly as penalized regression splines and estimates every smoothing parameter by GCV or REML.

GA²M and explainable boosting machines. Lou, Caruana & Gehrke (2012) compared ways of fitting the shape functions fjf_j and found that gradient boosting with bagged shallow trees gave the most accurate additive models on low- to medium-dimensional data sets. Adding a few pairwise terms fjk(xj,xk)f_{jk}(x_j,x_k) chosen by a fast interaction search gives GA²M (Lou, Caruana, Gehrke & Hooker, 2013). The open-source explainable boosting machine (Nori, Jenkins, Koch & Caruana, 2019) implements it: boosting cycles through the features one at a time with a very small learning rate, bagging stabilizes the shapes, and pairwise interactions are detected automatically. Each term is a curve or a heat map that a domain expert can read and, if necessary, edit.

Key takeaways

  • B-splines span the same space as truncated powers but are local (a cubic lives on 4 intervals), nonnegative and a partition of unity, giving banded, well-conditioned least squares.
  • The minimizer of ∑i(yi−f(xi))2+λ∫f′′2\sum_i(y_i-f(x_i))^2+\lambda\int f''^2 is a natural cubic spline with knots at the data; the fit is SλyS_\lambda\mathbf y with df=∑k1/(1+λdk)\mathrm{df}=\sum_k1/(1+\lambda d_k) running from nn down to 2.
  • Choose λ\lambda by GCV or REML. With mm derivatives the optimal rate is n−2m/(2m+d)n^{-2m/(2m+d)}, n−4/5n^{-4/5} for cubic splines in one dimension; the spline is asymptotically a kernel smoother with Fourier response 1/(1+ω4)1/(1+\omega^4) and bandwidth ∝λ1/4fX−1/4\propto\lambda^{1/4}f_X^{-1/4}.
  • Additive models g(μ)=α+∑jfj(xj)g(\mu)=\alpha+\sum_jf_j(x_j) attain the one-dimensional rate in any dimension and are fitted by backfitting or joint penalized splines; concurvity is their collinearity.
  • GA²M and explainable boosting machines add a few pairwise terms and make every term inspectable, which exposes problems like the asthma paradox but does not make the terms causal.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A smoothing spline is fitted to n=50n=50 points with distinct xx values. What range do its effective degrees of freedom tr⁡Sλ\operatorname{tr}S_\lambda cover as λ\lambda goes from 00 to ∞\infty?

  1. From 50 down to 0
  2. From 50 down to 1
  3. From 50 down to 2
  4. They stay at 50; only the coefficients shrink
Show the answer

C. From 50 down to 2

tr⁡Sλ=∑k1/(1+λdk)\operatorname{tr}S_\lambda=\sum_k1/(1+\lambda d_k) with d1=d2=0d_1=d_2=0. At λ=0\lambda=0 every term is 1 (interpolation, 50 degrees of freedom); as λ→∞\lambda\to\infty only the two unpenalized directions, intercept and slope, survive.

Question 2

On how many consecutive knot intervals is a single cubic B-spline basis function nonzero?

  1. 1
  2. 2
  3. 4
  4. All of them
Show the answer

C. 4

A degree-kk B-spline lives on k+1k+1 consecutive intervals, so a cubic lives on four. That local support makes the design matrix sparse and Φ⊤Φ\Phi^\top\Phi banded.

Question 3

Why can an additive model in d=20d=20 inputs be estimated far more accurately from nn examples than a general smooth function of 20 inputs?

  1. Because additive models are linear in the inputs
  2. Because backfitting is faster than other algorithms
  3. Because it never overfits
  4. Because each component is a function of one input, so if the truth is additive the error decreases at the one-dimensional rate n−2m/(2m+1)n^{-2m/(2m+1)}
Show the answer

D. Because each component is a function of one input, so if the truth is additive the error decreases at the one-dimensional rate n−2m/(2m+1)n^{-2m/(2m+1)}

Stone (1985) showed that additive structure removes dd from the exponent: the rate is the one-dimensional n−4/5n^{-4/5} for m=2m=2, against n−4/24=n−1/6n^{-4/24}=n^{-1/6} for a general function of 20 inputs. The price is the assumption itself: interactions it leaves out are lost.

Question 4

A GA²M for pneumonia mortality shows a lower risk for patients with asthma. The model will be used to decide who can be treated at home. What is the right response?

  1. Trust it: the model is interpretable, so its terms are causal effects
  2. Recognize a treatment-driven pattern (asthmatics received aggressive care), and correct or constrain the term before deployment
  3. Remove the asthma feature and keep everything else unchanged, which fully solves the problem
  4. Switch to a black-box model with the same accuracy, which will not have this problem
Show the answer

B. Recognize a treatment-driven pattern (asthmatics received aggressive care), and correct or constrain the term before deployment

The pattern is real in the data but reflects how asthmatic patients were treated, so acting on it would send high-risk patients home. An intelligible model makes the problem visible; fixing it takes domain knowledge, for instance editing that term.

Further reading

  • C. H. Reinsch, "Smoothing by spline functions," Numerische Mathematik 10, 177–183 (1967).
  • G. Wahba, Spline Models for Observational Data (SIAM, 1990).
  • T. Hastie & R. Tibshirani, Generalized Additive Models (Chapman & Hall, 1990).
  • Y. Lou, R. Caruana & J. Gehrke, "Intelligible models for classification and regression," Proceedings of the 18th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (2012).
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapters 5 and 9.