- Introduced by
- Wu, Z. et al. / Chen, T. et al.
- Year
- 2018–2020
- Type
- Self-supervised + non-parametric classifier
- Family
- Machine learning
What does it do?
Self-supervised K-nearest neighbors (SSL-kNN) combines representation learning without labels with a non-parametric k-NN classifier.
A neural encoder is first trained via a self-supervised objective — such as contrastive or masked prediction — so that semantically similar samples cluster together in the embedding space. A simple k-NN lookup on those embeddings then assigns class labels, serving both as a lightweight probe and as a practical classifier.
The intuition behind the method
Conventional k-NN works directly on raw features, so its accuracy is limited by how well those features separate the classes. Self-supervised pre-training reshapes the embedding space so that augmented views of the same sample, and similar samples more generally, lie close together, without using any labels. Once the space has this structure, a simple k-NN lookup can classify queries with little additional machinery. The approach serves two purposes: as an evaluation protocol for judging how useful a self-supervised representation is, and as a classifier that needs only a small labelled support set.
History
Wu et al. (2018) framed instance discrimination as a non-parametric classification problem and showed that the resulting compact features support fast nearest-neighbour retrieval at run time. The use of k-NN accuracy as an evaluation protocol for self-supervised features is not attributed to a specific origin here. SimCLR (Chen et al., 2020) is a contrastive learning framework for visual representations and is cited for its pre-training objective rather than for the k-NN protocol.
When to use it
Use SSL-kNN when labelled data are scarce or absent and a large pool of unlabelled data is available for pre-training. It is a reasonable choice for evaluating a self-supervised representation with a non-parametric classifier, and when training a classifier head on the embeddings is not wanted. It also suits open-set or growing label inventories, because a new class only requires adding labelled embeddings to the support set rather than retraining the encoder. Avoid it when labelled data are plentiful, since fully supervised fine-tuning is then likely to be preferable, and when the pre-training data do not resemble the target domain. If the raw feature space is already compact and class-separated, standard supervised k-NN may be sufficient at lower cost. Memory and retrieval costs grow with the size of the support set. The method assumes that the labels in the support set are correct. Because the prediction is a majority vote, frequent classes dominate under class imbalance, so the class counts in the support set should be checked.
Limitations and considerations
- Classification quality depends on the pre-training objective and the encoder architecture; a weak self-supervised encoder yields weak neighbourhoods.
- k-NN retrieval becomes slow and memory-intensive as the support set grows to millions of samples without approximate nearest-neighbour indexing.
- Optimal k is dataset-dependent and requires tuning; too small a k is noisy, too large a k blurs decision boundaries.
- Under significant domain shift between pre-training data and the target domain, embedding quality degrades and k-NN accuracy can drop substantially.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Encoder training needs no labels; labels are needed only for the support set used at inference.
- The classifier has no trained parameters, so the main tuning decisions are the choice of k and the distance metric, both of which can be checked on a validation split.
- New classes can be added by inserting labelled embeddings into the support set without retraining the encoder, provided the frozen embedding separates the new classes; this should be verified on validation data.
- Any self-supervised backbone can be substituted, since the k-NN step operates only on the embedding vectors; accuracy changes with the backbone, so results should be re-evaluated after a swap.
- The k-NN accuracy gives a direct read-out of how well the frozen representation separates the classes.
Applications
- Label-free image classification using contrastive or masked pre-training followed by k-NN lookup.
- Evaluation metric for self-supervised learning: k-NN accuracy as a proxy for representation quality.
- Open-set and continual learning where the label inventory grows without requiring encoder retraining.
- Retrieval-augmented classification in medical imaging or remote sensing with limited annotated data.
- Anomaly detection by flagging query embeddings whose k-NN distances exceed a threshold.
How it works
How it works
An encoder (e.g., a ResNet or Vision Transformer) is trained using a self-supervised objective with no class labels. Common objectives include contrastive loss (SimCLR, MoCo), clustering loss (SwAV), or masked image modelling (MAE). The goal is to produce embeddings z such that augmented views of the same sample are close and views of different samples are far apart.
After pre-training, the encoder is frozen and all samples, training and query alike, are passed through it to produce fixed-dimensional embedding vectors. No fine-tuning on labels is required at this stage, making the step entirely unsupervised.
For each query embedding z_q, the k nearest neighbours are retrieved from a labelled or pseudo-labelled support set using cosine or Euclidean distance. The predicted label is the majority class among those k neighbours, which is the mode written in the formula above. Distance-weighted voting is a different rule from this formula, so results from weighted implementations should not be compared directly with it. Ties in the vote must be broken by a fixed, reported rule, for example by choosing an odd k for binary tasks.
Formula
\hat{y} = \text{mode}\{y_i : i \in \text{kNN}(\mathbf{z}_q)\}Accuracy of the k-NN classifier on a held-out test set is reported, computed on the frozen embeddings. Because no labels were used to train the encoder, the score is a useful proxy for how well the frozen representation separates the classes. It also depends on k, the distance metric, the support set and the match between pre-training and target domains, so these settings should be reported alongside the score. The value of k should be fixed on a validation split before the test set is evaluated.
Common pitfalls
- Using raw pixel features or non-SSL embeddings and expecting the same accuracy as a properly pre-trained encoder.
- Evaluating k-NN on training-set neighbours rather than a truly held-out test set, inflating reported accuracy.
- Ignoring the choice of distance metric: cosine similarity is often preferred to Euclidean distance for normalised high-dimensional embeddings, so the choice should be checked on validation data.
- Selecting k based on test-set performance rather than a validation set, which leaks labels into hyperparameter selection.
- Assuming k-NN accuracy is directly comparable across studies that used different encoders, datasets, or support-set sizes.
Frequently asked questions
How is SSL-kNN different from standard supervised kNN?
Standard kNN operates on hand-crafted or task-specific features and requires labeled training samples to build its support set. SSL-kNN first learns a general-purpose embedding via self-supervised pre-training on unlabeled data; the k-NN step is then applied in that learned space, which typically produces far better representations than raw features.
What value of k should I use?
The appropriate k depends on the dataset and the size of the support set. Larger k gives more stable predictions but can blur boundaries between similar classes, while very small k is sensitive to noisy neighbours. Tune k on a validation split, not the test set, and report the value used.
Can SSL-kNN be used for regression rather than classification?
Yes. Replace majority-vote aggregation with the mean (or weighted mean) of the k neighbors' continuous target values. The self-supervised encoder still provides the embedding; only the aggregation step changes.
How much labeled data is needed for the support set?
The encoder training itself requires no labels at all. Accuracy with very few labelled support examples depends on how well the encoder separates the classes, so the support-set size should be varied and reported.
Is approximate nearest-neighbor (ANN) retrieval acceptable?
Yes, and for large support sets it is often necessary. Libraries such as FAISS, ScaNN, or HNSWlib provide sub-linear retrieval; they trade some exactness for speed, so the effect on accuracy should be measured against exact k-NN on the same embeddings.
Related methods
Sources
Chen, T., Kornblith, S., Norouzi, M., & Hinton, G. (2020). A simple framework for contrastive learning of visual representations. In Proceedings of the 37th International Conference on Machine Learning (ICML), PMLR 119, 1597–1607.
Open publication referenceWu, Z., Xiong, Y., Yu, S. X., & Lin, D. (2018). Unsupervised feature learning via non-parametric instance discrimination. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 3733–3742.
Open DOI reference