REGRESSION MODELLING FOR HEALTH PRACTITIONERS · CHAPTER 11
Nonlinear Relationships, Splines and Generalized Additive Models
Why go beyond linearity?
Linear models assume that the expected outcome changes linearly with the predictors. In practice, many associations in health research are nonlinear—for example, cholesterol may increase rapidly after a threshold age, or the dose–response relationship between a drug and outcome may plateau. Ignoring nonlinear patterns can lead to poor model fit and misleading inferences. Nonlinear relationships can be modelled by transforming predictors (e.g., square, log) or by using flexible smooth functions such as splines. Generalised additive models (GAMs) extend GLMs by modelling the linear predictor as a sum of smooth functions.
Polynomial and piecewise polynomials
A simple approach to modelling curvature is to include polynomial terms. For example, a quadratic model allows a parabolic relationship. However, high-degree polynomials can behave erratically at the extremes and are sensitive to outliers. Piecewise polynomials or splines join lower-degree polynomials at breakpoints (knots) and maintain smoothness across intervals.
Cubic splines and natural splines
Cubic splines are piecewise cubic polynomials constrained to be
continuous and have continuous first and second derivatives at the
knots. Natural splines impose additional constraints at the boundaries,
reducing unrealistic behaviour at the edges. In R, the
splines package provides bs() for B–splines
and ns() for natural splines. In Python, one can use
patsy’s cr() or the pygam library. In Julia,
the MixedModels and GAM packages support
splines.
Generalized additive models (GAMs)
A generalized additive model extends a GLM by allowing the linear predictor to be a sum of smooth functions of predictors: where are smooth functions estimated from the data (e.g., splines). GAMs preserve interpretability—the effect of each predictor is visualised as a smooth curve—and can capture complex nonlinearities without specifying a particular parametric form.
Worked example: modelling cholesterol by age using splines
Suppose we model cholesterol level as a nonlinear function of age, adjusting for sex. We compare a linear model, a quadratic model, and a natural spline with three knots.
Worked example
R
library(splines)
# df has: Chol, Age, Sex (0/1)
# Linear model
fit_lin <- lm(Chol ~ Age + Sex, data = df)
# Quadratic model
fit_quad <- lm(Chol ~ Age + I(Age^2) + Sex, data = df)
# Natural spline with three knots at quantiles
knots <- quantile(df$Age, probs = c(0.25, 0.5, 0.75))
fit_ns <- lm(Chol ~ ns(Age, knots = knots) + Sex, data = df)
# Plot fitted curves
new_age <- seq(min(df$Age), max(df$Age), length.out=100)
pred_lin <- predict(fit_lin, newdata = data.frame(Age=new_age, Sex=0))
pred_ns <- predict(fit_ns, newdata = data.frame(Age=new_age, Sex=0))
plot(df$Age, df$Chol, col=gray(0.7), pch=16)
lines(new_age, pred_lin, col="blue", lwd=2)
lines(new_age, pred_ns, col="red", lwd=2)
legend("topright", legend=c("Linear","Natural spline"), col=c("blue","red"), lty=1)
Python (pygam)
from pygam import LinearGAM, s, f
# df with Chol, Age, Sex
X = df[['Age','Sex']].values
y = df['Chol'].values
# Fit GAM with smooth term for Age and factor for Sex
gam = LinearGAM(s(0) + f(1)).fit(X, y)
XX = gam.generate_X_grid(term=0, n=100)
plt.scatter(df['Age'], y, alpha=0.3)
plt.plot(XX[:,0], gam.predict(XX), color='red')
Julia
using DataFrames, Statistics, GLM, RCall
# Julia lacks a built-in GAM, but we can call R's mgcv via RCall
R"library(mgcv)"
R_df = rcopy(df) # convert to R data.frame
R"fit_gam <- gam(Chol ~ s(Age) + Sex, data = df)"
R"summary(fit_gam)"
Interpretation
Model selection. Use tools such as generalized cross–validation (GCV), AIC or visual inspection to choose the appropriate flexibility (number of knots or smoothness parameter). Avoid overfitting with too many knots.
Interpretation. Smooth functions can reveal thresholds or plateaus in associations. Plot the smooth functions with confidence intervals to aid interpretation.
Extrapolation. GAMs may behave unpredictably outside the range of the data; avoid extrapolating beyond observed values.
Interactions. GAMs can include interaction terms between smooths or between smooths and linear predictors if biologically plausible.
Exercises
Exercises
For the cholesterol example, compare the linear, quadratic and natural spline models using AIC. Which model fits best? Plot and interpret the estimated curves.
Simulate data where the mean outcome is a nonlinear function of a predictor (e.g., ). Fit a polynomial regression and a GAM and compare the fits.
Use a GAM to model a binary outcome (e.g., obesity) as a smooth function of age and a linear function of sex. Interpret the smooth term.
Discuss the advantages and limitations of splines compared with categorising a continuous predictor (e.g., age groups).
Code examples use illustrative datasets. Supply data with the named columns to run them.