Curves in a straight-line model: polynomials and splines
Linear regression means linear in the coefficients, not straight. Transform a predictor, or expand it into a spline basis, to fit a curve with the same machinery.
What runs in CodeSplash
- Linear regression (OLS) Verified in Python and R
- Generalized additive model (smooth terms) Verified in Python and R
You will be able to
- Explain "linear in the coefficients"
- Compare polynomials and restricted cubic splines
- Choose the number of knots without chasing noise
- Build a spline basis as a Prepare step that exports to Python and R
Linear in what?
Read"Linear regression" sounds as though it can only draw straight lines. It means the model is linear in the coefficients. This is a linear model:
To least squares, is one more column. Any curve you can write as a sum of known functions of fits with the same arithmetic, the same intervals and the same diagnostics.
When a line isn't enough
ReadFit a straight line of ozone on temperature, wind and solar radiation. looks healthy at 0.606, and yet the RESET testRamsey RESET testAdds powers of the fitted values to a regression. If they help, the model's form has probably missed something. says the form is wrong: = 16.9, p < .001.
Ozone rises slowly in the cool range and steeply in the heat. A straight line misses that in a way can't show. The residual plot can.
New York air quality, 1973Why not high-degree polynomials?
ReflectA quadratic or a cubic is a fine first step. But polynomials are global: moving one point on the left can bend the curve on the far right, and high powers swing wildly at the edges of the data.
Before reading on, think about what you'd want instead. What should happen to a curve at its edges, where data are thin?
Splines work locally
ReadA splineSplineA curve built from short polynomial pieces joined smoothly at knots, which fits with ordinary regression arithmetic. joins short cubic pieces at chosen points called knots, smoothly enough that the joins don't show. Each piece mainly responds to nearby data.
A restricted cubic spline, also called a natural spline, goes further: it forces the curve to be a straight line beyond the outer knots. That tames the edges where polynomials misbehave.
In practice, 3 to 5 knots at quantiles of fit most curves. Each knot costs a parameter, so count them against your rows.
Predict the cost
PredictPredict first
A restricted cubic spline with knots adds columns to the model. How many columns do 5 knots add in place of one straight-line term?
Make your guess between 1 and 8 extra columns, then reveal.
Reveal
Four columns: . That's three more coefficients than the straight line, and three more degrees of freedom spent.
Build it in Prepare
In the appAdd a Spline basis step to a recipe in Prepare. It expands a numeric column into natural or B-spline columns, with knots learned from the data and stored with the recipe, so the export reproduces them.
Then use those columns as predictors in Analyze, and compare the fit with the straight-line model using a nested test. To let the data choose the wiggliness instead, use a generalized additive model, covered later in this track.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("airquality.csv").dropna(subset=["Ozone", "Temp"])
straight = smf.ols("Ozone ~ Temp", data=df).fit()
spline = smf.ols("Ozone ~ cr(Temp, df=5, constraints='center')", data=df).fit() # natural cubic spline
print(straight.rsquared, spline.rsquared, spline.compare_f_test(straight))library(splines)
df <- na.omit(read.csv("airquality.csv")[, c("Ozone", "Temp")])
straight <- lm(Ozone ~ Temp, data = df)
spline <- lm(Ozone ~ ns(Temp, df = 4), data = df)
anova(straight, spline)Check your understanding
CheckpointCheck yourself
Which of these is a linear model?
Show the answer
Answer: a
"Linear" refers to the coefficients. The first model is a weighted sum of known functions of x. The other two have a coefficient inside a non-linear function.
Check yourself
What does a restricted cubic spline do that an ordinary cubic spline doesn't?
Show the answer
Answer: b
Restricting the tails to be linear reduces the wild behavior at the edges, where data are thin.
Check yourself
You have 40 rows and try 12 knots. The curve wiggles through every cluster of points, and R² is high. What's happening?
Show the answer
Answer: b
Each knot spends a degree of freedom. A flexible curve on few rows follows noise and predicts new data poorly.
Recap
Recap- Linear regression is linear in the coefficients, so you can fit curves with the same tools.
- Polynomials are global and unstable at the edges; splines are local, and restricted splines are straight in the tails.
- Three to five knots at quantiles fit most curves. Each one costs a parameter.
- A Spline basis step in Prepare keeps the same knots when the recipe is exported.
Concepts in this lesson