The Blessing of Dimensionality
Building and checking models
Principle or heuristic
Advanced
It’s good to have more data, even if you label this additional information as “dimensions” rather than “data points.”
What it is
In statistics, “curse of dimensionality” often refers to “the difficulty of fitting a model when many possible predictors are available.” Gelman objects: “more predictors is more data, and it should not be a ‘curse’ to have more data.” With multilevel modeling, he writes, “there is no curse of dimensionality”, because in realistic problems the predictors have structure: “they are units with K measurements that have names, orderings, etc.” More measured variables are more information. If your method gets worse when you hand it more information, the fault lies with the method, not with the information. With a model that regularizes sensibly, such as a hierarchical model, a prior or a penalty, adding dimensions should help, or at worst do no harm.
Why it matters
Analysts often throw away variables to “avoid overfitting,” or refuse to include group indicators because there are “too many parameters.” That discards real information. The curse belongs to unregularized methods like least squares with many predictors. Shrinkage turns the curse into a blessing: each extra weak predictor adds a bit of signal, and the prior or penalty keeps the noise in check.
How it works
With \(p\) predictors and \(n\) observations, least squares has variance that grows roughly like \(p/(n - p)\) and breaks down as \(p \to n\). Ridge regression, or equivalently a normal prior on the coefficients, adds the penalty \(\lambda \lVert\beta\rVert^2\):
\[ \hat\beta_{\text{ridge}} = (X^\top X + \lambda I)^{-1} X^\top y. \]
When many predictors each carry a little signal, the penalized fit keeps improving as \(p\) grows, which is the blessing. Without the penalty, out-of-sample accuracy falls apart.
Simulated example
There are \(n = 100\) training observations and a test set. We add predictors one batch at a time. Each predictor has a small true coefficient. Compare test-set \(R^2\) for least squares and for ridge regression as the number of dimensions grows.
Show simulation code
The R version uses base R, and the Python version uses NumPy and Matplotlib. Where the simulation draws random numbers, each language draws its own, so exact numbers differ slightly but show the same pattern. The numbered markers in the R code are explained under it.
import {rng, range, mean, sum, ridge, fmt} from "../js/stats.js"
viewof signal = Inputs.range([0.05, 0.4], {value: 0.15, step: 0.01, label: "Size of each true coefficient"})
viewof lambda = Inputs.range([1, 200], {value: 40, step: 1, label: "Ridge penalty λ"})
viewof seed = Inputs.range([1, 500], {value: 20, step: 1, label: "Random seed"})
dims = {
const r = rng(seed);
const P = 90, n = 100, nTest = 500;
const beta = range(P).map(() => signal * (r() < 0.5 ? -1 : 1));
const make = m => range(m).map(() => {
const x = r.normals(P);
return {x, y: sum(x.map((v, j) => v * beta[j])) + r.normal(0, 1)};
});
const train = make(n), test = make(nTest);
const r2 = (fit, p) => {
const ty = test.map(d => d.y), my = mean(ty);
const sse = sum(test.map(d => (d.y - fit.predict(d.x.slice(0, p))) ** 2));
return Math.max(-0.5, 1 - sse / sum(ty.map(v => (v - my) ** 2)));
};
return [5, 10, 20, 30, 40, 50, 60, 70, 80, 90].flatMap(p => {
const X = train.map(d => d.x.slice(0, p)), y = train.map(d => d.y);
return [
{p, method: "Least squares", r2: r2(ridge(X, y, 0), p)},
{p, method: "Ridge (regularized)", r2: r2(ridge(X, y, lambda), p)}
];
});
}
Plot.plot({
ariaLabel: "The Blessing of Dimensionality: simulation chart",
ariaDescription: "Horizontal axis: Number of predictors (dimensions). Vertical axis: Out-of-sample R². The chart updates with the controls above it, and the summary below the charts states the result in words.",
height: 300,
x: {label: "Number of predictors (dimensions)"},
y: {label: "Out-of-sample R²", grid: true, domain: [-0.5, 1]},
color: {legend: true, range: ["#d6604d", "#2166ac"]},
marks: [Plot.line(dims, {x: "p", y: "r2", stroke: "method", strokeWidth: 2, marker: "circle"}), Plot.ruleY([0])]
})# The Blessing of Dimensionality: more predictors, with regularization.
1signal <- 0.15 # size of each true coefficient
lambda <- 40 # ridge penalty
2set.seed(20)
P <- 90
n <- 100
3beta <- signal * sample(c(-1, 1), P, replace = TRUE)
make <- function(m) {
X <- matrix(rnorm(m * P), m, P)
list(X = X, y = as.vector(X %*% beta + rnorm(m)))
}
train <- make(n)
test <- make(500)
# Ridge regression with an unpenalized intercept (lambda = 0: least squares)
4ridge <- function(X, y, lambda) {
Xc <- scale(X, scale = FALSE)
b <- solve(
crossprod(Xc) + (lambda + 1e-9) * diag(ncol(X)),
crossprod(Xc, y - mean(y))
)
list(a = mean(y) - sum(colMeans(X) * b), b = b)
}
5r2 <- function(fit, p) {
pred <- fit$a + test$X[, 1:p, drop = FALSE] %*% fit$b
max(-0.5, 1 - sum((test$y - pred)^2) / sum((test$y - mean(test$y))^2))
}
ps <- seq(10, 90, by = 10)
6res <- t(sapply(c(5, ps), function(p) {
X <- train$X[, 1:p, drop = FALSE]
c(
p = p, least_squares = r2(ridge(X, train$y, 0), p),
ridge = r2(ridge(X, train$y, lambda), p)
)
}))
print(round(res, 2)) # out-of-sample R squared (floored at -0.5)
7matplot(res[, "p"], res[, -1],
type = "b", pch = 19, lty = 1,
col = c("#d6604d", "#2166ac"), xlab = "Number of predictors",
ylab = "Out-of-sample R squared"
)
legend("bottomleft", c("Least squares", "Ridge (regularized)"),
col = c("#d6604d", "#2166ac"), pch = 19, bty = "n"
)- 1
- The page’s controls: the size of each true coefficient and the ridge penalty.
- 2
- Fixes the random numbers so the run is reproducible.
- 3
- Ninety predictors, each with a small real effect. More predictors carry more signal, if the model can use it.
- 4
- Ridge regression, written out with an unpenalized intercept. A penalty of zero gives least squares.
- 5
- Out-of-sample R squared on a separate test set, floored at -0.5 so a disastrous fit doesn’t swamp the chart.
- 6
- Fit both estimators with the first p predictors, for p from 5 to 90, against 100 training cases.
- 7
- Least squares falls apart as p approaches n; the regularized fit keeps improving. That is the blessing.
# The Blessing of Dimensionality: more predictors, with regularization.
import numpy as np
import matplotlib.pyplot as plt
signal = 0.15 # size of each true coefficient
lam = 40 # ridge penalty
rng = np.random.default_rng(20)
P, n = 90, 100
beta = signal * rng.choice([-1, 1], P)
def make(m):
X = rng.normal(size=(m, P))
return X, X @ beta + rng.normal(size=m)
X_train, y_train = make(n)
X_test, y_test = make(500)
def ridge(X, y, lam):
"""Ridge with an unpenalized intercept (lam = 0: least squares)."""
mx, my = X.mean(axis=0), y.mean()
Xc = X - mx
b = np.linalg.solve(Xc.T @ Xc + (lam + 1e-9) * np.eye(X.shape[1]),
Xc.T @ (y - my))
return my - mx @ b, b
def r2(fit, p):
a, b = fit
pred = a + X_test[:, :p] @ b
sst = np.sum((y_test - y_test.mean()) ** 2)
return max(-0.5, 1 - np.sum((y_test - pred) ** 2) / sst)
ps = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90]
ls = [r2(ridge(X_train[:, :p], y_train, 0), p) for p in ps]
rd = [r2(ridge(X_train[:, :p], y_train, lam), p) for p in ps]
for p, a, b in zip(ps, ls, rd):
print(f"{p:3d} predictors: least squares R2 {a:5.2f}, ridge R2 {b:5.2f}")
plt.plot(ps, ls, "o-", color="#d6604d", label="Least squares")
plt.plot(ps, rd, "o-", color="#2166ac", label="Ridge (regularized)")
plt.xlabel("Number of predictors")
plt.ylabel("Out-of-sample R squared (floored at -0.5)")
plt.legend()
plt.show()Key takeaways
- More variables are more information. Discarding them should be a last resort.
- The “curse” belongs to unregularized estimators. Priors, penalties and hierarchical models turn it into a blessing.
- If adding information makes your estimates worse, fix the method.
Source
- Andrew Gelman, The blessing of dimensionality (2004).