How to create a function to create K values with train and test accuracy in Python

994    Asked by LaunaKirchner in Data Science , Asked on Dec 17, 2019
Answered by Nitin Solanki

Let us create an empty list which will contain the training and testing accuracy and the respective k values. The following code will generate the k values along with the training and testing accuracy.

# creating empty list variable

acc = []

# running KNN algorithm for 3 to 50 nearest neighbours(odd numbers) and

# storing the accuracy values

for i in range(3,50,2):

    neigh = KNC(n_neighbors=i)

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

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

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

    acc.append([train_acc,test_acc])



Your Answer

Interviews

Parent Categories