Skip to content
ml-recall

Topic notes

Nearest Neighbors & Kernel Methods

Methods that keep the training data instead of a fixed set of weights — k-nearest neighbours, kernel (Nadaraya–Watson) regression, kernels, Gaussian processes and fast similarity search.

5-min read AI-checked

Practise 39 questions Take a test

Key ideas

Nonparametric methods have no fixed-size weight vector: the model is (part of) the training data, so its capacity — and its memory and prediction cost — grow with the data.

kk-nearest neighbours1. fit only stores the training set; to predict, find the kk training points closest to the query (usually Euclidean distance) and take a majority vote of their labels (classification) or the mean of their targets (regression). With uniform weights, predict_proba is the fraction of neighbours in each class; weights="distance" gives closer neighbours more say1. It needs labels, so the classifier is supervised (plain neighbour search is not).

Kernel (Nadaraya–Watson) regression3. Predict a weighted average of all training labels, with weights from a kernel of the distance, normalized to sum to 1; nothing is trained. The bandwidth σ\sigma is the knob: a narrow kernel follows local variation (wiggly, high variance), a wide one smooths (high bias), and as σ→∞\sigma \to \infty the prediction becomes the global mean of yy. The kernel's shape (Gaussian, boxcar, Epanechnikov) matters much less, and its height cancels in the normalization3. Tuning σ\sigma on training error drives it to 0, because each point then predicts its own label — use leave-one-out or cross-validation. The estimator is consistent if the kernel is narrowed suitably as data grow3. A kernel density estimate sums the same kernels without dividing by their total.

Kernels4. A (positive semidefinite) kernel k(x,x′)k(\mathbf{x}, \mathbf{x}') is a similarity whose Gram matrix on every finite set of points is positive semidefinite. Nonnegative combinations, products and limits of kernels are again kernels4; hence so are exp⁡\exp of a kernel (a limit of sums of products) and g(x)g(x′)g(\mathbf{x})g(\mathbf{x}') (its Gram matrix is gg⊤\mathbf{g}\mathbf{g}^\top). A difference of kernels need not be one: k−2k=−kk - 2k = -k. The kernel encodes assumptions — the RBF kernel lets correlation fade steadily with distance, so data with a cycle (hourly demand repeating every 24 hours) calls for a periodic kernel. Kernel ridge regression predicts k(x∗,X)(K+λI)−1yk(\mathbf{x}_*, X)(K + \lambda I)^{-1}\mathbf{y}, the same form as the GP mean below; for distinct inputs the RBF Gram matrix KK is invertible, so as λ→0\lambda \to 0 the fit interpolates the training data — zero training error, overfitting. The perceptron has a kernel form too: starting from zero, its weight vector is a sum of the misclassified inputs, so f(x)=∑imiyi k(xi,x)f(\mathbf{x}) = \sum_i m_i y_i\, k(\mathbf{x}_i, \mathbf{x}) with mim_i the number of mistakes made on xi\mathbf{x}_i.

Gaussian processes5. A GP is a prior over functions: any finite set of function values is jointly Gaussian, with mean function m(x)m(\mathbf{x}) and covariance given by a kernel5. Read the RBF kernel (Formulas): k(x,x)=a2k(\mathbf{x}, \mathbf{x}) = a^2 is the prior variance, so the amplitude aa sets the vertical scale; the correlation fades over distances of order ℓ\ell, so the length-scale ℓ\ell sets the wiggliness — small ℓ\ell gives fast variation, large ℓ\ell slowly varying functions. Predictive uncertainty grows as the query moves away from the training inputs5, and the faster the smaller ℓ\ell is. With observation noise σ2\sigma^2, the posterior mean is a kernel-weighted combination of the training targets; a large σ2\sigma^2 lets it pass farther from the points, a tiny one makes it nearly interpolate. Exact inference solves a linear system and a log-determinant with the n×nn \times n matrix K+σ2IK + \sigma^2 I: O(n3)O(n^3) time and O(n2)O(n^2) memory, historically limiting exact GPs to about 10,000 points5. After that factorization, each test point costs O(n)O(n) for the mean and O(n2)O(n^2) for the variance. Sums of independent GPs are GPs with summed kernels (scaling a GP by cc scales its kernel by c2c^2).

Similarity search at scale6. Locality-sensitive hashing wants collisions, but only between similar items, so a query is compared with the items in its buckets only. MinHash is such a hash for sets: two sets get the same min-hash with probability equal to their Jaccard similarity; random hyperplanes give such a hash for the angle between vectors (cosine similarity)6.

Formulas

y^kNN(x)=1k∑i∈Nk(x)yi,y^NW(x)=∑iyi K(x−xi)∑jK(x−xj)\hat y_{k\text{NN}}(\mathbf{x}) = \frac{1}{k}\sum_{i \in N_k(\mathbf{x})} y_i, \qquad \hat y_{\text{NW}}(\mathbf{x}) = \frac{\sum_i y_i\,K(\mathbf{x} - \mathbf{x}_i)}{\sum_j K(\mathbf{x} - \mathbf{x}_j)} kRBF(x,x′)=a2exp⁡ ⁣(−∥x−x′∥22ℓ2),μ(x∗)=k(x∗,X) [K+σ2I]−1yk_{\text{RBF}}(\mathbf{x}, \mathbf{x}') = a^2\exp\!\Big(-\frac{\lVert\mathbf{x} - \mathbf{x}'\rVert^2}{2\ell^2}\Big), \qquad \mu(\mathbf{x}_*) = k(\mathbf{x}_*, X)\,[K + \sigma^2 I]^{-1}\mathbf{y}

Curse of dimensionality: in the unit cube [0,1]p[0, 1]^p with uniform data, a sub-cube holding a fraction rr of the points needs edge length r1/pr^{1/p}.

Worked example

Training data x=(1,2,4,7)x = (1, 2, 4, 7), y=(1,3,2,6)y = (1, 3, 2, 6); query x=3x = 3.

In code

from sklearn.datasets import load_wine
from sklearn.model_selection import cross_validate
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)        # 13 features on very different scales
res = {}
for scaled in [False, True]:
    for k in [1, 15]:
        knn = KNeighborsClassifier(n_neighbors=k)
        model = make_pipeline(StandardScaler(), knn) if scaled else knn
        cv = cross_validate(model, X, y, cv=5, return_train_score=True)
        res[scaled, k] = (float(cv["train_score"].mean().round(2)), float(cv["test_score"].mean().round(2)))
print(res)  # {(False, 1): (1.0, 0.73), (False, 15): (0.73, 0.71), (True, 1): (1.0, 0.95), (True, 15): (0.97, 0.96)}

Keys are (scaled?, kk), values (training accuracy, validation accuracy): 1-NN is always perfect on its training folds; scaling lifts validation accuracy from about 0.7 to 0.95.

Common pitfalls

References

  1. scikit-learn User Guide — Sec. 1.6 Nearest Neighbors (1.6.2 Classification, 1.6.3 Regression, 1.6.4 Nearest Neighbor Algorithms)
  2. Wikipedia: k-nearest neighbors algorithm — Parameter selection; Dimension reduction; Data reduction
  3. Dive into Deep Learning — Sec. 11.2 Attention Pooling by Similarity (11.2.1 Kernels and Data, 11.2.2 Attention Pooling via Nadaraya–Watson Regression)
  4. Wikipedia: Positive-definite kernel — Definition (Some general properties; Examples of p.d. kernels)
  5. Dive into Deep Learning — Sec. 18.3 Gaussian Process Inference (18.3.1 Posterior Inference for Regression; 18.3.2 Equations for Making Predictions and Learning Kernel Hyperparameters in GP Regression; 18.3.3 Interpreting Equations for Learning and Predictions)
  6. Wikipedia: Locality-sensitive hashing — Definitions; Methods (Min-wise independent permutations, Random projection); Algorithm for nearest neighbor search