Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

k-Nearest Neighbors (kNN)

Intuition

Practice

Import the required libraries, including numpy, pandas and plotly. We also use train_test_split from sklearn.model_selection to split the dataset into training and testing sets.

Loading...
Loading...

Dataset

First, we load the dataset and display the first few rows of the dataset.

There are 150 samples, each with 4 features as ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Targets are ['setosa' 'versicolor' 'virginica']

In this example, we are going to use the last two features of the iris dataset to illustrate the kNN algorithm.

Plotting the dataset with pairs of features

Since we have 4 features, there are 6 possible pairs of features. Let’s plot them all.

Source
Loading...
Loading...

From the visualizations, we observe that the last two features (Petal Width and Petal Length) are the most promising to use in the kNN algorithm since they are the most separable.

Next, we split the dataset into a training set and a test set with 20 samples for the test set, and the rest for the training set.

Now, we create a kNN classifier using euclidean distance as the distance metric with k=3. The classifier is trained using the training set and then used to predict the test set.

Finally, the classifier is evaluated using the accuracy score and the confusion matrix.

Accuracy: 80.00%
Source
Loading...
Loading...

The confusion matrix indicates that the kNN algorithm with k=3 and euclidean distance has 80% accuracy on the test set. The setosa class is perfectly classified with a precision of 100%, while the versicolor and virginica classes are sometimes confused with each other.

Besides, we can plot the decision boundary of the kNN classifier in a heatmap.

Source
Loading...
Loading...

From the heatmap, the setosa class (red color) is the most separable from the other two classes. The decision boundary is clear and the kNN algorithm should be able to classify the setosa class with high accuracy.

The versicolor and virginica classes are not as separable as the setosa class. In the middle of the plot, there is a region where the two classes overlap. The kNN algorithm may not be able to classify these two classes with high accuracy.

kNN classifier with different k values

Loading...
Loading...

From the line graph, using euclidean distance with k = 10 gets the highest accuracy score of 90% on the test set, while using k = {4, 15, 16, 17} obtains the lowest accuracy score of 75%.

For the manhattan distance, using k = 3 achieves highest accuracy score of 90%. But at k = 6, the accuracy score is the lowest at 70%.

Using kNN Classifier from sklearn

The default kNN classifier from sklearn uses k = 5 and euclidean distance.

Loading...
Loading...