Building KNN with Sklearn

K-Nearest Neighbors is an algorithm for supervised learning. Where the data is 'trained' with data points corresponding to their classification. Once a point is to be predicted, it takes into account the 'K' nearest points to it to determine it's classificationThe k-nearest neighbors (KNN) algorithm is a non-parametric machine learning algorithm that can be used for both classification and regression tasks. It works by finding the k most similar instances in the training set to a new instance and then predicting the label of the new instance based on the labels of the k nearest neighbors.In scikit-learn, the KNeighborsClassifier class implements the k-nearest neighbors algorithm for classification tasks. The following code shows how to build a KNN classifier with 5 neighbors:

The n_neighbors parameter specifies the number of neighbors to use for the prediction. The default value is 5.

Other parameters that can be tuned for the KNN classifier include:

  • metric: The distance metric to use for calculating the distance between neighbors. The default metric is the Euclidean distance.
  • weights: The weight function to use for the prediction. The default weight function is uniform, which means that all neighbors are weighted equally.
  • algorithm: The algorithm to use for finding the nearest neighbors. The default algorithm is brute-force search.

You can experiment with different values for these parameters to find the best model for your data.

Here is an example of how to use the KNeighborsClassifier class to classify the Iris dataset:

Dataset

# read in the iris data
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris() # create X (features) and y (response) X = iris.data y = iris.target

X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25)


KNN (K=5)

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train) y_pred = knn.predict(X_test) accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)

 

Last modified: Tuesday, 12 September 2023, 12:09 PM