Skip to content

KNN

Algorithm

K-nearest neighbors classifies a sample using nearby labeled training observations. Feature scale affects Euclidean distance, so ToyML offers optional standardization. Training stores the observations; prediction computes their distances to the query and returns the most frequent label among the k closest observations.

Inputs and limitations

  • Each fit validates k, std_transform, and distance_metric together with the training data. After changing any of them, fit the same classifier again before calling predict. The keyword-only distance_metric currently supports "euclidean" (the default).
  • Fit on at least k samples. Each row must have the same positive number of finite numeric features and one hashable label. A successful refit replaces the previous training data. A failed refit preserves the previously fitted attributes.
  • With the default std_transform=True, training and prediction use the training set's feature means and population standard deviations (ddof=0, dividing variance by the training sample count). Constant features use a scale of one. Select False to work in the original feature units.
  • Pass one feature vector to predict. Samples whose computed distances round to the same float retain training order. For example, with standardization disabled, [1, 2**-27] and [1, 0] both have a computed distance of 1.0 from the origin. With k=1, the first training row gets the vote. If labels tie for the most votes, the first tied label in nearest-neighbor order wins.

Minimal example

from toyml.classification import KNN

samples = [[0.0], [0.2], [4.0], [4.2]]
model = KNN(k=2, std_transform=False).fit(samples, ["near", "near", "far", "far"])
print(model.predict([0.1]))

Numerical stability

If a varying feature's population standard deviation rounds to zero or is subnormal, the standardizer divides that column by the smallest positive normal float (2**-1022) and computes the mean and standard deviation in that unit. It uses the same unit for later queries. For the training column [0, 0, 0, 0, 5e-324], the four zeros have a standard score of -0.5 and the last value scores 2.0. A new value of 1e-323 scores 4.5.

If subtracting the mean would overflow, the standardizer divides both operands by the scale before subtracting. A standardized value outside the floating-point range raises ValueError. The standardizer's fit_transform saves the fitted statistics before transforming the training rows. Large integers can lose precision during centering. For a training column containing 2**53 and 2**53 + 1, both samples receive a standardized value of 0.0.

Euclidean distance uses math.hypot so that squaring very large or very small coordinate differences does not distort the ranking. A distance beyond the floating-point range ranks as infinity. Samples with such distances follow the same tie rule.

API

toyml.classification.knn.KNN dataclass

KNN(k: int, std_transform: bool = True, *, distance_metric: Literal['euclidean'] = 'euclidean')

K-Nearest Neighbors classification algorithm implementation.

This class implements the K-Nearest Neighbors algorithm for classification tasks. Each fit validates the current hyperparameters against the training data. After changing a hyperparameter, call fit again before using predict.

Examples:

>>> from toyml.classification import KNN
>>> dataset = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]]
>>> labels = ["A", "A", "B", "B"]
>>> knn = KNN(k=3, std_transform=True).fit(dataset, labels)
>>> knn.predict([2.5, 3.5])
'A'
References
  1. Li Hang
  2. Tan
  3. Zhou Zhihua
  4. Murphy
  5. Harrington

k instance-attribute

k: int

Number of neighbors in the vote, from one to the training sample count.

std_transform class-attribute instance-attribute

std_transform: bool = True

Whether to standardize features using training means and population standard deviations (ddof=0).

distance_metric class-attribute instance-attribute

distance_metric: Literal['euclidean'] = field(default='euclidean', kw_only=True)

Distance used to rank neighbors. Currently supports "euclidean".

dataset_ class-attribute instance-attribute

dataset_: list[list[float]] | None = field(default=None, init=False)

Training samples in the feature space used for neighbor searches.

labels_ class-attribute instance-attribute

labels_: list[Any] | None = field(default=None, init=False)

Training labels in the same order as the samples.

standardizer_ class-attribute instance-attribute

standardizer_: Standardizer | None = field(default=None, init=False)

Standardizer fitted to the training data when standardization is enabled.

fit

fit(dataset: list[list[float]], labels: list[Any]) -> KNN

Store the labeled samples. A failed refit preserves the previous fitted attributes.

PARAMETER DESCRIPTION
dataset

At least k rows of finite numeric features, all of the same positive width.

TYPE: list[list[float]]

labels

One hashable class label per row, in training order.

TYPE: list[Any]

RETURNS DESCRIPTION
KNN

The fitted instance (self).

RAISES DESCRIPTION
ValueError

If the neighbor count, distance metric, samples, or labels are invalid, or standardization exceeds the floating-point range.

TypeError

If std_transform is not a boolean.

Source code in src/toyml/classification/knn.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def fit(self, dataset: list[list[float]], labels: list[Any]) -> KNN:
    """Store the labeled samples. A failed refit preserves the previous fitted attributes.

    Args:
        dataset: At least `k` rows of finite numeric features, all of the
            same positive width.
        labels: One hashable class label per row, in training order.

    Returns:
        The fitted instance (`self`).

    Raises:
        ValueError: If the neighbor count, distance metric, samples, or labels are
            invalid, or standardization exceeds the floating-point range.
        TypeError: If `std_transform` is not a boolean.
    """
    n_samples = len(dataset)
    self._validate_hyperparameters(n_samples)
    self._validate_labels(labels, n_samples)

    if self.std_transform:
        standardizer = Standardizer()
        # fit_transform validates the features before computing their training statistics.
        samples = standardizer.fit_transform(dataset)
    else:
        standardizer = None
        self._validate_samples(dataset)
        samples = [point.copy() for point in dataset]
    # Publish the rows, labels and scaler together so a failed refit preserves the previous model.
    self.dataset_, self.labels_, self.standardizer_ = samples, labels.copy(), standardizer
    return self

predict

predict(x: list[float]) -> Any

Classify a single sample by majority vote among its nearest neighbors.

PARAMETER DESCRIPTION
x

Finite numeric features in training order, with the same width as a training row.

TYPE: list[float]

RETURNS DESCRIPTION
Any

The most frequent label among the nearest k samples. Samples whose

Any

distances round to the same float retain training order. Tied votes

Any

favor the label encountered first among the selected neighbors, from

Any

nearest to farthest.

RAISES DESCRIPTION
ValueError

If the model is unfitted or the query has invalid features or cannot be standardized.

Source code in src/toyml/classification/knn.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def predict(self, x: list[float]) -> Any:  # noqa: ANN401
    """Classify a single sample by majority vote among its nearest neighbors.

    Args:
        x: Finite numeric features in training order, with the same width as a training row.

    Returns:
        The most frequent label among the nearest `k` samples. Samples whose
        distances round to the same float retain training order. Tied votes
        favor the label encountered first among the selected neighbors, from
        nearest to farthest.

    Raises:
        ValueError: If the model is unfitted or the query has invalid features
            or cannot be standardized.
    """
    if self.dataset_ is None or self.labels_ is None:
        msg = "The model is not fitted yet!"
        raise ValueError(msg)
    if self.standardizer_ is not None:
        x = self.standardizer_.transform([x])[0]
    else:
        self._validate_point(x, len(self.dataset_[0]))
    nearest = self._nearest_labels(x, self.dataset_, self.labels_)
    # Counter resolves tied counts by first occurrence in nearest-neighbor order.
    return Counter(nearest).most_common(1)[0][0]

toyml.classification.knn.Standardizer dataclass

Standardizer()

A class for standardizing numerical datasets.

Provides methods to fit a standardization model to a dataset, transform datasets using the fitted model, and perform both operations in a single step. Uses population standard deviations (ddof=0), with unit scale for constant features.

fit

fit(dataset: list[list[float]]) -> Standardizer

Fit the standardization model to the given dataset.

PARAMETER DESCRIPTION
dataset

The input dataset to fit the model to.

TYPE: list[list[float]]

RETURNS DESCRIPTION
Standardizer

The fitted Standardizer instance.

RAISES DESCRIPTION
ValueError

If features are empty, inconsistent, or non-finite.

Source code in src/toyml/classification/knn.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def fit(self, dataset: list[list[float]]) -> Standardizer:
    """Fit the standardization model to the given dataset.

    Args:
        dataset: The input dataset to fit the model to.

    Returns:
        The fitted Standardizer instance.

    Raises:
        ValueError: If features are empty, inconsistent, or non-finite.
    """
    self._validate_dataset(dataset)
    self._column_stats = [self._fit_column(column) for column in zip(*dataset, strict=True)]
    return self

transform

transform(dataset: list[list[float]]) -> list[list[float]]

Transform the given dataset using the fitted standardization model.

PARAMETER DESCRIPTION
dataset

The input dataset to transform.

TYPE: list[list[float]]

RETURNS DESCRIPTION
list[list[float]]

New standardized rows; the input dataset is unchanged.

RAISES DESCRIPTION
ValueError

If unfitted or given invalid or unrepresentable feature values.

Source code in src/toyml/classification/knn.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def transform(self, dataset: list[list[float]]) -> list[list[float]]:
    """Transform the given dataset using the fitted standardization model.

    Args:
        dataset: The input dataset to transform.

    Returns:
        New standardized rows; the input dataset is unchanged.

    Raises:
        ValueError: If unfitted or given invalid or unrepresentable feature values.
    """
    if not self._column_stats:
        msg = "The model is not fitted yet!"
        raise ValueError(msg)
    self._validate_dataset(dataset, len(self._column_stats))
    return self._transform(dataset)

fit_transform

fit_transform(dataset: list[list[float]]) -> list[list[float]]

Fit the column statistics, then use them to standardize the training rows.

PARAMETER DESCRIPTION
dataset

The input dataset to fit and transform.

TYPE: list[list[float]]

RETURNS DESCRIPTION
list[list[float]]

New standardized rows; the input dataset is unchanged.

RAISES DESCRIPTION
ValueError

If features are invalid or cannot be standardized.

Source code in src/toyml/classification/knn.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def fit_transform(self, dataset: list[list[float]]) -> list[list[float]]:
    """Fit the column statistics, then use them to standardize the training rows.

    Args:
        dataset: The input dataset to fit and transform.

    Returns:
        New standardized rows; the input dataset is unchanged.

    Raises:
        ValueError: If features are invalid or cannot be standardized.
    """
    self.fit(dataset)
    return self._transform(dataset)