TExcelTAD
Home › Math for Machine Learning › Basis Functions and Overfitting

Basis Functions and Overfitting

"Linear" regression only needs to be linear in the parameters, not in the inputs. Replace x\mathbf{x} by a vector of features ϕ(x)\boldsymbol{\phi}(\mathbf{x}) (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

f(x)=θTϕ(x)=∑k=0K−1θk ϕk(x)f(\mathbf{x}) = \boldsymbol{\theta}^T\boldsymbol{\phi}(\mathbf{x}) = \sum_{k=0}^{K-1}\theta_k\,\phi_k(\mathbf{x})

With the feature matrix Φ∈RN×K\Phi \in \mathbb{R}^{N \times K}, Φnk=ϕk(xn)\Phi_{nk} = \phi_k(\mathbf{x}_n), everything from the previous lesson carries over with XX replaced by Φ\Phi: θML=(ΦTΦ)−1ΦTy\boldsymbol{\theta}_{\text{ML}} = (\Phi^T\Phi)^{-1}\Phi^T\mathbf{y}.

Common choices:

Basis ϕk(x)\phi_k(x) Notes
polynomial xkx^k simple; ill-conditioned for high degree unless xx is scaled to [−1,1][-1, 1]
Gaussian RBF exp⁡(−(x−ck)2/2s2)\exp(-(x - c_k)^2 / 2s^2) local bumps at centres ckc_k
Fourier sin⁡(kx)\sin(kx), cos⁡(kx)\cos(kx) periodic signals
python · try it yourself
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 1,x,x2,…1, x, x^2, \ldots on [0,10][0, 10] produce columns of wildly different scale that look almost alike, so ΦTΦ\Phi^T\Phi is close to singular. Scaling the input to [−1,1][-1, 1] (or using orthogonal polynomials) fixes it.

python · try it yourself
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 K=NK = N features, Φ\Phi is square and the fit interpolates every training point, noise included. As KK 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:

  1. fewer features (choose KK by cross-validation);
  2. regularization, (ΦTΦ+λI)−1ΦTy(\Phi^T\Phi + \lambda I)^{-1}\Phi^T\mathbf{y} (MAP Estimation);
  3. a Bayesian treatment that averages over parameters (Bayesian Linear Regression).

In software

  • sklearn.preprocessing.PolynomialFeatures and SplineTransformer build Φ\Phi; put them in a Pipeline with Ridge (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 Φ\Phi for inputs x=(0,1,2)x = (0, 1, 2) with features (1,x,x2)(1, x, x^2).

Answer

[100111124]\begin{bmatrix} 1 & 0 & 0 \\ 1 & 1 & 1 \\ 1 & 2 & 4 \end{bmatrix}.

Solution

Row nn is (1,xn,xn2)(1, x_n, x_n^2). Being square and invertible, it will interpolate any three targets exactly.

Exercise 2: Still linear?

Is f(x)=θ1sin⁡(θ2x)f(x) = \theta_1\sin(\theta_2x) a linear-in-parameters model?

Answer

No.

Solution

θ2\theta_2 sits inside the sine, so ff is not a linear combination of fixed features. θ1sin⁡x+θ2cos⁡x\theta_1\sin x + \theta_2\cos x, by contrast, is.

Exercise 3: Fit a parabola exactly (code)

Find the parabola through (0,1)(0, 1), (1,0)(1, 0), (2,3)(2, 3) by solving Φθ=y\Phi\boldsymbol{\theta} = \mathbf{y}.

Answer

y=1−3x+2x2y = 1 - 3x + 2x^2.

Solution
python · try it yourself
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 x=2x = 2, 1−6+8=31 - 6 + 8 = 3.

Test yourself

Polynomial regression is called linear regression because the model is linear in…

  1. the input xx
  2. the parameters θ\boldsymbol{\theta}
  3. the output
  4. nothing; the name is historical

With as many features as training points (and Φ\Phi invertible), the training error is…

  1. large
  2. zero
  3. equal to the noise variance
  4. undefined

Why scale inputs to [−1,1][-1, 1] before building high-degree polynomial features?

  1. It changes the model class
  2. It keeps the feature matrix well conditioned
  3. It removes the need for an intercept
  4. It makes the loss convex