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
fitvalidatesk,std_transform, anddistance_metrictogether with the training data. After changing any of them, fit the same classifier again before callingpredict. The keyword-onlydistance_metriccurrently supports"euclidean"(the default). - Fit on at least
ksamples. 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. SelectFalseto 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 of1.0from the origin. Withk=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
- Li Hang
- Tan
- Zhou Zhihua
- Murphy
- 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
TYPE:
|
labels
|
One hashable class label per row, in training order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KNN
|
The fitted instance ( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the neighbor count, distance metric, samples, or labels are invalid, or standardization exceeds the floating-point range. |
TypeError
|
If |
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 | |
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
The most frequent label among the nearest |
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 | |
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:
|
| 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 | |
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:
|
| 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 | |
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:
|
| 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 | |