Sub topic 17
Curved relationships with PolynomialFeatures
This chapter assumes you can fit a LinearRegression, read coef_, build a Pipeline, and know why Ridge needs scaled inputs. Here you will fit curved data with a linear model.
Linear in the coefficients, not in the features
"Linear" in linear regression means the prediction is a weighted sum of features. It does not need to be a straight line in the original input. If you add a column holding x squared, the model y = w1*x + w2*x² + b is still linear in w1, w2 and b. Ordinary least squares fits it the same way.
PolynomialFeatures is a transformer that builds these extra columns. With degree=2 and one input x, it produces x and x². With two inputs a and b, it produces a, b, a², a*b and b². The a*b column is an interaction term, so the effect of a can depend on b.
A worked example
The data below follows a parabola plus noise. A straight line cannot capture it, so the pipeline adds a squared term.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(150, 1))
y = 0.5 * X[:, 0] ** 2 - X[:, 0] + rng.normal(0, 0.5, size=150)
model = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
StandardScaler(),
Ridge(alpha=1.0),
)
model.fit(X, y)
print("train R2:", model.score(X, y))Three choices in this pipeline matter:
include_bias=Falsedrops the constant column of ones. The regressor already learns an intercept, so a second one is redundant.StandardScalercomes afterPolynomialFeatures. The columnsxandx²have very different ranges, and Ridge penalizes coefficients unevenly when scales differ.Ridgekeeps the coefficients stable, becausexandx²are correlated.
Choosing the degree
Each increase in degree adds columns. With n inputs, the number of columns grows roughly like n^degree. A high degree lets the curve chase noise, which is overfitting. It also behaves wildly outside the training range, because high powers grow quickly.
Treat degree as a hyperparameter. Compare values with cross-validation, as in earlier chapters, rather than judging by training R². Training R² never decreases as you add terms.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(150, 1))
y = 0.5 * X[:, 0] ** 2 - X[:, 0] + rng.normal(0, 0.5, size=150)
for degree in [1, 2, 3, 6, 10]:
pipe = make_pipeline(
PolynomialFeatures(degree=degree, include_bias=False),
StandardScaler(),
Ridge(alpha=1.0),
)
scores = cross_val_score(pipe, X, y, cv=5, scoring="r2")
print(degree, round(scores.mean(), 3))Degree 1 scores poorly because it underfits. Degree 2 matches the true shape, and higher degrees add little or lose a bit.
Common errors
- Fitting
PolynomialFeatureson the full dataset before splitting. Keep it inside the pipeline so every step is fit on training folds only. - Skipping scaling before a regularized model.
- Interpreting
coef_of the squared term alone. The effect ofxnow depends on bothxandx². - Predicting far outside the training range.
Exercise
Why is a model with a squared feature still called linear regression, and why should degree be chosen by cross-validation rather than training R²?
Show answer
The prediction is a weighted sum of the columns, so it is linear in the coefficients, and least squares can fit it. Training R² never falls as degree rises, so it rewards overfitting. Cross-validated R² uses held-out folds and drops when the curve starts fitting noise.