K Nearest Neighbors also known as KNN takes max vote of nearest neighbors and predicts it as output.

# Imports
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np

# Load Data
iris = load_iris()

# Create a dataframe
df = pd.DataFrame(iris.data, columns = iris.feature_names)
df['target'] = iris.target

# Let's see a sample of created df
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
130 7.4 2.8 6.1 1.9 2
74 6.4 2.9 4.3 1.3 1
# Let's see target names
targets = iris.target_names
['setosa' 'versicolor' 'virginica']
# Prepare training data for building the model
X_train = df.drop(['target'], axis=1)
y_train = df['target']

# Instantiate the model
cls = KNeighborsClassifier()

# Train/Fit the model 
cls.fit(X_train, y_train)

# Make prediction using the model
X_pred = [5.1, 3.2, 1.5, 0.5]
y_pred = cls.predict([X_pred])

print("Prediction is: {}".format(targets[y_pred]))
Prediction is: ['setosa']

That's how we Build K Nearest Neighbors classifier

That’s all for this mini tutorial. To sum it up, we learned how to Build K Nearest Neighbors classifier.

Hope it was easy, cool and simple to follow. Now it’s on you.

Leave a Reply

Your email address will not be published. Required fields are marked *