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 you give the model columns , 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 and still fit a linear model—runs throughout machine learning: kernels take it to infinite dimension without computing , and a neural network does exactly this with a 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 . The normal equations are ; prediction is the orthogonal projection of onto ; with Gaussian noise it is the maximum-likelihood estimator; and if has rank and the true function lies in the space spanned by the , is unbiased, with the number of basis functions. Only the function’s shape changes: linear in , nonlinear in .
The most common basis families for a variable :
- Polynomials: . Global: each coefficient changes the function across the entire axis.
- Interactions: with several variables, products such as or , allowing one variable’s effect to depend on another’s value.
- Step functions (piecewise constant): split the axis at and use indicators for each interval, , with outer intervals extending to . This is equivalent to binning the variable and treating each interval as a category.
- Radial bases: Gaussians with centers and width . Local: each acts only near its center.
- Piecewise linear: with . Each function adds a slope change at knot and the sum is continuous. It is a one-hidden-layer network with activation, , in which hidden-layer weights and biases are fixed and only the output layer is fitted (plus the linear term ).
- Regression splines: piecewise degree-3 polynomials joined continuously through the second derivative at knots. With knots, the truncated-power basis has functions; natural splines additionally require the function to be linear beyond the outermost knots, leaving 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.
Three things the figure teaches, which recur throughout:
- Global versus local. Monomials need high degree to capture the peak at , 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.
- Cancellation. With 10 monomials, the largest individual term reaches on while the sum stays between and ; with 16, it reaches . This is the first symptom of the poor conditioning studied next.
- Extrapolation. Outside , the polynomial is dominated by its highest-degree term and diverges; the sum of Gaussians returns to the constant 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 and there are six monomials: . The term is the interaction: with it, depends on . Pure interactions, without powers (, , but not ), are monomials with all .
Proof
A monomial of degree is a nonnegative-integer solution to . Add a slack variable : solutions correspond bijectively to those of . By stars and bars (combinations with repetition), a solution is a row of stars and bars separating them into groups: there are . For degree exactly there is no slack: stars and bars, . A pure interaction of degree is a subset of distinct variables: .
∎Growth is polynomial in each argument with the other fixed, but fast: for fixed , . With and there are already 5,151 columns; with and , 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 , functions and are almost indistinguishable: both are nearly zero until and rise together to 1. The columns of are nearly parallel, and the condition number shoots up.
We can calculate where this comes from. If the uniformly cover , the law of large numbers gives
which is the Hilbert matrix , the textbook example of an ill-conditioned matrix. Since , we expect , and the lab cell confirms it: measured versus predicted with , and versus with . The condition number multiplies by about 5.7 per degree. At , 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 of is the sample mean of , converging to by orthogonality of Legendre polynomials. The condition number of a positive diagonal is the ratio of its largest to smallest entry, , and that of is its square root.
∎Polynomials span the same space as , so the fit is the same polynomial in exact arithmetic: coefficients change, predictions do not. What changes is that the numerical problem moves from to . There are two remedies, and both are useful:
- Rescale to (or standardize, which does something similar). This alone reduces the condition number for monomials on from to with : better, but still growing by about 2.4 times per degree.
- Change basis to Legendre or Chebyshev on the rescaled variable. With , with Legendre and with Chebyshev.
Chebyshev polynomials are orthogonal with respect to weight , 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 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): points with equally spaced on and , , and fit polynomials of degrees . To measure how each fit 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 with , which can be calculated exactly,
because the cross term has zero expectation. The first term, , is irreducible error: no predictor can go below it.
The next cell repeats the experiment with 200 independent samples and summarizes the median of each quantity. It uses the Legendre basis on so what you see is statistics rather than rounding error, and converts coefficients to the monomial basis of only for display.
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 at to at , at , and exactly zero from ; the cell checks it never increases in any of the 200 samples. This is a theorem, not an empirical accident: models are nested, , and the minimum of over a larger subspace cannot be greater. With , 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 : it always chooses the maximum.
Validation error is U-shaped. It falls from to at , rises slowly to at , and then shoots up: at , at , and at , 190 times its minimum. The degree with lowest median true risk is 3 (, within of irreducible error), and validation with only 30 points chooses the same. To the left of the minimum the model underfits: with 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 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 in the monomial basis of rises from 33 at to at and at , to describe a function that never leaves 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 and are almost parallel on , 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 . 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: at , at , and at . 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, is a fixed function and terms are iid with mean : the sample mean is unbiased and its variance is that of one term divided by . For the second part, for each ; taking expectations, for every , and hence is also . And always, because 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.
The cell runs the same NumPy simulation with and the 13 degrees from 0 to 12:
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 versus median risk : the estimate promises a model almost as good as irreducible error (), but it is not. With an independent test set, the percentage falls to 54% and reported median 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: , compatible with zero, versus 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 : 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 , a projection of rank , we have . The training residual is and , the same trace argument as the previous lesson. Error on new responses is ; the cross term has zero expectation by independence and , so the expectation is . Divide by .
∎This theorem is an entire learning curve in miniature. Training error rises with toward , prediction error falls toward , and the gap closes as . The gap has a name: optimism of training error, and adding it back is the idea behind Mallows’ statistic (Hastie, Tibshirani and Friedman, chapter 7). With , 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: 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 , if is average prediction over training samples,
More data reduce variance (in the theorem, the term ), 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.
The two patterns you need to recognize:
| High bias (underfitting) | High variance (overfitting) | |
|---|---|---|
| Training error | high, rises slightly with | low, far below validation |
| Validation error | falls quickly and plateaus | high and still falling at the end |
| Gap between them | small early | large, closes slowly |
| Convergence level | far from desired error | near desired error, but needs large |
| What helps | more capacity, better features, less regularization | more data, less capacity, more regularization |
| What does not help | more data | more capacity |
In the lab’s initial state (, ), with degree 11 and 64 training examples, medians are for training and for validation: a 45% gap and validation still falling. Raise to 400 and, with 320 examples, they become and : the gap has closed and validation is at irreducible error. With degree 1 and , by contrast, curves end at and , close together and far from , near the asymptote : the best possible line leaves approximation error, and even a million points would not change it. Notice also the validation peak with degree 11 as approaches : it is the interpolation threshold from the degree figure, now traversed by moving .
Lab 1: polynomials, Vandermonde matrices, and orthogonal bases
Start with polynomial expansion from scratch. Each monomial is an exponent vector , generated recursively over the first variable: if has exponent , the rest is a monomial of degree in the remaining variables, exactly the recursion yielding the theorem’s count.
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, , differs from scikit-learn’s ; reproducing it is an exercise. Now conditioning: monomials on versus the Hilbert-matrix prediction, and three alternatives.
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 from below (the grid has 200 points, not infinitely many). Notice rescaling alone only reduces the problem from to at : high degrees also require an orthogonal basis. The final block reproduces the year warning’s numbers: with and the unscaled variable, is of order and the returned fit (RSS ) 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.
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 ; 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 , 22189 at ) 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).
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 . 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 to 5704, 4112, 3781, and 3635 at , 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 and , 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 (over a million) is much worse than at : near the fit is at the interpolation boundary and unstable. This is the same peak seen at , now moving rather than .
With libraries: PolynomialFeatures, Pipeline, and curves
The professional skeleton fits in a few lines; its pieces are worth knowing:
| Piece | What it does | Relevant detail |
|---|---|---|
PolynomialFeatures(degree, interaction_only, include_bias) | expands to monomials in scikit-learn order | include_bias=True adds a column of ones; redundant with LinearRegression, but harmless |
SplineTransformer(n_knots, degree) | B-spline basis per variable | local and better conditioned than monomials |
StandardScaler() before expansion | rescales each variable | without it, PolynomialFeatures on differently scaled variables gives columns of disparate orders of magnitude |
make_pipeline(...) | chains transformations and model | ensures each split fits scaling only on its training block |
validation_curve(modelo, X, y, param_name, param_range, cv) | error versus a hyperparameter | the name is paso__parámetro, for example polynomialfeatures__degree |
learning_curve(modelo, X, y, train_sizes, cv) | error versus | train_sizes accepts fractions or integers; shuffle=False uses the first examples of each block |
np.polynomial.Chebyshev.fit(x, y, deg) | stable univariate fit | rescales the data domain to |
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 , where the number of parameters equals the number of data points, then falls again: from at to at , when the fit interpolates data and the solution chosen from infinitely many is minimum norm. With diabetes the same peak appeared by varying instead of . 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 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 remains above degree 3’s . 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 and .
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 3. How do you turn the inequality into something directly countable?
polynomial_features(X, degree, interaction_only=False), returning the matrix of monomials of total degree 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 and degree 2, that order is . 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)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 rescaled to with the training data minimum and maximum. The starter uses monomials on unscaled ; tests compare with the exact solution calculated to 120 digits and require error below , 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) @ wSummary
- The model is linear in : 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 monomials of degree in variables. The Vandermonde matrix on inherits Hilbert-matrix conditioning, about 5.7 times worse per degree; rescaling to 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.