Explain KNN along with a case study in Python

884    Asked by LynettaWillett in Data Science , Asked on Dec 17, 2019
Answered by Lynetta Willett

Initially we import the libraries

# Importing Libraries

import pandas as pd

import numpy as np

Now we read the dataset

glass = pd.read_csv("glass.csv")

We will split the dataset for training and testing

# Training and Test data using

from sklearn.model_selection import train_test_split

train,test = train_test_split(glass,test_size = 0.2)

Now we will fit the model


# KNN using sklearn

# Importing Knn algorithm from sklearn.neighbors

from sklearn.neighbors import KNeighborsClassifier as KNC


# for 3 nearest neighbours

neigh = KNC(n_neighbors= 3)


# Fitting with training data

neigh.fit(train.iloc[:,0:9],train.iloc[:,9])


Now we predict the model

# train accuracy

train_acc = np.mean(neigh.predict(train.iloc[:,0:9])==train.iloc[:,9])


# test accuracy

test_acc = np.mean(neigh.predict(test.iloc[:,0:9])==test.iloc[:,9])



Your Answer

Interviews

Parent Categories