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.
-nearest neighbours1. fit only stores the training set; to predict, find the 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).
- is the complexity knob1,2. copies the nearest training label: zero training error (each training point is its own neighbour, unless identical inputs carry different labels) and a jagged boundary made of Voronoi cell walls — high variance. Larger suppresses noise and smooths the boundary, so training error usually rises; with uniform weights, predicts the majority class everywhere. Choose by cross-validation; an odd avoids ties for two classes2.
- Distances need care2. Without scaling, a feature measured in dollars swamps one measured in years; irrelevant features add noise to every distance, and -NN gives every feature equal weight — it selects none. In high dimension, neighbourhoods stop being local: the curse of dimensionality2.
- Cost1. Training is almost free, but a brute-force query computes distances in dimensions, , and barely depends on . k-d and ball trees cut a query to about in low dimension (k-d trees below roughly 20 features) and degrade toward as grows1. Removing training points whose removal changes no prediction (condensed nearest neighbour) shrinks the stored set2.
- When to use: low dimension, plenty of data, few queries, irregular boundaries. Wide sparse data such as word counts favour trees, naive Bayes or linear models.
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 is the knob: a narrow kernel follows local variation (wiggly, high variance), a wide one smooths (high bias), and as the prediction becomes the global mean of . The kernel's shape (Gaussian, boxcar, Epanechnikov) matters much less, and its height cancels in the normalization3. Tuning 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 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 of a kernel (a limit of sums of products) and (its Gram matrix is ). A difference of kernels need not be one: . 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 , the same form as the GP mean below; for distinct inputs the RBF Gram matrix is invertible, so as 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 with the number of mistakes made on .
Gaussian processes5. A GP is a prior over functions: any finite set of function values is jointly Gaussian, with mean function and covariance given by a kernel5. Read the RBF kernel (Formulas): is the prior variance, so the amplitude sets the vertical scale; the correlation fades over distances of order , so the length-scale sets the wiggliness — small gives fast variation, large slowly varying functions. Predictive uncertainty grows as the query moves away from the training inputs5, and the faster the smaller is. With observation noise , the posterior mean is a kernel-weighted combination of the training targets; a large 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 matrix : time and memory, historically limiting exact GPs to about 10,000 points5. After that factorization, each test point costs for the mean and for the variance. Sums of independent GPs are GPs with summed kernels (scaling a GP by scales its kernel by ).
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
Curse of dimensionality: in the unit cube with uniform data, a sub-cube holding a fraction of the points needs edge length .
Worked example
Training data , ; query .
- : neighbours and (both at distance 1), prediction . adds : . : the global mean, 3.0.
- Nadaraya–Watson, Gaussian kernel, : unnormalized weights , normalized , prediction . With it is (close to 2-NN); with , (the global mean).
- Curse of dimensionality: a sub-cube holding 10% of uniform data has edge 0.1 in 1-D, 0.316 in 2-D and 0.891 in 20-D — hardly "local".
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?, ), 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
- The neighbours come from the training set; test examples are only queries.
- A larger gives a simpler model and usually a higher training error; has zero training error.
- -NN needs scaled features and suffers from irrelevant ones; it neither selects nor weights features.
- Prediction, not training, is the slow part: cost grows with , while barely matters for brute force.
- In kernel regression the bandwidth matters far more than the kernel's shape; never pick it by training error.
- A GP's amplitude rescales the functions vertically ( from 1 to 9 triples their spread) without changing how fast they wiggle; that is the length-scale's job.
- Exact GP training is cubic in : three times the data costs 27 times the time and 9 times the memory.
- Sums and products of valid kernels are valid kernels; differences are not guaranteed to be.
References
- scikit-learn User Guide — Sec. 1.6 Nearest Neighbors (1.6.2 Classification, 1.6.3 Regression, 1.6.4 Nearest Neighbor Algorithms)
- Wikipedia: k-nearest neighbors algorithm — Parameter selection; Dimension reduction; Data reduction
- 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)
- Wikipedia: Positive-definite kernel — Definition (Some general properties; Examples of p.d. kernels)
- 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)
- Wikipedia: Locality-sensitive hashing — Definitions; Methods (Min-wise independent permutations, Random projection); Algorithm for nearest neighbor search