Online K-Nearest Neighbors

Machine Learning
Introduced by
Extension of Fix & Hodges (1951) KNN to the streaming/online setting; notable online variant by Losing et al. (2016)
Year
2010s (formalized in streaming-learning literature)
Type
Instance-based online classifier/regressor
Family
Machine learning

What does it do?

Online K-Nearest Neighbors (Online KNN) adapts the classic KNN algorithm to a data-stream setting where observations arrive sequentially and the model must update incrementally without full retraining.

Instead of storing all historical instances, it maintains a bounded sliding window or adaptive memory, using the most recent examples, or a representative subset chosen by a selection rule, to classify or predict each incoming point by proximity.

The intuition behind the method

Classic KNN is lazy: it stores every training point and searches them all at query time. In a stream the data keep arriving, so storing everything is impractical, and older examples may stop describing the current concept (concept drift). Online KNN therefore keeps a bounded buffer of recent or selected instances. Each incoming point is labelled by the majority class of its k nearest buffered neighbours, and only then is the point added to the buffer, with a forgetting rule removing old or less useful entries once capacity is reached. Because the buffer is the model, its size and eviction rule determine how quickly predictions follow a change in the data.

History

The k-nearest-neighbour rule is the basis of this method; online variants apply the same rule to streams through buffer management and forgetting, as described above. Losing, Hammer, and Wersing (2016) proposed Self Adjusting Memory kNN (SAM-kNN) for heterogeneous concept drift, meaning different drift types and rates. SAM-kNN uses biologically inspired memory models: it maintains dedicated models for the current and former concepts and coordinates their use according to the demands of the situation. The buffer mechanisms described on this page are a simpler form of this design. The authors report that the meta-parameters of SAM-kNN do not need to be optimised in practice, and they evaluate it on artificial streams with known drift characteristics as well as on real-world datasets.

When to use it

Choose Online KNN when observations arrive as a stream, retraining a model from scratch on each update is not feasible, and the features are numeric enough to admit a meaningful distance measure. It is a reasonable fit when the distribution may change over time, because the buffer lets old instances expire. Avoid it when the feature space is very high-dimensional, since distances concentrate and neighbour search loses discriminative value; when query latency is critical and the buffer is large, since each prediction scans stored instances unless an approximate index is used; or when a compact, interpretable model is required. If the data are stationary and fit in memory, batch KNN is simpler and avoids buffer-management choices, so it is the natural baseline to compare against.

Limitations and considerations

  • Prediction cost scales with buffer size, because each query scans the stored instances unless an approximate nearest-neighbour index is maintained.
  • Performance degrades in high-dimensional feature spaces because distances between points become less discriminative (the curse of dimensionality).
  • Scaling statistics estimated from early data may no longer match later data when the distribution drifts, so the normalisation itself can become stale.
  • Buffer size and forgetting rule must match the drift speed of the specific stream; no single setting suits all streams.
  • Under drift, the buffer holds only recent labelled instances, so a class that rarely appears in recent data can be forgotten and then predicted poorly.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Incremental updates: a new labelled instance is added to the buffer without retraining. Each prediction scans the buffer, so its cost grows with buffer size, O(n_buffer).
  • Drift handling is built into the memory: the forgetting rule lets stale instances leave the buffer, so neighbours can come from recent data. How well this tracks a change depends on the eviction rule, buffer capacity and drift speed (see limitations).
  • No parametric assumption about the feature distribution, so the method can represent nonlinear decision boundaries that a fixed linear model cannot.
  • The same lookup mechanism serves classification (majority vote) and regression (mean of neighbour targets).
  • The main design choices are explicit and inspectable: buffer capacity, forgetting rule, k, and distance metric.

Applications

  • Network intrusion detection, where attack patterns change over time and a buffer of recent traffic keeps the comparison set current.
  • Sensor stream classification where sensor drift shifts feature values gradually, so a recency-based buffer tracks the change.
  • User behaviour and recommendation modelling where preferences change, with the buffer limiting the influence of old interactions.
  • Fraud screening of transaction streams whose patterns shift, using recent labelled transactions as the comparison set.

How it works

How it works

1

A buffer of fixed capacity is initialised with training instances. It keeps the most recent observations, or a representative subset chosen by a forgetting strategy, so that predictions reflect the current distribution rather than older data that may no longer apply.

2

For each query point, the distance to every instance in the buffer is computed. The formula above uses Euclidean distance, although other metrics can be chosen. That formula applies to numeric features; data with mixed numeric and categorical features need a distance measure that handles the categorical variables. Because distances are used directly, numeric features on different scales must be normalised or standardised first; otherwise large-magnitude features dominate the comparison.

Formula
d(x_q, x_i) = \|x_q - x_i\|_2
3

The k buffered instances with the smallest distances are selected. For classification, the predicted label is the majority class among them, which is the form given in the formula above. For regression, the prediction is the mean (or distance-weighted mean) of their target values. A small k is flexible but sensitive to noise; a large k is more stable but can smooth over local structure.

Formula
\hat{y} = \text{mode}(\{y_i : x_i \in \text{kNN}(x_q)\})
4

After the prediction, the labelled instance is added to the buffer. If capacity is exceeded, an entry is removed by the forgetting rule, such as first-in-first-out eviction, reservoir sampling, or retaining instances that were recently misclassified.

5

When concept drift is expected, a detector such as ADWIN or DDM can be coupled with the buffer. On a detected change, the buffer can be shrunk or emptied so that predictions rely mainly on data from after the change.

Common pitfalls

  • Computing distances on unscaled or inconsistently scaled features, so that high-magnitude variables dominate similarity.
  • Setting the buffer too large in a fast-drifting stream, so the model keeps anchoring to outdated examples and reacts slowly to change.
  • Ignoring class imbalance in the buffer, which biases the majority vote toward the dominant class.
  • Using very high-dimensional data without dimensionality reduction, where distance-based neighbours lose meaning.
  • Running without any eviction rule, so the buffer never forgets and the model cannot adapt to drift.
  • Evaluating with random shuffles of a stream; evaluation should follow stream order (for example, test-then-train), otherwise future information leaks into the results.

Frequently asked questions

How does Online KNN differ from standard batch KNN?

Standard KNN stores all training data and is retrained from scratch on any update. Online KNN maintains a bounded buffer of recent or informative instances, updates it incrementally after each new observation, and can adapt to concept drift by expiring old examples, which makes it practical for continuous data streams.

How should I choose the buffer size and k?

Buffer capacity should reflect how quickly the concept changes: faster drift favours a smaller buffer that forgets sooner. k is chosen as in standard KNN: a larger k smooths predictions but may respond more slowly to new patterns, while a smaller k is more responsive but noisier. Because no fixed setting suits all streams, candidate buffer sizes and values of k are best compared on the target stream using test-then-train evaluation.

Does Online KNN require feature scaling?

Yes. KNN classifies by distance, so features on larger numerical scales dominate similarity calculations unless each feature is standardised or normalised to a common range before distances are computed. If the scaling is estimated from early data, it should be reviewed when the distribution drifts.

What if concept drift occurs abruptly rather than gradually?

Coupling Online KNN with a drift detector such as ADWIN or DDM allows abrupt changes to be detected statistically, so the buffer can be flushed or shrunk and predictions quickly reflect the new regime rather than averaging over obsolete data.

Is Online KNN suitable for high-dimensional data?

Not without preprocessing. In high-dimensional spaces, distances between points become similar and nearest-neighbour search becomes uninformative. Dimensionality reduction (such as PCA or feature selection) before Online KNN is strongly recommended when the feature count is large relative to the buffer size.

Related methods

Sources

  1. Losing, V., Hammer, B., & Wersing, H. (2016). KNN Classifier with Self Adjusting Memory for Heterogeneous Concept Drift. In Proceedings of the IEEE 16th International Conference on Data Mining (ICDM), pp. 291–300. IEEE.

    Open DOI reference
  2. Gama, J. (2010). Knowledge Discovery from Data Streams. CRC Press / Chapman & Hall.

    ISBN: 978-1-4398-2611-9