Sub topic 17
Curved relationships with PolynomialFeatures
This chapter assumes you can fit a LinearRegression, build a Pipeline, and read cross-validation scores. It also assumes you know why Ridge needs scaled inputs. Here you will see how a model that is linear in its coefficients can still fit a curve. You will also see how to pick the degree and which mistakes to avoid.
Linear in the coefficients, not in the inputs
"Linear" in linear regression means the prediction is a weighted sum of features. It does not mean the relationship with the original input must be a straight line. If you add a column holding x squared, the model is still a weighted sum:
y = b + w1·x + w2·x²
Ordinary least squares solves for w1 and w2 exactly as before. The only change is that the design matrix has an extra column. PolynomialFeatures builds those columns for you.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
X = np.array([[2, 3], [4, 5]])
poly = PolynomialFeatures(degree=2, include_bias=False)
print(poly.fit_transform(X))
print(poly.get_feature_names_out(["a", "b"]))For two inputs a and b, degree 2 produces a, b, a^2, a b and b^2. The a b column is an interaction term. It lets the effect of a depend on the value of b.
A first polynomial pipeline
The data below follow a parabola plus noise. This is the pipeline from the chapter plan, using Ridge to keep the coefficients stable.
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 details matter here.
include_bias=Falseremoves the constant column of ones. The regressor already fits an intercept, so a second constant column is redundant. With plainLinearRegressionit is harmless but wasteful. With Ridge it is a trap, because the penalty would apply to a column that duplicates the intercept's job.StandardScalercomes afterPolynomialFeatures. The squared column has a very different range from the original column. Ridge penalizes all coefficients equally, so unscaled columns get penalized unevenly.- The pipeline guarantees that the scaler's mean and standard deviation are learned from training data only. This is the same leakage protection you used earlier.
Choosing the degree with cross-validation
Training R-squared will never get worse as you raise the degree, because each higher degree contains the lower ones. That makes training score useless for choosing. Use cross-validation instead and treat degree as a hyperparameter.
import numpy as np
from sklearn.linear_model import LinearRegression
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, 12]:
model = make_pipeline(
PolynomialFeatures(degree=degree, include_bias=False),
StandardScaler(),
LinearRegression(),
)
scores = cross_val_score(
model, X, y, cv=5, scoring="neg_root_mean_squared_error"
)
print(f"degree {degree:2d} CV RMSE: {-scores.mean():.3f}")Expect a pattern like this:
- Degree 1 underfits. Its error is clearly above the noise level, and the residuals would show a U shape.
- Degree 2 should land near the noise standard deviation of 0.5. That is the best any model can do on this data.
- Degrees 3 and above add flexibility the data does not need. The error stays flat or rises slightly, and the rise grows with degree as the model starts fitting noise.
Pick the smallest degree whose cross-validated error is close to the best. You can also search degree and alpha together with GridSearchCV, using the step-name prefix polynomialfeatures__degree.
How fast the columns grow
With n input features and degree d, the output has C(n + d, d) − 1 columns (without the bias). That count grows quickly.
| Input features | Degree | Output columns |
|---|---|---|
| 1 | 2 | 2 |
| 5 | 2 | 20 |
| 10 | 2 | 65 |
| 10 | 3 | 285 |
| 20 | 3 | 1770 |
With 285 columns and a few hundred rows, plain OLS will overfit badly. Several options help:
- Use Ridge, Lasso or ElasticNet so the extra columns are shrunk or dropped.
- Set
interaction_only=Trueto keep products of distinct features (a b) but skip powers (a^2). - Apply polynomial expansion only to the columns that need it, using a
ColumnTransformer. - Lower the degree. Degree 2 or 3 covers most practical cases.
Reading the coefficients
After fitting, the coefficients belong to the expanded columns. You can pair them with names from the transformer.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
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)
pipe = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
Ridge(alpha=0.01),
).fit(X, y)
names = pipe[0].get_feature_names_out(["x"])
for name, coef in zip(names, pipe[-1].coef_):
print(name, round(coef, 3))
print("intercept:", round(pipe[-1].intercept_, 3))This version skips the scaler so the numbers match the generating equation. You should see a coefficient near −1 for x and near 0.5 for x^2. In the scaled pipeline the coefficients are in standard-deviation units and are harder to compare to the true equation.
A coefficient for x alone no longer means "the effect of one more unit of x". The effect of x now depends on x itself. The slope at a point is w1 + 2·w2·x. Interpret polynomial models by plotting predictions across the input range, not by reading single coefficients.
Failure modes
- Extrapolation. A polynomial fitted on x between −3 and 3 can produce wild values at x = 6. Higher degrees diverge faster outside the training range. Check that new inputs fall inside the range you trained on.
- Multicollinearity.
xandx^2are strongly correlated when x is all positive, and higher powers are worse. Coefficients become unstable and large. Scaling and Ridge both reduce this problem. Centering x before expansion also helps. - Runaway degree. A high degree on a small dataset makes the curve oscillate between points. This is overfitting in its most visible form.
- Leakage through preprocessing. Fitting a scaler on all the data before cross-validation leaks information. Keep every step inside the pipeline.
- Wrong input shape.
PolynomialFeaturesexpects a 2D array. PassX[:, [0]]orX.reshape(-1, 1)for one feature, not a 1D array.
When to use something other than polynomials
Polynomials are global. A change to the data at one end of the range can shift the fitted curve at the other end. If the curve has local bends, SplineTransformer builds piecewise polynomials that stay local and extrapolate more safely. If you already know the shape, such as a logarithm or a square root, transform the feature or the target directly. That gives a simpler and more interpretable model than a high-degree polynomial.
Exercise
You have 8 numeric features and apply PolynomialFeatures(degree=3, include_bias=False). How many output columns do you get, and which two changes would you make to reduce overfitting risk?
Show answer
The count is C(8 + 3, 3) − 1 = 165 − 1 = 164 columns. To reduce overfitting, replace LinearRegression with Ridge, Lasso or ElasticNet and tune alpha by cross-validation. You could also lower the degree to 2 (44 columns) or set interaction_only=True to drop the pure powers.
Exercise
A colleague fits StandardScaler on the full dataset, then runs crossvalscore on a PolynomialFeatures + Ridge model fitted to the scaled data. Why is the CV score unreliable, and how do you fix it?
Show answer
The scaler saw the validation folds when it learned its mean and standard deviation, so information from held-out rows leaked into training. Put PolynomialFeatures, StandardScaler and Ridge in one Pipeline and pass the pipeline to crossvalscore. The scaler is then refit on the training portion of each fold.