Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 9
Non-Linear Modeling with Polynomial Features & Splines
Real-world relationships are frequently non-linear (diminishing marginal returns, acceleration curves, seasonal waves). Polynomial feature expansion projects linear algorithms into higher-dimensional feature spaces, allowing linear models to fit curves: y = w0 + w1 x + w2 x² + ... + wn x^n. To avoid Runge's phenomenon (wild polynomial oscillations at the boundaries), modern practitioners employ B-Splines (`SplineTransformer`) for localized non-linear fitting.
Polynomial Features vs B-Splines in Scikit-Learn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, SplineTransformer
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
# Generate non-linear sinusoidal data
np.random.seed(42)
n = 80
X = np.sort(np.random.uniform(0, 10, size=n)).reshape(-1, 1)
y = np.sin(X.ravel()) * 10 + np.random.normal(0, 1.5, size=n)
# 1. High-Degree Polynomial Pipeline (Susceptible to boundary oscillation)
poly_model = Pipeline([
('poly', PolynomialFeatures(degree=5, include_bias=False)),
('ridge', Ridge(alpha=1.0))
])
poly_model.fit(X, y)
# 2. B-Spline Transformer Pipeline (Piecewise cubic polynomials joined smoothly at knots)
spline_model = Pipeline([
('spline', SplineTransformer(n_knots=6, degree=3, extrapolation='linear')),
('ridge', Ridge(alpha=1.0))
])
spline_model.fit(X, y)
# Evaluate on dense evaluation grid
X_grid = np.linspace(0, 10, 500).reshape(-1, 1)
poly_pred = poly_model.predict(X_grid)
spline_pred = spline_model.predict(X_grid)
print(f"Polynomial Degree 5 Test MSE: {mean_squared_error(y, poly_model.predict(X)):.4f}")
print(f"B-Spline (6 knots) Test MSE : {mean_squared_error(y, spline_model.predict(X)):.4f}")
print("B-Splines prevent boundary oscillations while preserving non-linear capacity!")Pro Tip: Dimensionality Explosion with PolynomialFeatures
For a dataset with p features expanded to degree d, the number of generated features scales combinatorially: `(p + d)! / (p! * d!)`. Expanding 30 features to degree 3 produces 5,456 columns. Always set `interaction_only=True` to generate interaction terms without higher-order self-powers, or use `SplineTransformer`.
MlPolynomialRegression Visual Representation
Hands-On Challenge: Build a Spline Knot Tuning GridSearch
Set up a `GridSearchCV` pipeline that optimizes the number of spline knots (`n_knots`: 4, 6, 8, 12) and spline degree (2, 3) for fitting non-linear engine emissions data.
Quick Quiz & Key Concept Checks
Common Pitfall: Unscaled Features in Polynomial Expansions
If feature x has values near 1,000, `x³ = 1,000,000,000`. Unscaled polynomial terms produce massive floating-point conditioning errors during matrix multiplication. Always apply `StandardScaler` BEFORE and AFTER polynomial expansion.