Basis Functions and Overfitting
"Linear" regression only needs to be linear in the parameters, not in the inputs. Replace by a vector of features (powers, sines, bumps) and the same least-squares machinery fits curves. The price is a richer model that can overfit, so this lesson also shows how to detect and control it.
Feature maps
With the feature matrix , , everything from the previous lesson carries over with replaced by : .
Common choices:
| Basis | Notes | |
|---|---|---|
| polynomial | simple; ill-conditioned for high degree unless is scaled to | |
| Gaussian RBF | local bumps at centres | |
| Fourier | , | periodic signals |
import numpy as np
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 1, 30))
y = np.sin(2 * np.pi * x) + 0.15 * rng.normal(size=30)
centres = np.linspace(0, 1, 8)
def rbf(x): return np.column_stack([np.ones_like(x)] + [np.exp(-(x - c)**2 / (2 * 0.1**2)) for c in centres])
def poly(x, d=5): return np.vander(2 * x - 1, d + 1, increasing=True)
x_test = np.linspace(0, 1, 500); y_test = np.sin(2 * np.pi * x_test)
for name, feat in (("RBF (9 features)", rbf), ("poly deg 5", poly)):
theta = np.linalg.lstsq(feat(x), y, rcond=None)[0]
print(f"{name:17s} train MSE {np.mean((feat(x) @ theta - y)**2):.4f} "
f"error vs true curve {np.mean((feat(x_test) @ theta - y_test)**2):.4f}")RBF (9 features) train MSE 0.0125 error vs true curve 0.0064
poly deg 5 train MSE 0.0147 error vs true curve 0.0055
Conditioning of polynomial features
Raw powers on produce columns of wildly different scale that look almost alike, so is close to singular. Scaling the input to (or using orthogonal polynomials) fixes it.
import numpy as np
x = np.linspace(0, 10, 50)
for d in (5, 10):
raw = np.vander(x, d + 1, increasing=True)
scaled = np.vander(x / 5 - 1, d + 1, increasing=True)
print(f"degree {d:2d}: cond(Phi) raw {np.linalg.cond(raw):.1e} scaled to [-1,1] {np.linalg.cond(scaled):.1e}")degree 5: cond(Phi) raw 4.2e+05 scaled to [-1,1] 4.1e+01
degree 10: cond(Phi) raw 5.4e+11 scaled to [-1,1] 2.9e+03
Overfitting and the number of features
With features, is square and the fit interpolates every training point, noise included. As grows the training error goes to zero while the test error eventually rises (Empirical Risk Minimization showed this curve). Remedies, all covered in this course:
- fewer features (choose by cross-validation);
- regularization, (MAP Estimation);
- a Bayesian treatment that averages over parameters (Bayesian Linear Regression).
In software
sklearn.preprocessing.PolynomialFeaturesandSplineTransformerbuild ; put them in aPipelinewithRidge(Polynomial Regression).- Kernel methods use infinitely many features implicitly (The Dual SVM and Kernels).
- A neural network's hidden layer is a learned feature map, with the last layer doing linear regression (or classification) on it.
Exercises
Exercise 1: Feature matrix
Write for inputs with features .
Answer
.
Solution
Row is . Being square and invertible, it will interpolate any three targets exactly.
Exercise 2: Still linear?
Is a linear-in-parameters model?
Answer
No.
Solution
sits inside the sine, so is not a linear combination of fixed features. , by contrast, is.
Exercise 3: Fit a parabola exactly (code)
Find the parabola through , , by solving .
Answer
.
Solution
import numpy as np
Phi = np.vander(np.array([0.0, 1, 2]), 3, increasing=True)
print(np.round(np.linalg.solve(Phi, np.array([1.0, 0, 3])), 10) + 0)[ 1. -3. 2.]
Check: at , .
Test yourself
Polynomial regression is called linear regression because the model is linear in…
- the input
- the parameters
- the output
- nothing; the name is historical
With as many features as training points (and invertible), the training error is…
- large
- zero
- equal to the noise variance
- undefined
Why scale inputs to before building high-degree polynomial features?
- It changes the model class
- It keeps the feature matrix well conditioned
- It removes the need for an intercept
- It makes the loss convex