This example shows how to use KNeighborsClassifier.
We train such a classifier on the iris dataset and observe the difference of the
decision boundary obtained with regards to the parameter weights.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Load the data
In this example, we use the iris dataset. We split the data into a train and test
dataset.
We want to use a k-nearest neighbors classifier considering a neighborhood of 11 data
points. Since our k-nearest neighbors model uses euclidean distance to find the
nearest neighbors, it is therefore important to scale the data beforehand. Refer to
the example entitled
Importance of Feature Scaling for more
detailed information.
Thus, we use a Pipeline to chain a scaler before to use
our classifier.
Now, we fit two classifiers with different values of the parameter
weights. We plot the decision boundary of each classifier as well as the original
dataset to observe the difference.
We observe that the parameter weights has an impact on the decision boundary. When
weights="uniform" all nearest neighbors will have the same impact on the decision.
Whereas when weights="distance" the weight given to each neighbor is proportional
to the inverse of the distance from that neighbor to the query point.
In some cases, taking the distance into account might improve the model.
Total running time of the script: (0 minutes 0.229 seconds)