Skip to content
E
Educatum

Effect of k on variance and bias in KNN

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 kk directly governs the bias-variance tradeoff because effective model complexity scales inversely with kk (roughly N/kN / k effective degrees of freedom). When kk is small (e.g., k=1k = 1), the model makes almost no smoothing assumptions, producing low bias and very high variance—sensitive to every noisy point or outlier. As kk 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 Y=f(x)+εY = f(x) + \varepsilon with independent noise variance σ2\sigma^2, the expected squared prediction error at query xx makes this tradeoff explicit:

MSE(x)=(f(x)−1k∑i∈Nk(x)f(xi))2+σ2k+σ2\text{MSE}(x) = \left(f(x) - \frac{1}{k}\sum_{i \in N_k(x)} f(x_i)\right)^2 + \frac{\sigma^2}{k} + \sigma^2

Here, the variance term σ2/k\sigma^2 / k shrinks monotonically as kk grows, while the squared bias term grows as neighbors xi∈Nk(x)x_i \in N_k(x) lie farther from xx.

Key Terms

  • Bias: Systematic error from oversmoothing the target function when kk averages across too wide a neighborhood.
  • Variance: Prediction sensitivity to particular noisy samples or outliers in the training set when kk is too small.
  • Bias-Variance Tradeoff: Balancing local flexibility (small kk) against noise smoothing (larger kk) to minimize out-of-sample error.

Example

Consider two classes A and B arranged along noisy interleaving moons:

  • Small kk (k=1k = 1): 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 kk (k=50k = 50 or k=N/2k = N/2): 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 kk (e.g., k=10k = 10 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()
  • Cross-Validation: Selecting kk empirically by minimizing cross-validated error across training folds.
  • Distance-Weighted k-NN: Weighting neighbors by inverse distance 1/d(x,xi)1 / d(x, x_i) helps maintain low bias even at slightly higher kk values while keeping variance bounded.
  • Curse of Dimensionality: In high dimensions, even the kk nearest neighbors can sit far from xx, causing both high bias and unstable distance rankings unless dimensionality is reduced.
  • Overfitting vs. Underfitting: Recognizing how 1/k1/k parallels inverse regularization strength in parametric models (k=1k=1 overfits like λ→0\lambda \to 0; k=Nk=N underfits like λ→∞\lambda \to \infty) and understanding its effect on bias and variance.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.