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 , , , 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 , 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 basis functions has average variance , 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 fixed functions of the input, the basis functions , and fit
The design matrix becomes with entries , and everything in Linear Regression & Least Squares carries over with in place of : , the fitted values are a projection, and the inference formulas still hold. The vector is a feature map, and choosing it well is feature engineering.
| Basis | Character | |
|---|---|---|
| Polynomial | , | global: every coefficient moves the whole curve; badly conditioned at high degree |
| Orthogonal polynomials | Legendre, Chebyshev | the same span as the powers, far better conditioned |
| Step functions | local and piecewise constant: a binned feature, one-hot encoded | |
| Splines | piecewise polynomials joined smoothly at knots | local and smooth: the default for one-dimensional curves |
| Radial basis functions | bumps around centers with width ; work in any dimension | |
| Interactions | the effect of one input depends on the value of another | |
| Fourier | , | periodic patterns: seasons, time of day |
Which of these models is not linear in its parameters?
Show the answer
C.
In the parameter sits inside the exponential, so the model is not a weighted sum of fixed functions of , and least squares has no closed form. Taking logs gives , 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 are nearly collinear on an interval: for 20 equally spaced points on and degree 10, the condition number of the monomial design matrix is about , against about 5 for Legendre polynomials spanning the same functions. Forming squares it, to about , 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 , 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
where each term switches on a new cubic at its knot without breaking smoothness.
knots split the line into pieces, each a cubic with 4 coefficients:
At each knot, the value and the first and second derivatives of neighboring pieces must agree: 3 constraints per knot.
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 on both outer pieces: 4 more constraints. With knots, counting the two boundary knots:
A cubic regression spline has 6 knots. Including the intercept, how many basis functions does it need?
Show the answer
10 functions
: seven cubic pieces have 28 coefficients, and the 6 knots impose 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 at centers , on a grid or at cluster centers. The width 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 , where is bump evaluated at training point , 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 , with the true values at the inputs and noise covariance .
The fitted values are , where projects onto the span of the columns. A projection is symmetric and idempotent, so
The trace of a projection is the dimension it projects onto: . The average variance of the fitted values is
The mean of the fit is , 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 . A generalized linear model (Nelder & Wedderburn, 1972) keeps the linear predictor and changes the rest:
- Random component. Given , follows an exponential-family distribution (Gaussian, Bernoulli, Poisson, gamma, …) with mean .
- Linear predictor. , or with any basis.
- Link function. A monotone with , so the mean is .
| Target | Distribution | Link | Mean | |
|---|---|---|---|---|
| any real number | Gaussian | identity: | ||
| 0 or 1 | Bernoulli | logit: | ||
| counts | Poisson | log: | ||
| positive and skewed (claim sizes, durations) | gamma | log (common choice) |
Model with , so . Dropping the constant , the negative log-likelihood is
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):
The Hessian is a weighted sum of outer products with positive weights , so is convex, and Newton's method becomes a sequence of weighted least-squares fits with weights :
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 , raising by one unit multiplies the expected count by , a rate ratio. Exposure. If case was observed for time (or over an area, or a population of size ), model : the term is an offset with coefficient fixed at 1, and then describes rates per unit of exposure.
In a Poisson regression of yearly hospital visits, the coefficient of a risk score is . By what percentage does one extra point of the score raise the expected number of visits, all else equal?
Show the answer
28 %
, 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 , not by .
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 with sample_weight=t instead, which gives the same coefficients) and it adds an 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 one-dimensional functions in each of inputs has products, and the polynomials of degree at most in variables need monomials: 5,151 for and . Two escapes run through the rest of this topic and the course.
The first assumes additive structure. A generalized additive model has
each a spline with its own smoothness penalty: about parameters instead of , and each can be plotted, so the model explains itself feature by feature. Selected pairwise terms 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 , 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 basis functions for a cubic spline with knots and for a natural one.
- A least-squares fit with basis functions has average variance while its bias falls with ; 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 ; linear, logistic and Poisson regression are all GLMs.
- Poisson regression has gradient and Hessian ; 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.
A full degree-2 polynomial expansion of 10 inputs (constant, linear terms, squares and all pairwise products) has how many features?
- 21
- 56
- 66
- 100
Show the answer
C. 66
: one constant, ten linear terms, ten squares and products. In general the monomials of degree at most in variables number .
A Poisson regression of insurance claims has coefficient on "number of previous claims". What does that mean?
- Each previous claim adds 0.3 to the expected number of claims
- Each previous claim raises the probability of a claim by 30 percentage points
- Each previous claim multiplies the expected number of claims by
- 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
With a log link, , so one more unit of multiplies by : a 35% higher expected count.
With training points, you move from to basis functions and fit by least squares. Ignoring bias, what happens to the average variance of the fitted values?
- It stays the same, because variance depends only on the noise
- It roughly doubles
- It falls, because a richer basis fits better
- It becomes four times larger
Show the answer
D. It becomes four times larger
The average variance is : before and after. Each basis function contributes one unit of .
Your target is a count with many zeros. Why not just fit least squares to instead of using Poisson regression?
- Nothing is wrong; the two give the same estimates
- is undefined, and the exponential of a mean of logs underestimates the mean count
- Least squares cannot be used with transformed targets
- Taking logs makes the model nonlinear in its parameters
Show the answer
B. 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 by Jensen's inequality, so back-transformed predictions are biased low. Poisson regression models directly and handles zeros naturally.
In a generalized linear model, what does the link function connect?
- The mean of given to the linear predictor
- The raw inputs to the basis functions
- Each observed to its own transformed value, before fitting
- The noise variance to the number of features
Show the answer
A. The mean of given to the linear predictor
. The link transforms the mean, not the data: that is how logistic regression keeps probabilities in and Poisson regression keeps rates positive without transforming any observation.
Go deeper
- Generalized Linear Models · Exponential families and link functions: one idea behind many regressions.
- Splines & Additive Models · Smoothing splines, GAMs and interpretable nonlinearity.
- Feature Maps & the Road to Kernels · Explicit feature expansions, their cost, and random features.
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).