K-Nearest Neighbors classifier implementation.
Classes
K-Nearest Neighbors classifier using instance-based lazy learning.
__init__( self, k: int = 1, distance_weighting: str = 'uniform', search_algorithm: str = 'brute', auto_select_k: bool = False, leaf_size: int = 30, )
Overview
The algorithm operates in the following steps:
-
Store all training instances during
fit()(no model is built). - For a new query point, compute the distance to every training instance
- Select the k closest training instances.
- Assign weights to the neighbors according to the chosen weighting scheme.
- Predict the class with the highest aggregated weight among the neighbors.
Theory
Given a query point x, the predicted class is:
- N_k(x): The set of k nearest neighbors of x
- w_i: Weight assigned to neighbor i
- C: The set of all classes
- Uniform: w_i = 1
- Inverse distance: w_i = 1 / d(x, x_i)
- Similarity: w_i = 1 / (1 + d(x, x_i))
Parameters
k
distance_weighting
How to weight neighbors:
- •
'uniform': All neighbors weighted equally. - •
'distance': Weight by inverse of distance :math:`1/d`. - •
'distance_squared': Weight by inverse squared distance :math:`1/d^2`. - •
'similarity': Weight by similarity :math:`1/(1+d)`.
search_algorithm
Algorithm for finding neighbors:
- •
'brute': Brute force search. - •
'kd_tree': KD-tree for faster search in low dimensions. - •
'ball_tree': Ball tree for higher-dimensional or non-Euclidean data.
auto_select_k
leaf_size
Attributes
X_train_
y_train_
classes_
fit.
search_
Notes
Complexity:
- Training: O(1) (instances are simply stored)
- Prediction (brute force): O(n \cdot m) per query where n = number of training samples, m = number of features
- Prediction (KD-tree, average case): O(m \cdot \log n) per query
- Space: O(n \cdot m) for storing all training instances
- Small to medium datasets where training time must be near-zero
- Decision boundaries are highly irregular or non-linear
- New training instances arrive incrementally (online learning)
- When an interpretable, non-parametric baseline is needed
- Low-dimensional feature spaces (especially with tree-based search)
References
See Also
Basic classification with distance-weighted voting:
>>> from tuiml.algorithms.neighbors import KNearestNeighborsClassifier
>>> from tuiml.datasets import load_iris
>>> X, y = load_iris()
>>> clf = KNearestNeighborsClassifier(k=3, distance_weighting='distance')
>>> clf.fit(X, y)
KNearestNeighborsClassifier(k=3, n_train=150, weighting='distance')
>>> clf.predict(X[:1])
array([0])
Methods
fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsClassifier'
fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsClassifier'
Fit the KNearestNeighborsClassifier classifier by storing the training data.
Parameters
X
y
Returns
self
partial_fit
(self, X: np.ndarray, y: np.ndarray, classes: Optional[np.ndarray]=None) -> 'KNearestNeighborsClassifier'
partial_fit
(self, X: np.ndarray, y: np.ndarray, classes: Optional[np.ndarray]=None) -> 'KNearestNeighborsClassifier'
Incrementally add training samples to the classifier.
Parameters
X
y
classes
Returns
self
update
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsClassifier'
update
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsClassifier'
Add new instances to the training set (online learning).
Parameters
X
y
Returns
self
K-Nearest Neighbors regressor using instance-based lazy learning.
__init__( self, k: int = 1, distance_weighting: str = 'uniform', search_algorithm: str = 'brute', auto_select_k: bool = False, leaf_size: int = 30, )
Overview
The algorithm operates in the following steps:
-
Store all training instances during
fit()(no model is built). - For a new query point, compute the distance to every training instance
- Select the k closest training instances.
- Assign weights to the neighbors according to the chosen weighting scheme.
- Predict the weighted average of the neighbor target values.
Theory
Given a query point x, the predicted value is:
- N_k(x) -- The set of k nearest neighbors of x
- w_i -- Weight assigned to neighbor i
- y_i -- Target value of neighbor i
- Uniform: w_i = 1
- Inverse distance: w_i = 1 / d(x, x_i)
- Similarity: w_i = 1 / (1 + d(x, x_i))
Parameters
k
distance_weighting
How to weight neighbors:
-
'uniform'- All neighbors weighted equally. -
'distance'- Weight by inverse of distance :math:`1/d`. -
'distance_squared'- Weight by inverse squared distance :math:`1/d^2`. -
'similarity'- Weight by similarity :math:`1/(1+d)`.
search_algorithm
Algorithm for finding neighbors:
-
'brute'- Brute force search. -
'kd_tree'- KD-tree for faster search in low dimensions. -
'ball_tree'- Ball tree for higher-dimensional data.
auto_select_k
leaf_size
Attributes
X_train_
y_train_
search_
Notes
Complexity:
- Training: O(1) (instances are simply stored)
- Prediction (brute force): O(n \cdot m) per query
- Prediction (KD-tree, average case): O(m \cdot \log n) per query
- Space: O(n \cdot m) for storing all training instances
- Small to medium datasets where training time must be near-zero
- Non-linear relationships between features and target
- When an interpretable, non-parametric baseline is needed
- Low-dimensional feature spaces (especially with tree-based search)
References
Basic regression with distance-weighted averaging:
>>> from tuiml.algorithms.neighbors import KNearestNeighborsRegressor
>>> import numpy as np
>>> X = np.array([[1], [2], [3], [4], [5]])
>>> y = np.array([1.0, 2.1, 2.9, 4.0, 5.1])
>>> reg = KNearestNeighborsRegressor(k=3, distance_weighting='distance')
>>> reg.fit(X, y)
KNearestNeighborsRegressor(k=3, n_train=5, weighting='distance')
>>> reg.predict(np.array([[2.5]]))
array([...])
Methods
fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
Fit the regressor by storing the training data.
Parameters
X
y
Returns
self
partial_fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
partial_fit
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
Incrementally add training samples to the regressor.
Parameters
X
y
Returns
self
update
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
update
(self, X: np.ndarray, y: np.ndarray) -> 'KNearestNeighborsRegressor'
Add new instances to the training set (online learning).
Parameters
X
y
Returns
self