Foundations to Frontier
Tests
D. Classical Machine Learning › D1 Linear Models for Regression

Spline Regression and Generalized Additive Models (GAMs)

Splines fit flexible curves as piecewise polynomials joined smoothly at knots. Written in a basis (truncated powers or B-splines), a spline fit is just linear regression on basis features, and adding a roughness penalty (smoothing splines, P-splines) lets one parameter λ control smoothness. Generalized additive models extend this to many predictors as a sum of smooth one-dimensional functions, keeping interpretability while avoiding the curse of dimensionality. This page covers regression splines, B-splines, natural splines, smoothing splines and P-splines, effective degrees of freedom and GCV, and GAMs fitted by backfitting, including their blind spot for interactions. In the exercises you build a B-spline basis, P-spline smoothing with GCV, and backfitting; then you model a solar array's output from telemetry and compare a GAM with linear regression and k-NN, with and without an interaction.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Flexible curves from simple pieces

A draughtsman’s spline was a thin strip of wood bent through pegs: it passes the pegs smoothly with no kinks. Spline regression does the same with maths. It joins short polynomial pieces at points called knots so that the curve is smooth where they meet. Add a “stiffness” penalty and you control how much the curve bends to chase the data. A generalized additive model (GAM) uses one such curve per input and adds them up: flexible, yet you can still plot and explain each input’s effect.

P-splines: many bumps, one smoothness knob
18 basis functions · effective degrees of freedom 7.8 · GCV 0.0728
Purple: each B-spline bump multiplied by its coefficient; orange: their sum, the fit; dashed: the truth. With a penalty, the number of knots matters little once it is generous: λ sets the smoothness. Find the λ with the lowest GCV, then compare with λ = 10⁻⁴ (wiggly) and 10⁶ (a straight line, 2 degrees of freedom).
Why engineers care

Many engineering responses are smooth but not linear: output versus temperature, drag versus Mach number, degradation versus age. Splines model them with a few interpretable curves. GAMs are a favourite for explainable models of telemetry, energy use and reliability, because each feature’s effect is a plot you can check against physics.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Spline pieces are joined at…
  2. 2. A GAM predicts with…
  3. 3. In the demo, a very large λ gives…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

A spline is linear regression on new features

Data: x = 0, 1, 2, 3, 4 and y = 0, 1, 2, 2, 2. The response rises, then levels off at x = 2.

Use a linear spline with one knot at 2. Its features are 1, x and (x − 2)₊ = max(x − 2, 0):

x 1 x (x − 2)₊ y
0 1 0 0 0
1 1 1 0 1
2 1 2 0 2
3 1 3 1 2
4 1 4 2 2

Least squares gives y = 0 + 1·x − 1·(x − 2)₊, an exact fit. The slope is 1 before the knot and 1 − 1 = 0 after it. A straight line through the same data has slope 0.5 and misses the bend.

Cubic splines use 1, x, x², x³ and (x − κ)³₊ for each knot κ. The pieces then join with matching value, slope and curvature.

The steps in plain English:

  1. Choose a spline basis: B-splines on many evenly spaced knots, say 10–40.
  2. Build the basis matrix B (one column per basis function).
  3. Fit coefficients by least squares plus a roughness penalty λ·‖Dc‖² (P-spline).
  4. Pick λ by GCV or cross-validation. The effective degrees of freedom tell you how flexible the result is.
  5. For several inputs, fit one smooth function per input and add them (a GAM), cycling through the inputs (backfitting).
📝 Quick check (Level 1)
0/3 answered
  1. 1. (x − 2)₊ at x = 5?
  2. 2. In the hand example, the slope after the knot is…
  3. 3. A cubic spline's pieces join with matching…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Bases, penalties and GAMs

Regression splines. Fix K knots and regress on a degree-d spline basis (K + d + 1 columns including the intercept). The number and position of the knots control smoothness.

B-splines. B-splines are a numerically stable basis for the same space. Each function is a local bump spanning d + 1 knot intervals, and the functions sum to 1 everywhere (partition of unity). They are computed by the Cox–de Boor recursion. The design matrix is banded, so fits are fast.

Natural cubic splines are linear beyond the boundary knots. This reduces the wild behaviour near the edges and saves 4 degrees of freedom.

Smoothing splines. Minimise Σ(yᵢ − f(xᵢ))² + λ∫f″(x)²dx over all functions. The solution is a natural cubic spline with knots at every data point.

P-splines (Eilers and Marx, 1996) are a practical approximation: many B-splines plus a penalty on second differences of neighbouring coefficients: ĉ = (BᵀB + λDᵀD)⁻¹Bᵀy.

Effective df = tr(B(BᵀB + λDᵀD)⁻¹Bᵀ). It runs from the number of basis functions (at λ = 0) down to 2 (a line, at λ → ∞).

GCV = n·RSS/(n − df)².

GAMs. The model is g(E[y]) = α + f₁(x₁) + … + f_p(x_p), with any link g (D1.15). Backfitting cycles through j, smoothing the partial residual y − α − Σₖ≠ⱼ fₖ against xⱼ and centring each fⱼ. Modern software (mgcv) fits all components jointly by penalised likelihood and chooses λ automatically (REML or GCV).

from sklearn.preprocessing import SplineTransformer
from sklearn.linear_model import RidgeCV
from sklearn.pipeline import make_pipeline
spline_model = make_pipeline(SplineTransformer(n_knots=20, degree=3), RidgeCV(alphas=np.logspace(-4, 4, 30)))
from pygam import LinearGAM, s, te
gam = LinearGAM(s(0) + s(1) + s(2) + te(0, 1)).gridsearch(X, y)     # te(): tensor-product interaction
# R: mgcv::gam(y ~ s(theta) + s(temp) + s(age), method = "REML")

Use them when effects are smooth and you want interpretable per-feature curves, with moderate p. Add interactions (tensor products) where physics or residuals demand them. Plain GAMs cannot represent them (exercise 2).

🐍 Exercise 1: B-splines, P-splines and backfitting
Build a cubic B-spline basis by the Cox–de Boor recursion, fit P-splines with a second-difference penalty and choose λ by GCV, compute effective degrees of freedom, and fit an additive model by backfitting; check partition of unity, the straight-line limit, the recovery of a noisy curve, and the recovery of two additive components while a third, irrelevant one stays near zero.
📝 Quick check (Level 2)
0/3 answered
  1. 1. B-spline basis functions at any x sum to…
  2. 2. As λ → ∞, a second-difference P-spline becomes…
  3. 3. Backfitting smooths each feature's…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Theory

Smoothing-spline theorem (Reinsch, 1967; Kimeldorf and Wahba, 1971). Among all twice-differentiable functions, the minimiser of Σ(yᵢ − f(xᵢ))² + λ∫f″² is a natural cubic spline with knots at the unique xᵢ. The infinite-dimensional problem therefore has a finite solution: a reproducing-kernel Hilbert space result that foreshadows kernel methods (D5).

Equivalent kernel. A smoothing spline acts like a kernel smoother with local bandwidth ∝ (λ/density)^(1/4) (Silverman, 1984). So it is closely related to LOESS (D1.19), with automatic adaptation to the data density.

Rates. For f with two derivatives, the optimal λ gives MSE ~ n^(−4/5), the same as local linear regression.

Bayesian view. The penalty is a Gaussian prior on the coefficients (on f″). The P-spline fit is the posterior mean. This gives credible bands and REML selection of λ, as in mgcv.

GAMs and the curse of dimensionality. A p-dimensional smooth needs data growing exponentially in p. A sum of 1-D smooths converges at the 1-D rate (Stone, 1985). The price is no interactions unless you add them: tensor-product smooths te(x₁, x₂) or varying-coefficient terms. Concurvity, the non-linear analogue of collinearity, makes components unidentifiable when features are functionally related.

Relatives:

  • MARS (multivariate adaptive regression splines): adaptive hinge functions with interactions;
  • EBMs (explainable boosting machines): GAMs fitted by boosting;
  • neural additive models;
  • KANs: learnable splines on network edges.

Interview questions.

  • Why penalise instead of choosing knots? Knot placement is a hard combinatorial problem. With many knots and a penalty, one continuous λ does the job and is easy to tune.
  • How do you detect a missing interaction in a GAM? Plot residuals against pairs of features, compare with a model that adds a te() term (AIC or CV), or compare with a flexible model such as boosting.
📝 Quick check (Level 3)
0/3 answered
  1. 1. The smoothing-spline minimiser is…
  2. 2. GAMs avoid the curse of dimensionality because…
  3. 3. The non-linear analogue of collinearity in GAMs is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Explaining a solar array’s output

History.

  • Schoenberg (1946) coined “spline” and studied spline approximation.
  • De Boor and Cox (1972) gave the stable B-spline recursion.
  • Reinsch (1967) and Wahba developed smoothing splines and GCV (Craven and Wahba, 1979).
  • Hastie and Tibshirani (1986, 1990) introduced GAMs and backfitting.
  • Eilers and Marx (1996) introduced P-splines.
  • Wood’s mgcv (2000s) made automatic smoothness selection by REML standard.
  • Explainable boosting machines (Lou, Caruana et al., 2012–2019) brought GAMs to high-stakes ML.

Exercise 1.

  • The B-spline basis sums to 1 everywhere.
  • On sin 2πx + x with n = 200 and σ = 0.25, GCV picks λ = 10. The fit has 7.6 effective degrees of freedom and MSE 0.0013.
  • As λ → ∞, the effective df tends to 2 and the fit to a straight line.
  • Backfitting recovers sin(3x₁) and x₂² with errors of about 0.001, while the irrelevant third feature’s component stays flat (sd 0.03).

Exercise 2: solar-array current. Setup: features are sun angle, temperature (with a hot-panel knee), array age (saturating degradation) and one irrelevant channel. Train on 400 points; λ and k are chosen on a validation split; 15 datasets. The table shows the test RMSE; the noise standard deviation is 0.15.

Truth Linear GAM (P-spline backfitting) k-NN
Additive 0.500 0.155 0.537
With a sun-angle × temperature interaction 0.710 0.613 0.518
  • When the truth is additive, the GAM reaches the noise floor (0.155 against σ = 0.15). It is more than 3 times better than linear regression and k-NN. k-NN suffers from the 4-D curse of dimensionality and the irrelevant feature.
  • When the truth contains an interaction, the GAM’s error quadruples. It can only add up one-dimensional effects. k-NN, which assumes no structure, now wins, though it is still far from the noise level.
  • The remedy is to add a tensor-product term te(θ, T), or to use a flexible model and inspect it with partial-dependence plots.
🐍 Exercise 2 (research): additive models for solar-array telemetry
Simulate solar-array output from sun angle, temperature, age and an irrelevant feature, with an additive truth or with an interaction; compare linear regression, a P-spline additive model fitted by backfitting and k-NN (tuned on a validation split) by test RMSE.

Splines and GAMs in AI, robotics and aerospace

  • Trajectory generation: B-spline and minimum-snap polynomial trajectories for drones and manipulators.
  • Aerodynamic and engine tables: smooth interpolation of coefficient tables in flight dynamics models.
  • Interpretable telemetry models: GAMs and EBMs for power, thermal and degradation trends.
  • Neural networks: spline-based activations and KANs; splines in neural ODEs and implicit fields.

References

  1. C. de Boor (2001). A Practical Guide to Splines, revised ed. Springer.
  2. P. H. C. Eilers, B. D. Marx (1996). “Flexible smoothing with B-splines and penalties.” Statistical Science 11(2).
  3. T. Hastie, R. Tibshirani (1990). Generalized Additive Models. Chapman & Hall.
  4. S. N. Wood (2017). Generalized Additive Models: An Introduction with R, 2nd ed. CRC Press.
  5. P. Craven, G. Wahba (1979). “Smoothing noisy data with spline functions.” Numerische Mathematik 31.