Simple Algorithm
Machine Learning · Descent · 22 min

Basis Functions & Generalized Linear Models

Polynomials, splines and link functions: linear models that bend.

A straight line cannot follow a curve, but a linear model can: it only has to be linear in its parameters, not in its inputs. Feed least squares the features xx, x2x^2, x3x^3, or a row of smooth bumps, and it fits curves with all of its machinery intact. Replace the Gaussian noise by a Poisson or Bernoulli distribution, connect it through a link function, and the same linear predictor models counts and probabilities.

What you’ll learn

  • Write a basis-function model f(x)=w⊤φ(x)f(\mathbf x)=\mathbf w^\top\boldsymbol\varphi(\mathbf x), build its design matrix, and fit it by least squares with polynomial, spline, radial and interaction features.
  • Compare global and local bases: explain why high-degree polynomials are unstable, and count the basis functions of cubic and natural cubic splines.
  • Show that a least-squares fit with MM basis functions has average variance σ2M/n\sigma^2M/n, and use it to reason about the bias–variance trade-off.
  • Define a generalized linear model by its distribution, linear predictor and link function, derive the gradient and Hessian of Poisson regression, and read its coefficients as rate ratios.

Linear in the parameters

Least squares never needed the inputs to enter linearly. It needs a model that is linear in the weights. Choose MM fixed functions of the input, the basis functions φ1,…,φM\varphi_1,\dots,\varphi_M, and fit

f(x)=∑m=1Mwm φm(x)=w⊤φ(x).f(\mathbf x)=\sum_{m=1}^Mw_m\,\varphi_m(\mathbf x)=\mathbf w^\top\boldsymbol\varphi(\mathbf x).

The design matrix becomes Φ∈Rn×M\Phi\in\R^{n\times M} with entries Φim=φm(xi)\Phi_{im}=\varphi_m(\mathbf x_i), and everything in Linear Regression & Least Squares carries over with Φ\Phi in place of XX: w^=(Φ⊤Φ)−1Φ⊤y\hat{\mathbf w}=(\Phi^\top\Phi)^{-1}\Phi^\top\mathbf y, the fitted values are a projection, and the inference formulas still hold. The vector φ(x)\boldsymbol\varphi(\mathbf x) is a feature map, and choosing it well is feature engineering.

Basisφm(x)\varphi_m(x)Character
Polynomialxmx^m, m=0,…,M−1m=0,\dots,M-1global: every coefficient moves the whole curve; badly conditioned at high degree
Orthogonal polynomialsLegendre, Chebyshevthe same span as the powers, far better conditioned
Step functions1{ξm−1≤x<ξm}\mathbf 1\{\xi_{m-1}\le x<\xi_m\}local and piecewise constant: a binned feature, one-hot encoded
Splinespiecewise polynomials joined smoothly at knotslocal and smooth: the default for one-dimensional curves
Radial basis functionsexp⁡(−∥x−cm∥2/(2ℓ2))\exp\big(-\norm{\mathbf x-\mathbf c_m}^2/(2\ell^2)\big)bumps around centers cm\mathbf c_m with width ℓ\ell; work in any dimension
Interactionsxjxkx_jx_kthe effect of one input depends on the value of another
Fouriersin⁡(2πmx/T)\sin(2\pi mx/T), cos⁡(2πmx/T)\cos(2\pi mx/T)periodic patterns: seasons, time of day
Common basis families. Several can be combined in one model; the fit is still a single least-squares problem.
Check your understanding

Which of these models is not linear in its parameters?

  1. y=w0+w1sin⁡x+w2exy=w_0+w_1\sin x+w_2e^x
  2. y=w0+w1log⁡xy=w_0+w_1\log x
  3. y=w0 ew1xy=w_0\,e^{w_1x}
  4. y=w0+w1x1+w2x1x2y=w_0+w_1x_1+w_2x_1x_2
Show the answer

C. y=w0 ew1xy=w_0\,e^{w_1x}

In w0ew1xw_0e^{w_1x} the parameter w1w_1 sits inside the exponential, so the model is not a weighted sum of fixed functions of xx, and least squares has no closed form. Taking logs gives log⁡y=log⁡w0+w1x\log y=\log w_0+w_1x, which is linear, but fitting that changes the noise model.

Global and local bases

Polynomial regression has two problems at high degree. Statistically, the fit oscillates, worst near the ends of the data; interpolating at equally spaced points can even diverge as the degree grows (Runge's phenomenon). Numerically, the columns xmx^m are nearly collinear on an interval: for 20 equally spaced points on [0,1][0,1] and degree 10, the condition number of the monomial design matrix is about 2.4×1072.4\times10^7, against about 5 for Legendre polynomials spanning the same functions. Forming Φ⊤Φ\Phi^\top\Phi squares it, to about 6×10146\times10^{14}, close to the limits of double precision. Use an orthogonal basis or a QR solver (The Geometry of Least Squares).

Local bases avoid both problems. A spline cuts the range at knots ξ1<⋯<ξK\xi_1<\dots<\xi_K, fits a polynomial on each piece, and joins the pieces smoothly. For cubic splines the joins match the value, slope and curvature, which the eye cannot tell from a smooth curve. One basis is the truncated power basis

1, x, x2, x3, (x−ξ1)+3, …, (x−ξK)+3,(u)+=max⁡(u,0),1,\ x,\ x^2,\ x^3,\ (x-\xi_1)_+^3,\ \dots,\ (x-\xi_K)_+^3,\qquad(u)_+=\max(u,0),

where each term (x−ξk)+3(x-\xi_k)_+^3 switches on a new cubic at its knot without breaking smoothness.

DerivationHow many parameters does a cubic spline have?
  1. 4(K+1) coefficients4(K+1)\ \text{coefficients}

    KK knots split the line into K+1K+1 pieces, each a cubic with 4 coefficients:

  2. 4(K+1)−3K=K+44(K+1)-3K=K+4

    At each knot, the value and the first and second derivatives of neighboring pieces must agree: 3 constraints per knot.

  3. natural cubic spline:K+4−4=K basis functions\text{natural cubic spline:}\quad K+4-4=K\ \text{basis functions}

    That matches the truncated power basis: 4 global terms plus one per knot. A natural cubic spline is also linear beyond the outermost knots, which imposes f′′=f′′′=0f''=f'''=0 on both outer pieces: 4 more constraints. With KK knots, counting the two boundary knots:

Predict before you look

A cubic regression spline has 6 knots. Including the intercept, how many basis functions does it need?

Show the answer

10 functions

K+4=10K+4=10: seven cubic pieces have 28 coefficients, and the 6 knots impose 3×6=183\times6=18 smoothness constraints. The B-spline basis of Splines & Additive Models spans exactly the same 10-dimensional space with local, well-conditioned functions.

Radial basis functions place bumps exp⁡(−∥x−cm∥2/(2ℓ2))\exp(-\norm{\mathbf x-\mathbf c_m}^2/(2\ell^2)) at centers cm\mathbf c_m, on a grid or at cluster centers. The width ℓ\ell sets the smoothness: small widths give wiggly fits, large ones nearly flat fits. Put a center at every training point and add the quadratic penalty λ w⊤Kw\lambda\,\mathbf w^\top K\mathbf w, where KikK_{ik} is bump kk evaluated at training point ii, and you have kernel ridge regression, which Feature Maps & the Road to Kernels derives.

More features, more variance

Every basis function adds flexibility, and flexibility has a price that can be computed exactly. Fix the inputs and write y=f+ε\mathbf y=\mathbf f+\boldsymbol\varepsilon, with f\mathbf f the true values at the inputs and noise covariance σ2I\sigma^2I.

DerivationThe variance of a fit counts its parameters
  1. Cov⁡(y^)=σ2HH⊤=σ2H\Cov(\hat{\mathbf y})=\sigma^2HH^\top=\sigma^2H

    The fitted values are y^=Hy\hat{\mathbf y}=H\mathbf y, where H=Φ(Φ⊤Φ)−1Φ⊤H=\Phi(\Phi^\top\Phi)^{-1}\Phi^\top projects onto the span of the MM columns. A projection is symmetric and idempotent, so

  2. 1n∑i=1nVar⁡(y^i)=σ2tr⁡Hn=σ2Mn\frac1n\sum_{i=1}^n\Var(\hat y_i)=\frac{\sigma^2\operatorname{tr}H}{n}=\frac{\sigma^2M}{n}

    The trace of a projection is the dimension it projects onto: tr⁡H=tr⁡((Φ⊤Φ)−1Φ⊤Φ)=M\operatorname{tr}H=\operatorname{tr}\big((\Phi^\top\Phi)^{-1}\Phi^\top\Phi\big)=M. The average variance of the fitted values is

  3. 1nE∥y^−f∥2=1n∥(I−H)f∥2⏟bias2, falls with M+σ2Mn⏟variance, grows with M\frac1n\E\norm{\hat{\mathbf y}-\mathbf f}^2=\underbrace{\frac1n\norm{(I-H)\mathbf f}^2}_{\text{bias}^2\text{, falls with }M}+\underbrace{\frac{\sigma^2M}n}_{\text{variance, grows with }M}

    The mean of the fit is HfH\mathbf f, the projection of the truth onto the span. Its error, the bias, can only shrink as basis functions are added, because the span grows. Together:

Generalized linear models

Squared error and a mean that is a straight line are the wrong model for many targets. Counts cannot be negative, and their spread grows with their mean. Probabilities must stay in [0,1][0,1]. A generalized linear model (Nelder & Wedderburn, 1972) keeps the linear predictor and changes the rest:

  1. Random component. Given x\mathbf x, yy follows an exponential-family distribution (Gaussian, Bernoulli, Poisson, gamma, …) with mean μ(x)\mu(\mathbf x).
  2. Linear predictor. η=w⊤x\eta=\mathbf w^\top\mathbf x, or w⊤φ(x)\mathbf w^\top\boldsymbol\varphi(\mathbf x) with any basis.
  3. Link function. A monotone gg with g(μ)=ηg(\mu)=\eta, so the mean is μ=g−1(w⊤x)\mu=g^{-1}(\mathbf w^\top\mathbf x).
TargetDistributionLink g(μ)g(\mu)Mean μ=g−1(η)\mu=g^{-1}(\eta)Var⁡(y)\Var(y)
any real numberGaussianidentity: μ\muη\etaσ2\sigma^2
0 or 1Bernoullilogit: log⁡μ1−μ\log\frac{\mu}{1-\mu}11+e−η\dfrac1{1+e^{-\eta}}μ(1−μ)\mu(1-\mu)
counts 0,1,2,…0,1,2,\dotsPoissonlog: log⁡μ\log\mueηe^\etaμ\mu
positive and skewed (claim sizes, durations)gammalog (common choice)eηe^\etaϕ μ2\phi\,\mu^2
Linear regression and logistic regression are the first two rows; Poisson regression is the third. The last column is why a GLM is more than a transformed least-squares fit: each family carries its own relation between mean and variance, and the fit weights each observation accordingly.
DerivationPoisson regression
  1. ℓ(w)=∑i=1n(ew⊤xi−yi w⊤xi)\ell(\mathbf w)=\sum_{i=1}^n\Big(e^{\mathbf w^\top\mathbf x_i}-y_i\,\mathbf w^\top\mathbf x_i\Big)

    Model yi∼Poisson(μi)y_i\sim\mathrm{Poisson}(\mu_i) with log⁡μi=w⊤xi\log\mu_i=\mathbf w^\top\mathbf x_i, so P(yi)=e−μiμiyi/yi!P(y_i)=e^{-\mu_i}\mu_i^{y_i}/y_i!. Dropping the constant log⁡yi!\log y_i!, the negative log-likelihood is

  2. ∇ℓ(w)=∑i=1n(μi−yi) xi\nabla\ell(\mathbf w)=\sum_{i=1}^n(\mu_i-y_i)\,\mathbf x_i

    Its gradient has the same form as for least squares and logistic regression, prediction minus target times input, a consequence of the log being the canonical link for the Poisson (Generalized Linear Models):

  3. ∇2ℓ(w)=∑i=1nμi xixi⊤⪰0\nabla^2\ell(\mathbf w)=\sum_{i=1}^n\mu_i\,\mathbf x_i\mathbf x_i^\top\succeq0

    The Hessian is a weighted sum of outer products with positive weights μi\mu_i, so ℓ\ell is convex, and Newton's method becomes a sequence of weighted least-squares fits with weights μi\mu_i:

  4. ∑i=1n(yi−μ^i) xi=0⟹∑i=1nμ^i=∑i=1nyi\sum_{i=1}^n(y_i-\hat\mu_i)\,\mathbf x_i=\mathbf 0\quad\Longrightarrow\quad\sum_{i=1}^n\hat\mu_i=\sum_{i=1}^ny_i

    At the optimum the gradient vanishes. With an intercept (a constant feature), one of these equations says that the fitted counts add up to the observed counts:

Reading the coefficients. Since μ=ew0ew1x1⋯\mu=e^{w_0}e^{w_1x_1}\cdots, raising xjx_j by one unit multiplies the expected count by ewje^{w_j}, a rate ratio. Exposure. If case ii was observed for time tit_i (or over an area, or a population of size tit_i), model log⁡μi=log⁡ti+w⊤xi\log\mu_i=\log t_i+\mathbf w^\top\mathbf x_i: the term log⁡ti\log t_i is an offset with coefficient fixed at 1, and w\mathbf w then describes rates per unit of exposure.

Predict before you look

In a Poisson regression of yearly hospital visits, the coefficient of a risk score is wj=0.25w_j=0.25. By what percentage does one extra point of the score raise the expected number of visits, all else equal?

Show the answer

28 %

e0.25≈1.284e^{0.25}\approx1.284, so each point multiplies the expected count by 1.284: about 28% more visits. The effect is multiplicative, so four extra points multiply it by e1≈2.72e^{1}\approx2.72, not by 1+4×0.281+4\times0.28.

python
import numpy as np
import statsmodels.api as sm

# y: counts, X: features, t: exposure (e.g. years each case was observed)
model = sm.GLM(y, sm.add_constant(X), family=sm.families.Poisson(), offset=np.log(t))
fit = model.fit()                   # maximum likelihood, computed by IRLS
print(fit.params)                   # coefficients on the log scale
print(np.exp(fit.params))           # rate ratios per unit of each feature
print(fit.deviance, fit.df_resid)   # goodness of fit (see the Convergence lesson)

scikit-learn's PoissonRegressor fits Poisson regression too, but it has no offset argument (fit the rate y/ty/t with sample_weight=t instead, which gives the same coefficients) and it adds an ℓ2\ell_2 penalty by default (alpha=1.0); set alpha=0 for the plain maximum-likelihood fit.

Additive models and the road ahead

In several dimensions a full basis expansion explodes. A grid of MM one-dimensional functions in each of dd inputs has MdM^d products, and the polynomials of degree at most pp in dd variables need (d+pp)\binom{d+p}{p} monomials: 5,151 for d=100d=100 and p=2p=2. Two escapes run through the rest of this topic and the course.

The first assumes additive structure. A generalized additive model has

g(μ)=w0+f1(x1)+f2(x2)+⋯+fd(xd),g(\mu)=w_0+f_1(x_1)+f_2(x_2)+\dots+f_d(x_d),

each fjf_j a spline with its own smoothness penalty: about dMdM parameters instead of MdM^d, and each fjf_j can be plotted, so the model explains itself feature by feature. Selected pairwise terms fjk(xj,xk)f_{jk}(x_j,x_k) can be added where the data demand them. The second escape never writes the features down at all: kernels compute inner products of huge, even infinite, feature vectors directly.

Key takeaways

  • "Linear" means linear in the weights: with basis functions φ(x)\boldsymbol\varphi(\mathbf x), least squares fits curves, interactions and periodic patterns with all of its machinery intact.
  • High-degree polynomials are global, oscillate and are badly conditioned; splines are local and smooth, with K+4K+4 basis functions for a cubic spline with KK knots and KK for a natural one.
  • A least-squares fit with MM basis functions has average variance σ2M/n\sigma^2M/n while its bias falls with MM; penalties let you keep a rich basis without paying the full variance.
  • A GLM combines an exponential-family distribution, a linear predictor and a link g(μ)=w⊤xg(\mu)=\mathbf w^\top\mathbf x; linear, logistic and Poisson regression are all GLMs.
  • Poisson regression has gradient ∑i(μi−yi)xi\sum_i(\mu_i-y_i)\mathbf x_i and Hessian ∑iμixixi⊤\sum_i\mu_i\mathbf x_i\mathbf x_i^\top; its coefficients are log rate ratios, and exposure enters as an offset.

Check yourself

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

Question 1

A full degree-2 polynomial expansion of 10 inputs (constant, linear terms, squares and all pairwise products) has how many features?

  1. 21
  2. 56
  3. 66
  4. 100
Show the answer

C. 66

1+10+10+45=66=(122)1+10+10+45=66=\binom{12}{2}: one constant, ten linear terms, ten squares and (102)=45\binom{10}2=45 products. In general the monomials of degree at most pp in dd variables number (d+pp)\binom{d+p}{p}.

Question 2

A Poisson regression of insurance claims has coefficient 0.30.3 on "number of previous claims". What does that mean?

  1. Each previous claim adds 0.3 to the expected number of claims
  2. Each previous claim raises the probability of a claim by 30 percentage points
  3. Each previous claim multiplies the expected number of claims by e0.3≈1.35e^{0.3}\approx1.35
  4. Each previous claim multiplies the expected number of claims by 0.3
Show the answer

C. Each previous claim multiplies the expected number of claims by e0.3≈1.35e^{0.3}\approx1.35

With a log link, μ=exp⁡(w0+0.3x+… )\mu=\exp(w_0+0.3x+\dots), so one more unit of xx multiplies μ\mu by e0.3≈1.35e^{0.3}\approx1.35: a 35% higher expected count.

Question 3

With n=200n=200 training points, you move from M=10M=10 to M=40M=40 basis functions and fit by least squares. Ignoring bias, what happens to the average variance of the fitted values?

  1. It stays the same, because variance depends only on the noise
  2. It roughly doubles
  3. It falls, because a richer basis fits better
  4. It becomes four times larger
Show the answer

D. It becomes four times larger

The average variance is σ2M/n\sigma^2M/n: σ2⋅10/200=0.05σ2\sigma^2\cdot10/200=0.05\sigma^2 before and σ2⋅40/200=0.2σ2\sigma^2\cdot40/200=0.2\sigma^2 after. Each basis function contributes one unit of tr⁡H\operatorname{tr}H.

Question 4

Your target is a count with many zeros. Why not just fit least squares to log⁡y\log y instead of using Poisson regression?

  1. Nothing is wrong; the two give the same estimates
  2. log⁡0\log0 is undefined, and the exponential of a mean of logs underestimates the mean count
  3. Least squares cannot be used with transformed targets
  4. Taking logs makes the model nonlinear in its parameters
Show the answer

B. log⁡0\log0 is undefined, and the exponential of a mean of logs underestimates the mean count

Zeros must be dropped or shifted by an arbitrary constant, and even without zeros exp⁡(Elog⁡y)≤Ey\exp(\E\log y)\le\E y by Jensen's inequality, so back-transformed predictions are biased low. Poisson regression models log⁡E[y]\log\E[y] directly and handles zeros naturally.

Question 5

In a generalized linear model, what does the link function connect?

  1. The mean of yy given x\mathbf x to the linear predictor w⊤x\mathbf w^\top\mathbf x
  2. The raw inputs to the basis functions
  3. Each observed yiy_i to its own transformed value, before fitting
  4. The noise variance to the number of features
Show the answer

A. The mean of yy given x\mathbf x to the linear predictor w⊤x\mathbf w^\top\mathbf x

g(E[y∣x])=w⊤xg(\E[y\mid\mathbf x])=\mathbf w^\top\mathbf x. The link transforms the mean, not the data: that is how logistic regression keeps probabilities in (0,1)(0,1) and Poisson regression keeps rates positive without transforming any observation.

Go deeper

Further reading

  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapters 5 and 9.
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 3 and §4.3.
  • J. A. Nelder & R. W. M. Wedderburn, "Generalized linear models," Journal of the Royal Statistical Society, Series A 135(3), 370–384 (1972).
  • P. McCullagh & J. A. Nelder, Generalized Linear Models, 2nd ed. (Chapman & Hall, 1989).