Module contents
Lesson 3 of 24Core 80 min

Polynomial regression, basis expansions and diagnosing overfitting

Turn the linear model into a nonlinear approximator with feature maps φ(x): polynomials, interactions, and local bases. Use polynomial regression to observe overfitting directly and learn practical diagnostic tools: training, validation, and test splits, validation curves, and learning curves. Formal bias–variance decomposition belongs to m13; here the focus is reading it in real plots.

After this lesson you can

  • Construct polynomial feature maps with interactions and count terms as a function of degree and dimension.
  • Fit polynomials of increasing degree and explain coefficient explosion and ill-conditioning of the Vandermonde matrix.
  • Separate training, validation, and test data correctly and justify each partition's role.
  • Plot and interpret validation and learning curves to choose among more data, more capacity, or more regularization.

Before you start

Motivation: curves with the linear machinery intact

The linear regression of the previous lesson has everything one could ask of a method: a closed-form solution, a stable numerical algorithm (QR), a probabilistic interpretation, and convergent gradient descent. It has an obvious flaw: it only draws lines and hyperplanes. Electricity consumption versus temperature is U-shaped (heating on one side, air conditioning on the other), a drug dose has an optimum, and a home’s price does not increase equally for the first square meter and the 300th.

The solution is to change variables. If instead of xx you give the model columns 1,x,x21, x, x^2, fitting remains a least-squares problem linear in the coefficients, with the same formula and code, but the fitted function is a parabola. This idea—transform inputs using a fixed map ϕ\phi and still fit a linear model—runs throughout machine learning: kernels take it to infinite dimension without computing ϕ\phi, and a neural network does exactly this with a ϕ\phi that is learned too.

The price of flexibility appears immediately. With enough columns, the model can pass through every training point, noise included, and predict the rest very poorly: overfitting. This lesson uses polynomial regression as a lab to see it directly and learn practical diagnostic tools: training, validation, and test splits, the validation curve, and the learning curve. The theory explaining them, bias–variance decomposition, belongs in learning theory; here you will learn to read it in real plots.

Feature maps: linear in parameters

Everything you proved for linear regression holds unchanged, because it never relied on the design-matrix columns being the original variables: only on the model being linear in w\vb{w}. The normal equations are Φ⊤Φw^=Φ⊤y\mat{\Phi}\T\mat{\Phi}\hat{\vb{w}} = \mat{\Phi}\T\vb{y}; prediction is the orthogonal projection of y\vb{y} onto col⁡(Φ)\col(\mat{\Phi}); with Gaussian noise it is the maximum-likelihood estimator; and if Φ\mat{\Phi} has rank pp and the true function lies in the space spanned by the ϕj\phi_j, σ^2=RSS/(n−p)\hat\sigma^2 = \mathrm{RSS}/(n - p) is unbiased, with pp the number of basis functions. Only the function’s shape changes: linear in w\vb{w}, nonlinear in x\vb{x}.

The most common basis families for a variable x∈Rx \in \R:

  • Polynomials: 1,x,x2,…,xM1, x, x^2, \dots, x^M. Global: each coefficient changes the function across the entire axis.
  • Interactions: with several variables, products such as x1x2x_1x_2 or x1x2x3x_1x_2x_3, allowing one variable’s effect to depend on another’s value.
  • Step functions (piecewise constant): split the axis at c1<⋯<cKc_1 < \dots < c_K and use indicators for each interval, 1[ck≤x<ck+1]\ind[c_k \le x < c_{k+1}], with outer intervals extending to ±∞\pm\infty. This is equivalent to binning the variable and treating each interval as a category.
  • Radial bases: Gaussians exp⁡ ⁣(−(x−cj)2/(2s2))\exp\!\big(-(x - c_j)^2/(2s^2)\big) with centers cjc_j and width ss. Local: each acts only near its center.
  • Piecewise linear: 1,x,(x−ξ1)+,…,(x−ξK)+1, x, (x - \xi_1)_+, \dots, (x - \xi_K)_+ with (u)+=max⁡(u,0)(u)_+ = \max(u, 0). Each function (x−ξk)+(x - \xi_k)_+ adds a slope change at knot ξk\xi_k and the sum is continuous. It is a one-hidden-layer network with ReLU⁡\relu activation, (x−ξk)+=ReLU⁡(x−ξk)(x - \xi_k)_+ = \relu(x - \xi_k), in which hidden-layer weights and biases are fixed and only the output layer is fitted (plus the linear term xx).
  • Regression splines: piecewise degree-3 polynomials joined continuously through the second derivative at knots. With KK knots, the truncated-power basis 1,x,x2,x3,(x−ξk)+31, x, x^2, x^3, (x - \xi_k)_+^3 has K+4K + 4 functions; natural splines additionally require the function to be linear beyond the outermost knots, leaving KK functions (Hastie, Tibshirani and Friedman, chapter 5). In practice another basis of the same space, B-splines, is used because truncated powers are ill-conditioned.
InteractiveBuild the function with bases
no datano data
  • data
  • sum f^(x)=∑jwj ϕj(x)\hat f(x) = \sum_j w_j\,\phi_j(x)
  • terms wj ϕj(x)w_j\,\phi_j(x) (colors cycle by term)
  • true function
Basis
10
Training error0.0103
κ(Φ)\kappa(\mat{\Phi})8.3 · 10⁶
Largest ∣wj ϕj(x)∣|w_j\,\phi_j(x)| on [0,1][0, 1]2.2 · 10⁵
Prediction at x=−0.3x = -0.31.2 · 10³
Prediction at x=1.3x = 1.3−2.0 · 10³
Global basis: each xjx^j affects the whole interval. Outside the data the highest-degree term dominates and the curve shoots away.
Fifty noisy points from a function with a narrow peak at x=0.7x = 0.7. Choose the family and number KK of basis functions: thin curves are terms wj ϕj(x)w_j\,\phi_j(x) and the thick curve their sum. With monomials, look at the largest-term readout: the sum, of size 1, comes from subtracting enormous terms. Then look at shaded regions without data: each family extrapolates in its own way.

Three things the figure teaches, which recur throughout:

  1. Global versus local. Monomials need high degree to capture the peak at x=0.7x = 0.7, and the curve then oscillates across the entire interval. With Gaussians or piecewise-linear functions, the two or three nearby bases capture the peak without changing the rest. That is why splines are preferred over high-degree global polynomials when flexibility is needed.
  2. Cancellation. With 10 monomials, the largest individual term wjxjw_j x^j reaches 2×1052\times 10^5 on [0,1][0, 1] while the sum stays between −2-2 and 22; with 16, it reaches 101010^{10}. This is the first symptom of the poor conditioning studied next.
  3. Extrapolation. Outside [0,1][0, 1], the polynomial is dominated by its highest-degree term and diverges; the sum of Gaussians returns to the constant w0w_0 as they all vanish; steps repeat the last value; piecewise-linear functions continue the last line. None of these extrapolations knows the true function: the basis determines it. Far from data, the model returns its inductive bias, not information.

Polynomial regression

With d=2d = 2 and M=2M = 2 there are six monomials: 1,x1,x2,x12,x1x2,x221, x_1, x_2, x_1^2, x_1x_2, x_2^2. The term x1x2x_1x_2 is the interaction: with it, ∂f/∂x1=w10+2w20x1+w11x2\partial f/\partial x_1 = w_{10} + 2w_{20}x_1 + w_{11}x_2 depends on x2x_2. Pure interactions, without powers (x1x2x_1x_2, x1x2x3x_1x_2x_3, but not x12x_1^2), are monomials with all αi∈{0,1}\alpha_i \in \{0, 1\}.

Proof

A monomial of degree ≤M\le M is a nonnegative-integer solution to α1+⋯+αd≤M\alpha_1 + \cdots + \alpha_d \le M. Add a slack variable α0=M−∣α∣≥0\alpha_0 = M - \abs{\alpha} \ge 0: solutions correspond bijectively to those of α0+α1+⋯+αd=M\alpha_0 + \alpha_1 + \cdots + \alpha_d = M. By stars and bars (combinations with repetition), a solution is a row of MM stars and dd bars separating them into d+1d + 1 groups: there are (M+dd)=(d+MM)\binom{M + d}{d} = \binom{d + M}{M}. For degree exactly kk there is no slack: kk stars and d−1d - 1 bars, (k+d−1k)\binom{k + d - 1}{k}. A pure interaction of degree kk is a subset of kk distinct variables: (dk)\binom{d}{k}.

∎

Growth is polynomial in each argument with the other fixed, but fast: for fixed MM, (d+MM)=(d+1)⋯(d+M)M!∼dM/M!\binom{d + M}{M} = \frac{(d + 1)\cdots(d + M)}{M!} \sim d^M/M!. With d=100d = 100 and M=2M = 2 there are already 5,151 columns; with d=20d = 20 and M=4M = 4, 10,626. With samples of hundreds or thousands of examples, full polynomial regression is viable only with few variables or low degree. This explosion motivates kernels, which work with all those monomials without constructing them.

The Vandermonde matrix is ill-conditioned

Fitting a degree-15 polynomial to 100 points should be a small, easy problem. It is not, for a geometric reason. On [0,1][0, 1], functions x14x^{14} and x15x^{15} are almost indistinguishable: both are nearly zero until 0.70.7 and rise together to 1. The columns of V\mat{V} are nearly parallel, and the condition number κ(V)=σmax⁡/σmin⁡\kappa(\mat{V}) = \sigma_{\max}/\sigma_{\min} shoots up.

We can calculate where this comes from. If the xix_i uniformly cover [0,1][0, 1], the law of large numbers gives

1n(V⊤V)jk=1n∑i=1nxi j+k  ⟶  ∫01xj+k ⁣dx=1j+k+1,\frac{1}{n}\big(\mat{V}\T\mat{V}\big)_{jk} = \frac{1}{n}\sum_{i=1}^n x_i^{\,j+k} \;\longrightarrow\; \int_0^1 x^{j+k}\dd x = \frac{1}{j + k + 1},

which is the Hilbert matrix HM+1\mat{H}_{M+1}, the textbook example of an ill-conditioned matrix. Since κ(V⊤V)=κ(V)2\kappa(\mat{V}\T\mat{V}) = \kappa(\mat{V})^2, we expect κ(V)≈κ(HM+1)\kappa(\mat{V}) \approx \sqrt{\kappa(\mat{H}_{M+1})}, and the lab cell confirms it: 2.19×1072.19\times 10^{7} measured versus 2.29×1072.29\times 10^{7} predicted with M=10M = 10, and 8.5×10148.5\times 10^{14} versus 9.0×10149.0\times 10^{14} with M=20M = 20. The condition number multiplies by about 5.7 per degree. At κ≈1015\kappa \approx 10^{15}, double-precision least squares has no reliable coefficient digits.

The reasoning also suggests a remedy. Conditioning is determined by the basis Gram matrix with respect to the input distribution. If you choose a basis orthogonal with respect to that distribution, the Gram matrix approaches a diagonal and the problem becomes well conditioned.

Proof

Entry (j,k)(j, k) of 1nP⊤P\frac1n\mat{P}\T\mat{P} is the sample mean of Pj(x)Pk(x)P_j(x)P_k(x), converging to 12∫−11PjPk ⁣dx=δjk2k+1\frac12\int_{-1}^1 P_jP_k\dd x = \frac{\delta_{jk}}{2k + 1} by orthogonality of Legendre polynomials. The condition number of a positive diagonal is the ratio of its largest to smallest entry, 2M+12M + 1, and that of P\mat{P} is its square root.

∎

Polynomials P0,…,PMP_0, \dots, P_M span the same space as 1,t,…,tM1, t, \dots, t^M, so the fit is the same polynomial in exact arithmetic: coefficients change, predictions do not. What changes is that the numerical problem moves from κ≈1015\kappa \approx 10^{15} to κ≈6\kappa \approx 6. There are two remedies, and both are useful:

  1. Rescale xx to [−1,1][-1, 1] (or standardize, which does something similar). This alone reduces the condition number for monomials on [−1,1][-1, 1] from 8.5×10148.5\times 10^{14} to 1.7×1071.7\times 10^{7} with M=20M = 20: better, but still growing by about 2.4 times per degree.
  2. Change basis to Legendre or Chebyshev on the rescaled variable. With M=20M = 20, κ=6.3\kappa = 6.3 with Legendre and 3.53.5 with Chebyshev.

Chebyshev polynomials are orthogonal with respect to weight 1/1−t21/\sqrt{1 - t^2}, not the uniform measure, so the theorem does not apply as written; in practice, on equally spaced points, they behave even slightly better than Legendre. np.polynomial.Chebyshev.fit does both things for you: rescales the data domain to [−1,1][-1, 1] and fits in the Chebyshev basis. And np.polyfit, which uses monomials, at least scales each Vandermonde column by its norm before solving.

Overfitting in action

Take a variant of the experiment opening Bishop’s book (section 1.1, with 10 points): n=15n = 15 points with xx equally spaced on [0,1][0, 1] and y=sin⁡(2πx)+εy = \sin(2\pi x) + \varepsilon, ε∼N(0,0.32)\varepsilon \sim \Normal(0, 0.3^2), and fit polynomials of degrees M=0,1,…,20M = 0, 1, \dots, 20. To measure how each fit f^\hat f generalizes, you have two tools. One is realistic: mean squared error on 30 new points from the same generator, called validation. The other exists only in simulation: true risk R(f^)=E[(Y−f^(X))2]R(\hat f) = \E[(Y - \hat f(X))^2] with X∼Unif⁡(0,1)X \sim \Unif(0, 1), which can be calculated exactly,

R(f^)=σ2+∫01(f^(x)−sin⁡2πx)2 ⁣dx,R(\hat f) = \sigma^2 + \int_0^1 \big(\hat f(x) - \sin 2\pi x\big)^2\dd x,

because the cross term has zero expectation. The first term, σ2=0.09\sigma^2 = 0.09, is irreducible error: no predictor can go below it.

InteractivePolynomial degree and overfitting
Degree M=12M = 12 fit to n=15n = 15 points
  • training (15)
  • validation (30)
  • fit
  • f(x)=sin⁡2πxf(x) = \sin 2\pi x
Mean squared error by degree (log scale)
  • training
  • validation
  • true risk
  • σ2\sigma^2
∣wj∣|w_j| in the monomial basis of xx (log scale): blue if wj>0w_j > 0, red if wj<0w_j < 0
110⁴10⁸10¹²10¹⁶j = 0j = 5j = 10j = 15j = 20
12 (p = 13)
Training error0.0037
Validation error (30 points)0.939
True risk1.073
Best degree by validation (M≤13M \le 13)5
max⁡j∣wj∣\max_j |w_j| (monomials in xx)8.4 · 10⁷
κ\kappa Vandermonde on [0,1][0, 1]2.4 · 10⁹
κ\kappa Legendre on [−1,1][-1, 1]28.6
Overfitting: training error keeps falling, but validation error rises.
Fifteen points from sin⁡2πx\sin 2\pi x plus Gaussian noise with deviation 0.3. Move the degree: upper left, the fit; right, training and validation errors and true risk against degree, with the current degree marked; below, coefficients in the monomial basis of xx. Request “New sample” several times at degree 3 and degree 12, or enable “Overlay” to see 20 fits at once: which changes more from sample to sample?

The next cell repeats the experiment with 200 independent samples and summarizes the median of each quantity. It uses the Legendre basis on t=2x−1t = 2x - 1 so what you see is statistics rather than rounding error, and converts coefficients to the monomial basis of xx only for display.

[ ]Overfitting in action: 200 experiment repetitionsBrowser
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import legendre as L, polynomial as P

f = lambda x: np.sin(2 * np.pi * x)
sigma, n, n_val, M_max = 0.3, 15, 30, 20
x = np.linspace(0, 1, n)                      # entradas de entrenamiento equiespaciadas
xq = (np.arange(2000) + 0.5) / 2000           # malla para integrar ∫(g - f)² en [0, 1]
V, Vq = L.legvander(2 * x - 1, M_max), L.legvander(2 * xq - 1, M_max)
# columna k: coeficientes de P_k(2x - 1) en la base 1, x, x², ... (para ver los coeficientes "de libro")
A_mono = np.zeros((M_max + 1, M_max + 1))
for k in range(M_max + 1):
    c = P.Polynomial(L.leg2poly(np.eye(M_max + 1)[k]))(P.Polynomial([-1, 2])).coef
    A_mono[:len(c), k] = c

def experimento(semilla):
    r = np.random.default_rng(semilla)
    y = f(x) + sigma * r.normal(size=n)
    xv = r.uniform(0, 1, n_val); yv = f(xv) + sigma * r.normal(size=n_val)
    Vv = L.legvander(2 * xv - 1, M_max)
    filas = []
    for M in range(M_max + 1):
        w = np.linalg.lstsq(V[:, :M + 1], y, rcond=None)[0]   # norma mínima si M + 1 > n
        filas.append([np.mean((V[:, :M + 1] @ w - y)**2), np.mean((Vv[:, :M + 1] @ w - yv)**2),
                      sigma**2 + np.mean((Vq[:, :M + 1] @ w - f(xq))**2),
                      np.abs(A_mono[:M + 1, :M + 1] @ w).max()])
    return np.array(filas)

R = np.array([experimento(s) for s in range(200)])     # 200 muestras independientes
med = np.median(R, axis=0)
print(" M   entrenamiento  validación  riesgo verdadero  máx |w_j|   (medianas de 200 muestras)")
for M in [0, 1, 3, 5, 7, 9, 11, 12, 13, 14, 15, 16, 18, 20]:
    print(f"{M:2d}   {med[M, 0]:12.4f}  {med[M, 1]:10.4f}  {med[M, 2]:16.4f}  {med[M, 3]:9.1e}")
print("grado con menor riesgo mediano:", np.argmin(med[:, 2]), "  con menor validación mediana:", np.argmin(med[:, 1]))
print("¿sube alguna vez el error de entrenamiento al subir M?", bool(np.any(np.diff(R[:, :, 0], axis=1) > 1e-12)))

r = np.random.default_rng(0)
y = f(x) + sigma * r.normal(size=n)
zz = np.linspace(0, 1, 400); Vz = L.legvander(2 * zz - 1, M_max)
fig, ejes = plt.subplots(1, 4, figsize=(12, 3), sharey=True)
for ax, M in zip(ejes, [1, 3, 9, 14]):
    w = np.linalg.lstsq(V[:, :M + 1], y, rcond=None)[0]
    ax.plot(zz, f(zz), "--", color="gray", label="f")
    ax.plot(zz, Vz[:, :M + 1] @ w, label="ajuste")
    ax.plot(x, y, "o", label="datos")
    ax.set_ylim(-2, 2); ax.set_title(f"M = {M}")
ejes[0].legend(loc="lower left")
plt.show()

Three patterns, each with an explanation:

Training error always decreases. From 0.5450.545 at M=0M = 0 to 0.0670.067 at M=3M = 3, 0.0260.026 at M=9M = 9, and exactly zero from M=14M = 14; the cell checks it never increases in any of the 200 samples. This is a theorem, not an empirical accident: models are nested, col⁡(ΦM)⊆col⁡(ΦM+1)\col(\mat{\Phi}_M) \subseteq \col(\mat{\Phi}_{M+1}), and the minimum of ∥y−z∥2\norm{\vb{y} - \vb{z}}^2 over a larger subspace cannot be greater. With M+1=n=15M + 1 = n = 15, the Vandermonde matrix of distinct nodes is square and invertible, and the polynomial interpolates the data: zero training error. Training error is therefore unsuitable for choosing MM: it always chooses the maximum.

Validation error is U-shaped. It falls from 0.600.60 to 0.1150.115 at M=3M = 3, rises slowly to 0.1480.148 at M=9M = 9, and then shoots up: 0.340.34 at M=12M = 12, 1.331.33 at M=13M = 13, and 21.621.6 at M=14M = 14, 190 times its minimum. The degree with lowest median true risk is 3 (0.1120.112, within 0.020.02 of irreducible error), and validation with only 30 points chooses the same. To the left of the minimum the model underfits: with M≤2M \le 2 it cannot represent a full sinusoid and both errors are high. To the right it overfits: it has capacity to follow noise and does so. At M=14M = 14 the interpolant oscillates violently between nodes, especially near the ends: the Runge phenomenon, which with equally spaced nodes amplifies any data perturbation, here noise.

Coefficients explode. The median of the largest ∣wj∣\abs{w_j} in the monomial basis of xx rises from 33 at M=3M = 3 to 1.1×1051.1\times 10^{5} at M=9M = 9 and 7.6×1097.6\times 10^{9} at M=14M = 14, to describe a function that never leaves [−2,2][-2, 2] on the data. Two effects combine. One is real: the high-degree fit oscillates greatly, and an oscillating function has large derivatives. The other is representational: because xjx^{j} and xj+1x^{j+1} are almost parallel on [0,1][0, 1], describing a function with them requires combinations with enormous alternating-sign coefficients that cancel (look at the stem plot: blue, red, blue). Large coefficients are therefore a symptom of overfitting one can monitor, and penalizing them is the idea behind ridge regression in the next lesson.

Notice also what happens beyond M=14M = 14. With more parameters than data, infinitely many polynomials interpolate, and lstsq returns the one with minimum coefficient norm in the Legendre basis. Its risk falls again: 24.524.5 at M=15M = 15, 0.310.31 at M=16M = 16, and 0.1670.167 at M=20M = 20. We return to this second descent at the end of the lesson.

The hold-out protocol: training, validation, and test

The previous experiment cheated: it measured true risk, which is unknown with real data. With real data you have only a finite sample, and the only way to estimate how a model predicts new data is to reserve data the model has not seen.

Why three blocks rather than two? Because error on a held-out set is a good estimate only for a model that does not depend on that set.

Proof

Conditioning on training data, f^\hat f is a fixed function and terms (yi′−f^(xi′))2(y'_i - \hat f(\vb{x}'_i))^2 are iid with mean R(f^)R(\hat f): the sample mean is unbiased and its variance is that of one term divided by mm. For the second part, min⁡kR^test(f^k)≤R^test(f^j)\min_k \hat R_{\text{test}}(\hat f_k) \le \hat R_{\text{test}}(\hat f_j) for each jj; taking expectations, E[min⁡kR^test(f^k)]≤R(f^j)\E[\min_k \hat R_{\text{test}}(\hat f_k)] \le R(\hat f_j) for every jj, and hence is also ≤min⁡jR(f^j)\le \min_j R(\hat f_j). And R(f^k^)≥min⁡kR(f^k)R(\hat f_{\hat k}) \ge \min_k R(\hat f_k) always, because f^k^\hat f_{\hat k} is one of the candidates.

∎

The inequality is the statistical version of the winner’s curse: the candidate winning on a noisy test is often one that got lucky on that test, and its reported error is doubly optimistic because the selected model’s actual risk is not necessarily the best possible. Bias grows with the number of candidates and decreases with selection-set size. The next figure makes this visible: each point is a complete experiment.

InteractiveWhat if you choose degree using the test set?
Reported error (vertical) versus true risk (horizontal), 300 replicates, log scale
0.050.050.10.10.20.20.50.511σ² = 0.09true risk of the chosen model
  • error on test used to choose degree
  • diagonal: exact estimate
Protocol
20
K = 13
Replicates below the diagonal65 %
Median reported error0.0958
Median true risk0.1097
Median (reported − true)−0.0146
The minimum of KK noisy estimates is downward biased: the winning degree often got lucky on that test.
300 independent replicates: fit degrees 0,…,K−10, \dots, K - 1 on 30 training points and select the lowest error on a set of mm points. Horizontally, the chosen model's true risk; vertically, the error that would be reported. With “Choose and evaluate on test,” the cloud lies below the diagonal. Switch to the correct protocol: chosen models are the same, but error is measured on an independent test set. Also try K=1K = 1 (no selection) and m=200m = 200.

The cell runs the same NumPy simulation with m=20m = 20 and the 13 degrees from 0 to 12:

[ ]Choosing on test: winner biasBrowser
import numpy as np
from numpy.polynomial import legendre as L

f = lambda x: np.sin(2 * np.pi * x)
sigma, n, m, grados = 0.3, 30, 20, range(13)
xq = (np.arange(1000) + 0.5) / 1000
Vq = L.legvander(2 * xq - 1, 12)

def muestra(r, k):
    x = r.uniform(0, 1, k)
    return L.legvander(2 * x - 1, 12), f(x) + sigma * r.normal(size=k)

r = np.random.default_rng(0)
comunicado_reuso, comunicado_honesto, riesgo = [], [], []
for _ in range(300):
    V, y = muestra(r, n); Vs, ys = muestra(r, m); Vt, yt = muestra(r, m)
    W = [np.linalg.lstsq(V[:, :M + 1], y, rcond=None)[0] for M in grados]
    err_sel = [np.mean((Vs[:, :M + 1] @ w - ys)**2) for M, w in zip(grados, W)]
    M = int(np.argmin(err_sel)); w = W[M]
    comunicado_reuso.append(err_sel[M])                              # el mismo conjunto elige y evalúa
    comunicado_honesto.append(np.mean((Vt[:, :M + 1] @ w - yt)**2))  # un test que no ha visto nadie
    riesgo.append(sigma**2 + np.mean((Vq[:, :M + 1] @ w - f(xq))**2))
c1, c2, rv = map(np.array, (comunicado_reuso, comunicado_honesto, riesgo))
print(f"riesgo verdadero del grado elegido: mediana {np.median(rv):.4f},  réplicas con riesgo > 1: {np.mean(rv > 1):.0%}")
for nombre, c in [("elegir y evaluar con el test", c1), ("test independiente", c2)]:
    d = c - rv
    print(f"{nombre:28s}  mediana comunicada {np.median(c):.4f},  por debajo del riesgo en {np.mean(d < 0):.0%},  "
          f"media de (comunicado - verdadero) {d.mean():+.3f} ± {d.std(ddof=1) / np.sqrt(len(d)):.3f}")

Reusing the test set, reported error falls below true risk in 68% of replicates, with median 0.0990.099 versus median risk 0.1110.111: the estimate promises a model almost as good as irreducible error (0.090.09), but it is not. With an independent test set, the percentage falls to 54% and reported median 0.1140.114 matches risk. It does not fall exactly to 50% because mean squared error on 20 points has a right-skewed distribution, whose median is somewhat below its mean. The theorem guarantees that the mean of (reported − true) is zero with an independent test, and the cell prints it with its standard error: −0.19±0.18-0.19 \pm 0.18, compatible with zero, versus −0.33±0.16-0.33 \pm 0.16 reusing the test. The large standard errors have a visible cause: in 2% of replicates, the 20 selection points lead to a high degree that looked good on them but whose true risk exceeds 1 (almost 30 in the worst). Those few replicates dominate means, so comparisons here use medians and percentages.

Practical consequences:

  • Look at test once. If you consult it to make a decision (degree, whether to retrain, which variables to remove), it has become validation and you have lost the unbiased estimate. Repeated decisions on the same held-out set are called adaptive data analysis and have their own theory.
  • Size matters through variance. By the theorem, the estimate’s standard error is sd⁡(ℓi)/m\operatorname{sd}(\ell_i)/\sqrt m: if individual losses have deviation 0.5, 100 test examples give standard error 0.05, and halving it requires four times as many. Distinguishing models differing by less than a couple of standard errors reads noise. Splits such as 60/20/20 or 80/10/10 are conventions, not rules: what matters is absolute validation and test size relative to the differences you want to detect.
  • With little data, hold-out wastes too much. Cross-validation reuses each example for training and validation, and nested cross-validation does the same for the test layer. You will see this in the cross-validation lesson, along with splits respecting groups and time.

Validation and learning curves

Two of the most common practical diagnostics are plots with the same vertical axis (training and validation error) but different horizontal axes.

Both are calculated using repeated random splits and drawn with a band showing variation between splits, because one split can tell a misleading story. You have seen the validation curve: it is the right-hand graph in the degree figure. Read its U shape: left of the minimum, underfitting (both errors high and close); right, overfitting (training error keeps falling, validation error rises). Choose the minimizing value or, under the one-standard-error rule, the simplest model whose validation error lies within one standard error of the minimum.

Reading the learning curve well requires a little more theory. In one case it can be calculated exactly.

Proof

With hat matrix H=X(X⊤X)−1X⊤\mat{H} = \mat{X}(\mat{X}\T\mat{X})\inv\mat{X}\T, a projection of rank pp, we have y^=Hy=Xβ+Hε\hat{\vb{y}} = \mat{H}\vb{y} = \mat{X}\vb{\beta} + \mat{H}\vb{\varepsilon}. The training residual is (I−H)ε(\mat{I} - \mat{H})\vb{\varepsilon} and E[ε⊤(I−H)ε]=σ2tr⁡(I−H)=σ2(n−p)\E[\vb{\varepsilon}\T(\mat{I} - \mat{H})\vb{\varepsilon}] = \sigma^2\tr(\mat{I} - \mat{H}) = \sigma^2(n - p), the same trace argument as the previous lesson. Error on new responses is y′−y^=ε′−Hε\vb{y}' - \hat{\vb{y}} = \vb{\varepsilon}' - \mat{H}\vb{\varepsilon}; the cross term has zero expectation by independence and E∥Hε∥2=σ2tr⁡H=σ2p\E\norm{\mat{H}\vb{\varepsilon}}^2 = \sigma^2\tr\mat{H} = \sigma^2 p, so the expectation is σ2(n+p)\sigma^2(n + p). Divide by nn.

∎

This theorem is an entire learning curve in miniature. Training error rises with nn toward σ2\sigma^2, prediction error falls toward σ2\sigma^2, and the gap 2σ2p/n2\sigma^2p/n closes as 1/n1/n. The gap has a name: optimism of training error, and adding it back is the idea behind Mallows’ CpC_p statistic (Hastie, Tibshirani and Friedman, chapter 7). With n=pn = p, training error is zero: as many parameters as data interpolate.

When the model is misspecified (the true function is not in the class), both curves approach another level: σ2\sigma^2 plus approximation error, the distance from the true function to the best function in the class. This is the same decomposition formalized by bias–variance: at each x\vb{x}, if fˉ(x)=ED[f^(x)]\bar f(\vb{x}) = \E_{\Data}[\hat f(\vb{x})] is average prediction over training samples,

ED,Y[(Y−f^(x))2]=σ2⏟irreducible+(f(x)−fˉ(x))2⏟sesgo2+ED[(f^(x)−fˉ(x))2]⏟varianza.\E_{\Data, Y}\big[(Y - \hat f(\vb{x}))^2\big] = \underbrace{\sigma^2}_{\text{irreducible}} + \underbrace{\big(f(\vb{x}) - \bar f(\vb{x})\big)^2}_{\text{sesgo}^2} + \underbrace{\E_{\Data}\big[(\hat f(\vb{x}) - \bar f(\vb{x}))^2\big]}_{\text{varianza}}.

More data reduce variance (in the theorem, the term σ2p/n\sigma^2 p/n), but bias approaches the model class’s approximation error, which no sample size reduces. The proof, variants, and limits appear in the bias and variance lesson; this much suffices to read curves.

InteractiveLearning curve lab
Learning curves: median and quartiles of 20 80/20 splits (log scale)
  • training
  • validation
  • best possible at degree M
  • σ2\sigma^2
With n≤pn \le p the polynomial interpolates: training error is 0 and drawn on the lower edge; values above 100 appear on the upper edge.
Capacity
11 (p = 12)
Data
80
0.30
Parameters pp12
Training n = 640.0676
Validation n = 640.1222
Irreducible error σ2\sigma^20.0900
Best possible error at degree MM0.0900
High variance: a 45% gap remains and validation still falls (×1.30 since halfway). More data help, as do lower capacity or regularization.
Data from sin⁡2πx\sin 2\pi x plus noise, with xx uniform on [0,1][0, 1]. For each size nn, fit a polynomial on the first nn examples of an 80/20 split and measure error on that subset and the held-out 20%; lines show the median of 20 splits and bands the quartiles. Dashed lines are exact: σ2\sigma^2 and the best possible error at that degree. Start with “High variance,” then try “High bias”: where would twice as much data help? Raise noise and observe the gap.

The two patterns you need to recognize:

High bias (underfitting)High variance (overfitting)
Training errorhigh, rises slightly with nnlow, far below validation
Validation errorfalls quickly and plateaushigh and still falling at the end
Gap between themsmall earlylarge, closes slowly
Convergence levelfar from desired errornear desired error, but needs large nn
What helpsmore capacity, better features, less regularizationmore data, less capacity, more regularization
What does not helpmore datamore capacity

In the lab’s initial state (N=80N = 80, σ=0.3\sigma = 0.3), with degree 11 and 64 training examples, medians are 0.0680.068 for training and 0.1220.122 for validation: a 45% gap and validation still falling. Raise NN to 400 and, with 320 examples, they become 0.0770.077 and 0.0800.080: the gap has closed and validation is at irreducible error. With degree 1 and N=80N = 80, by contrast, curves end at 0.2760.276 and 0.3120.312, close together and far from σ2=0.09\sigma^2 = 0.09, near the asymptote σ2+0.196=0.286\sigma^2 + 0.196 = 0.286: the best possible line leaves 0.1960.196 approximation error, and even a million points would not change it. Notice also the validation peak with degree 11 as nn approaches p=12p = 12: it is the interpolation threshold from the degree figure, now traversed by moving nn.

Lab 1: polynomials, Vandermonde matrices, and orthogonal bases

Start with polynomial expansion from scratch. Each monomial is an exponent vector α\alpha, generated recursively over the first variable: if x1x_1 has exponent kk, the rest is a monomial of degree ≤M−k\le M - k in the remaining d−1d - 1 variables, exactly the recursion yielding the theorem’s count.

[ ]Polynomial expansion from scratchBrowser
import numpy as np
from math import comb

def exponentes(d, M):
    """Todos los alfa en N^d con |alfa| <= M, por grado total y, dentro de cada grado, en orden lexicográfico."""
    def rec(d, M):
        if d == 0:
            return [()]
        return [(k,) + resto for k in range(M + 1) for resto in rec(d - 1, M - k)]
    return sorted(rec(d, M), key=lambda a: (sum(a), a))

def expansion_polinomica(X, M, solo_interacciones=False):
    X = np.asarray(X, dtype=float)
    A = np.array(exponentes(X.shape[1], M))
    if solo_interacciones:
        A = A[A.max(axis=1) <= 1]
    return np.prod(X[:, None, :] ** A[None, :, :], axis=2), A

X = np.array([[2.0, 3.0], [1.0, -1.0]])
Phi, A = expansion_polinomica(X, 2)
print("exponentes:", [tuple(int(v) for v in a) for a in A])
print(Phi)

print("\n  d    M   monomios   C(d+M, M)   interacciones puras   suma de C(d, k)")
for d, M in [(2, 2), (2, 10), (5, 4), (20, 2), (20, 4), (100, 2)]:
    A = np.array(exponentes(d, M))
    n_int = int(np.sum(A.max(axis=1) <= 1))
    print(f"{d:3d}  {M:3d}  {len(A):9d}  {comb(d + M, M):10d}   {n_int:19d}   {sum(comb(d, k) for k in range(min(d, M) + 1)):15d}")

Column order is a convention. This cell’s order, 1,x2,x1,x22,x1x2,x121, x_2, x_1, x_2^2, x_1x_2, x_1^2, differs from scikit-learn’s 1,x1,x2,x12,x1x2,x221, x_1, x_2, x_1^2, x_1x_2, x_2^2; reproducing it is an exercise. Now conditioning: monomials on [0,1][0, 1] versus the Hilbert-matrix prediction, and three alternatives.

[ ]Vandermonde versus Legendre and ChebyshevBrowser
import numpy as np
import mpmath as mp
from numpy.polynomial import legendre as L, chebyshev as C

x = np.linspace(0, 1, 200)
t = 2 * x - 1                              # el mismo x reescalado a [-1, 1]
mp.mp.dps = 60                             # la matriz de Hilbert necesita aritmética de 60 cifras

def kappa_hilbert(m):
    autovalores = mp.eigsy(mp.hilbert(m))[0]
    return float(max(autovalores) / min(autovalores))

print(" M   κ monomios [0,1]  √κ(Hilbert)   κ monomios [-1,1]  κ Legendre  √(2M+1)  κ Chebyshev")
for M in [2, 4, 6, 8, 10, 12, 15, 20]:
    k01 = np.linalg.cond(np.vander(x, M + 1, increasing=True))
    k11 = np.linalg.cond(np.vander(t, M + 1, increasing=True))
    kL = np.linalg.cond(L.legvander(t, M))
    kC = np.linalg.cond(C.chebvander(t, M))
    print(f"{M:2d}   {k01:14.2e}  {np.sqrt(kappa_hilbert(M + 1)):11.2e}   {k11:15.2e}  {kL:10.2f}  {np.sqrt(2 * M + 1):7.2f}  {kC:10.2f}")

# x sin escalar: años como variable
rng = np.random.default_rng(1)
anios = np.arange(1990, 2021, dtype=float)
y_anios = np.sin((anios - 1990) / 5) + 0.1 * rng.normal(size=anios.size)
s = (anios - 2005) / 15                     # reescalado a [-1, 1]
print("\nAjuste a 31 años, 1990-2020")
for M in [2, 3, 5]:
    V = np.vander(anios, M + 1, increasing=True)
    Vs = L.legvander(s, M)
    w = np.linalg.lstsq(V, y_anios, rcond=None)[0]
    ws = np.linalg.lstsq(Vs, y_anios, rcond=None)[0]
    print(f"M = {M}:  κ sin escalar = {np.linalg.cond(V):.1e}   κ escalado = {np.linalg.cond(Vs):5.2f}   "
          f"RSS sin escalar = {np.sum((V @ w - y_anios)**2):.3f}   RSS escalado = {np.sum((Vs @ ws - y_anios)**2):.3f}")

The second column follows the first with error below 6%, as predicted by the Gram-matrix argument, and Legendre follows 2M+1\sqrt{2M + 1} from below (the grid has 200 points, not infinitely many). Notice rescaling alone only reduces the problem from 8.5×10148.5\times 10^{14} to 1.7×1071.7\times 10^7 at M=20M = 20: high degrees also require an orthogonal basis. The final block reproduces the year warning’s numbers: with M=5M = 5 and the unscaled variable, κ\kappa is of order 102810^{28} and the returned fit (RSS 6.4956.495) is worse than degree 2.

Lab 2: validation and learning curves from scratch

Now real data: scikit-learn’s diabetes dataset, 442 patients, 10 already centered and scaled clinical variables, and a response measuring disease progression one year later. For the validation curve we use the two variables most correlated with response, body mass index (bmi, 0.59) and s5 (0.57), with polynomials of degrees 1 to 8 in them. Each function receives prepared splits, as scikit-learn does, and preprocessing (standardization and expansion) is fitted inside each split using only its training block to avoid leaking validation information.

[ ]Validation curve from scratch and with scikit-learnBrowser
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import ShuffleSplit, validation_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression

X, y = load_diabetes(return_X_y=True)
print("correlación con y:", {nombre: round(float(np.corrcoef(X[:, j], y)[0, 1]), 2) for j, nombre in enumerate(load_diabetes().feature_names)})
X2 = X[:, [2, 8]]                         # bmi y s5

def ajustar_polinomio(Xtr, ytr, M):
    """Estandariza con los estadísticos de entrenamiento, expande y resuelve mínimos cuadrados."""
    mu, sd = Xtr.mean(0), Xtr.std(0)
    w = np.linalg.lstsq(expansion_polinomica((Xtr - mu) / sd, M)[0], ytr, rcond=None)[0]
    return lambda Z: expansion_polinomica((Z - mu) / sd, M)[0] @ w

def curva_validacion(X, y, grados, particiones):
    tr = np.zeros((len(grados), len(particiones))); va = np.zeros_like(tr)
    for j, (i_tr, i_va) in enumerate(particiones):
        for i, M in enumerate(grados):
            g = ajustar_polinomio(X[i_tr], y[i_tr], M)
            tr[i, j] = np.mean((g(X[i_tr]) - y[i_tr])**2)
            va[i, j] = np.mean((g(X[i_va]) - y[i_va])**2)
    return tr, va

particiones = list(ShuffleSplit(n_splits=10, test_size=0.25, random_state=0).split(X2))
grados = list(range(1, 9))
tr, va = curva_validacion(X2, y, grados, particiones)

modelo = make_pipeline(StandardScaler(), PolynomialFeatures(), LinearRegression())
tr_sk, va_sk = validation_curve(modelo, X2, y, param_name="polynomialfeatures__degree", param_range=grados,
                                cv=particiones, scoring="neg_mean_squared_error")
print(" M   entrenamiento   validación media ± desv.   validación mediana")
for i, M in enumerate(grados):
    print(f"{M:2d}   {tr[i].mean():12.0f}   {va[i].mean():12.0f} ± {va[i].std():<9.0f}   {np.median(va[i]):10.0f}")
print("máxima diferencia relativa con scikit-learn:", np.max(np.abs(va + va_sk) / va))

# ¿de dónde sale la media disparada con grado 7? La peor partición, paciente a paciente
j = int(np.argmax(va[6])); i_tr, i_va = particiones[j]
g = ajustar_polinomio(X2[i_tr], y[i_tr], 7)
e = (g(X2[i_va]) - y[i_va])**2; k = int(np.argmax(e))
z = (X2[i_va][k] - X2[i_tr].mean(0)) / X2[i_tr].std(0)
print(f"grado 7, partición {j}: error medio {e.mean():.0f}; un solo paciente aporta el {e.max() / e.sum():.0%} "
      f"(bmi a {z[0]:+.1f} y s5 a {z[1]:+.1f} desviaciones típicas); sin él, {np.delete(e, k).mean():.0f}")

The two implementations agree to rounding (relative difference below 10−1210^{-12}; validation_curve returns error with its sign reversed because scikit-learn always maximizes). The shape resembles the degree figure but is much less clear, as often happens with real data. Mean validation error is 3275 at degree 1, 3255 at degree 3 (the minimum), and 3313 at degree 4, with split-to-split deviations around 300 or 400: degrees 1 to 4 are indistinguishable on these data, and the one-standard-error rule would choose degree 1. From degree 6 mean error shoots up (5202 at M=6M = 6, 22189 at M=7M = 7) while the median rises slowly (3668, 4054). The cell’s last line locates the cause: in the worst degree-7 split, one validation patient contributes 96% of error. This patient is not outside either variable’s range separately, but combines s5 at 2.9 standard deviations above the mean with bmi below it, a region nearly empty in training, where the degree-7 polynomial extrapolates absurdly; without that patient, the split’s mean error falls from 174769 to 7137. This is the extrapolation warning with real data and two dimensions, where “outside the data” is not visible by looking at each variable separately.

For the learning curve we use all ten variables and compare degree 1 (11 parameters) with degree 2 (66 parameters).

[ ]Learning curves from scratch and with scikit-learnBrowser
from sklearn.model_selection import learning_curve

def curva_aprendizaje(X, y, M, tamanos, particiones):
    tr = np.zeros((len(tamanos), len(particiones))); va = np.zeros_like(tr)
    for j, (i_tr, i_va) in enumerate(particiones):
        for i, k in enumerate(tamanos):
            sub = i_tr[:k]                       # los k primeros del bloque de entrenamiento
            g = ajustar_polinomio(X[sub], y[sub], M)
            tr[i, j] = np.mean((g(X[sub]) - y[sub])**2)
            va[i, j] = np.mean((g(X[i_va]) - y[i_va])**2)
    return tr, va

particiones = list(ShuffleSplit(n_splits=10, test_size=0.25, random_state=0).split(X))
tamanos = [40, 60, 80, 120, 160, 220, 280, 331]
for M in [1, 2]:
    tr, va = curva_aprendizaje(X, y, M, tamanos, particiones)
    print(f"grado {M}   n             ", tamanos)
    print("          entrenamiento ", np.round(np.median(tr, 1)).astype(int))
    print("          validación    ", np.round(np.median(va, 1)).astype(int))

modelo = make_pipeline(StandardScaler(), PolynomialFeatures(2), LinearRegression())
_, tr_sk, va_sk = learning_curve(modelo, X, y, train_sizes=tamanos, cv=particiones,
                                 scoring="neg_mean_squared_error", shuffle=False)
print("scikit-learn, grado 2, validación", np.round(np.median(-va_sk, 1)).astype(int))

The two curves exhibit the table’s patterns. With degree 1, training and validation meet early: with 331 examples, 2829 and 3057 (medians), and validation has fallen only from 3131 to 3057 since n=160n = 160. This model has high bias relative to what might be achieved: more patients would barely improve it. With degree 2 the gap is enormous and closes slowly: validation error falls from 13364 at n=120n = 120 to 5704, 4112, 3781, and 3635 at n=331n = 331, still above the linear model and falling. On these data the quadratic overfits; with many more patients it might beat the linear model, and the curve says you cannot know without them.

Two details deserve attention. At n=40n = 40 and n=60n = 60, fewer examples than the 66 parameters, training error is 0 because the model interpolates, and scikit-learn gives different numbers: for an underdetermined system the two implementations choose different minimum-norm solutions (scikit-learn fits the intercept separately and excludes it from the norm). Validation at n=60n = 60 (over a million) is much worse than at n=40n = 40: near n=pn = p the fit is at the interpolation boundary and unstable. This is the same peak seen at M=14M = 14, now moving nn rather than pp.

With libraries: PolynomialFeatures, Pipeline, and curves

The professional skeleton fits in a few lines; its pieces are worth knowing:

PieceWhat it doesRelevant detail
PolynomialFeatures(degree, interaction_only, include_bias)expands to monomials in scikit-learn orderinclude_bias=True adds a column of ones; redundant with LinearRegression, but harmless
SplineTransformer(n_knots, degree)B-spline basis per variablelocal and better conditioned than monomials
StandardScaler() before expansionrescales each variablewithout it, PolynomialFeatures on differently scaled variables gives columns of disparate orders of magnitude
make_pipeline(...)chains transformations and modelensures each split fits scaling only on its training block
validation_curve(modelo, X, y, param_name, param_range, cv)error versus a hyperparameterthe name is paso__parámetro, for example polynomialfeatures__degree
learning_curve(modelo, X, y, train_sizes, cv)error versus nntrain_sizes accepts fractions or integers; shuffle=False uses the first examples of each block
np.polynomial.Chebyshev.fit(x, y, deg)stable univariate fitrescales the data domain to [−1,1][-1, 1]

The complete protocol, with a test set examined once, looks like this:

from sklearn.model_selection import train_test_split, validation_curve

X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)   # el test se aparta primero
modelo = make_pipeline(StandardScaler(), PolynomialFeatures(), LinearRegression())
_, va = validation_curve(modelo, X_tr, y_tr, param_name="polynomialfeatures__degree",
                         param_range=[1, 2, 3], cv=5, scoring="neg_mean_squared_error")
mejor = [1, 2, 3][int(np.argmax(va.mean(axis=1)))]                                # se elige solo con entrenamiento
modelo.set_params(polynomialfeatures__degree=mejor).fit(X_tr, y_tr)               # se reentrena con todo el bloque
print("error de test (una vez):", np.mean((modelo.predict(X_te) - y_te) ** 2))

Looking ahead: more parameters than data

In the degree figure and first cell you saw something classical theory does not predict. Risk rises until M=14M = 14, where the number of parameters equals the number of data points, then falls again: from 24.524.5 at M=15M = 15 to 0.1670.167 at M=20M = 20, when the fit interpolates data and the solution chosen from infinitely many is minimum norm. With diabetes the same peak appeared by varying nn instead of pp. Belkin, Hsu, Ma and Mandal (2019) called this shape double descent and documented it in random features, neural networks, and forests: a peak at interpolation threshold p≈np \approx n and a second descent above it, sometimes below the classical U-shaped minimum.

In our experiment the second descent does not go that far: at degree 20, risk 0.1670.167 remains above degree 3’s 0.1120.112. It also depends on a consequential choice: minimum norm in the Legendre basis. In another basis, the minimum-norm interpolant is another polynomial with another risk. Why minimum norm acts as implicit regularization, what the second descent depends on, and how it relates to huge networks interpolating their training data are covered in the minimum-norm interpolator and double descent. For now, the practical lesson is the same as the whole lesson: parameter count is not a reliable measure of effective capacity, so decisions use measured curves rather than rules about pp and nn.

Common mistakes

Exercises

NumericHow many columns?
How many monomials of total degree at most 3 are there in d=10d = 10 variables, including the constant term?
NumericHow much test data is needed?
Your model's individual squared losses (yi−f^(xi))2(y_i - \hat f(\vb{x}_i))^2 have standard deviation 0.50.5. How many test examples are needed for the standard error of estimated mean squared error to be 0.010.01?
NumericTraining optimism
You fit a well-specified linear model by least squares with p=10p = 10 parameters (including intercept) to n=50n = 50 examples with noise variance σ2=1\sigma^2 = 1. What is the expected difference between error on new responses at the same points and training error (both averaged per example)?
QuizClose, high curves
At the largest training size, a learning curve shows training error 0.30 and validation error 0.31, both stable for some time as nn grows. Your goal is 0.10. Which action is most promising?
QuizWhy not choose using test data?
Why should you not choose polynomial degree by looking at test-set error?
QuizMonomials or Legendre
You fit a degree-M=10M = 10 polynomial by least squares to n=50n = 50 distinct points in [−1,1][-1, 1], first using the monomial basis and then Legendre. Assuming exact arithmetic, what changes with the basis? Select all that apply.

More than one answer may be correct.

QuizA gap that does not close
At the largest available nn, your model has training error 0.05 and validation error 0.40, and validation is still falling at the end. The goal is 0.15. Which actions are reasonable? Select all that apply.

More than one answer may be correct.

QuizFar from the data
You fit three models to the same data with x∈[0,1]x \in [0, 1]: a degree-9 polynomial, a sum of a constant and 9 Gaussians centered in [0,1][0, 1] with width 0.1, and a piecewise-linear basis with 8 knots in (0,1)(0, 1). What does each predict at x=5x = 5?
ProofCounting monomials
Prove: In dd variables there are exactly (d+MM)\binom{d + M}{M} monomials of total degree ≤M\le M.
0
A monomial of degree ≤M\le M is a vector α∈Nd\alpha \in \N^d with α1+⋯+αd≤M\alpha_1 + \cdots + \alpha_d \le M.

Step 1 of 3. How do you turn the inequality into something directly countable?

CodeThe scikit-learn expansion
Implement polynomial_features(X, degree, interaction_only=False), returning the matrix of monomials of total degree ≤\le degree for rows of X (shape (n, d)), with a column of ones first and the same column order as scikit-learn's PolynomialFeatures(degree, interaction_only=interaction_only). For two variables a,ba, b and degree 2, that order is 1,a,b,a2,ab,b21, a, b, a^2, ab, b^2. With interaction_only=True, omit monomials with any variable raised above 1. Do not use PolynomialFeatures.
import numpy as np

def polynomial_features(X, degree, interaction_only=False):
  X = np.asarray(X, dtype=float)
  n, d = X.shape
  columnas = [np.ones(n)]
  # tu código: añade los monomios de grado 1, 2, ..., degree en el orden de scikit-learn
  return np.column_stack(columnas)
Shift+Enter to run
CodeDegree 15 without losing digits
Implement ajuste_chebyshev(x, y, grado, x_nuevo), fitting a degree-grado polynomial by least squares to data (x, y) and returning predictions at x_nuevo. Use the Chebyshev basis on xx rescaled to [−1,1][-1, 1] with the training data minimum and maximum. The starter uses monomials on unscaled xx; tests compare with the exact solution calculated to 120 digits and require error below 10−910^{-9}, several orders of magnitude better than monomials.
import numpy as np
from numpy.polynomial import chebyshev as C

def ajuste_chebyshev(x, y, grado, x_nuevo):
  x = np.asarray(x, dtype=float)
  x_nuevo = np.asarray(x_nuevo, dtype=float)
  # versión de partida: monomios sobre x sin escalar (mal condicionada)
  V = np.vander(x, grado + 1, increasing=True)
  w = np.linalg.lstsq(V, y, rcond=None)[0]
  return np.vander(x_nuevo, grado + 1, increasing=True) @ w
Shift+Enter to run

Summary

Key idea
A fixed feature map ϕ\phi turns linear regression into a nonlinear approximator without changing its machinery; the added flexibility costs overfitting and poor conditioning, and the only reliable way to choose how much to use is to measure it on data the fit has not seen.
  • The model f(x)=w⊤ϕ(x)f(\vb{x}) = \vb{w}\T\phi(\vb{x}) is linear in w\vb{w}: normal equations, projection, and maximum likelihood still apply. Global bases (polynomials) and local ones (steps, Gaussians, piecewise-linear functions, splines) differ in how they distribute flexibility and extrapolate.
  • There are (d+MM)\binom{d + M}{M} monomials of degree ≤M\le M in dd variables. The Vandermonde matrix on [0,1][0, 1] inherits Hilbert-matrix conditioning, about 5.7 times worse per degree; rescaling to [−1,1][-1, 1] and using Legendre or Chebyshev brings it to a single digit.
  • As capacity rises, training error always falls (nested models) and validation error traces a U; exploding coefficients signal the right-hand side.
  • Training fits, validation chooses, and test is used once: choosing with a set makes it optimistic for the chosen model.
  • The validation curve chooses capacity; the learning curve says what to do next: close, high curves call for more capacity or better features; a closing gap calls for more data or more regularization.