A user is giving first steps with R and now he is testing the KNN classification method (package class), but he is struggling to put it to work. He has two DocumentTermMatrix, one for train and another for test.

887    Asked by GayatriJaiteley in Data Science , Asked on Dec 20, 2019
Answered by Gayatri Jaiteley

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