How to Create a K Nearest Neighbors Classifier in Sklearn

03.06.2021

Intro

A K Nearest Neighbors Classifier will use a variety of distance measurements to create groups or clusters of your data. Using these clusters, the model will be able to classify new data into the same groups. In this article, we will learn how to build a KNN Classifier in Sklearn.

Creating a KNN Classifier

To build a KNN classifier, we use the KNeighborsClassifier class from the neighbors module. We create an instance of this class and specify the number of neighbors. The number of nieghbors can usually be found by training different models and comparing scroes. Once done, we can fit the data and use the model as any other sklearn model.

from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target

standardizer = StandardScaler()
x_standard = standardizer.fit_transform(X)

knn = KNeighborsClassifier(n_neighbors = 5)
model = knn.fit(x_standard, y)

print(model.score())