Effect of k on variance and bias in KNN
In k-Nearest Neighbors (k-NN), the neighborhood size k acts inversely to model complexity. A small k yields low bias and high variance because predictions closely follow individual noisy training points (overfitting), while a larger k averages over broader neighborhoods to reduce variance at the expense of higher bias and smoother decision boundaries (underfitting).
Study Card: Effect of k on variance and bias in KNN
Direct Answer
In K-Nearest Neighbors (KNN), the hyperparameter directly governs the bias-variance tradeoff because effective model complexity scales inversely with (roughly effective degrees of freedom). When is small (e.g., ), the model makes almost no smoothing assumptions, producing low bias and very high variance—sensitive to every noisy point or outlier. As increases, predictions average over a wider neighborhood, stabilizing estimates and lowering variance while raising bias as distant points from other classes or target regimes blur local boundaries.
For uniform-weighted k-NN regression under with independent noise variance , the expected squared prediction error at query makes this tradeoff explicit:
Here, the variance term shrinks monotonically as grows, while the squared bias term grows as neighbors lie farther from .
Key Terms
- Bias: Systematic error from oversmoothing the target function when averages across too wide a neighborhood.
- Variance: Prediction sensitivity to particular noisy samples or outliers in the training set when is too small.
- Bias-Variance Tradeoff: Balancing local flexibility (small ) against noise smoothing (larger ) to minimize out-of-sample error.
Example
Consider two classes A and B arranged along noisy interleaving moons:
- Small (): Every single noisy outlier creates an isolated pocket of its own label around itself. Training accuracy reaches 100%, but the jagged boundary generalizes poorly (high variance).
- Large ( or ): The neighborhood around any query covers a huge region of feature space, erasing fine curvature and predicting toward whichever class dominates globally. Decision boundaries become overly smooth and underfit local pockets (high bias).
- Intermediate (e.g., via cross-validation): Averages away isolated outliers while preserving the true curved crescent boundary, minimizing test error.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
# Generate synthetic non-linear dataset with noise
X, y = make_moons(n_samples=300, noise=0.3, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
def plot_decision_boundary(model, X_pts, y_pts, ax, title):
h = 0.02
x_min, x_max = X_pts[:, 0].min() - 1, X_pts[:, 0].max() + 1
y_min, y_max = X_pts[:, 1].min() - 1, X_pts[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
ax.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
ax.scatter(X_pts[:, 0], X_pts[:, 1], c=y_pts, s=30, cmap=plt.cm.Spectral, edgecolors='k')
ax.set_title(title)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# Compare k=1 (high variance), k=10 (balanced), k=50 (high bias)
for k, ax in zip([1, 10, 50], axes):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
train_acc = knn.score(X_train, y_train)
test_acc = knn.score(X_test, y_test)
plot_decision_boundary(knn, X_test, y_test, ax, f'KNN (k={k}) | Test={test_acc:.2f}')
print(f'k={k:2d}: Train Accuracy = {train_acc:.4f}, Test Accuracy = {test_acc:.4f}')
plt.tight_layout()
plt.show()
Related Concepts
- Cross-Validation: Selecting empirically by minimizing cross-validated error across training folds.
- Distance-Weighted k-NN: Weighting neighbors by inverse distance helps maintain low bias even at slightly higher values while keeping variance bounded.
- Curse of Dimensionality: In high dimensions, even the nearest neighbors can sit far from , causing both high bias and unstable distance rankings unless dimensionality is reduced.
- Overfitting vs. Underfitting: Recognizing how parallels inverse regularization strength in parametric models ( overfits like ; underfits like ) and understanding its effect on bias and variance.