Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

K-Nearest Neighbors (KNN)

SHUBHAM CHAUDA
Python in Plain English
4 min readSep 19, 2023

--

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(x_axis, y_axis, test_size=0.33, random_state=42)
knn.fit(X_train,y_train)
pred = knn.predict(X_test)
from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,pred))
[[46  8]
[14 22]]
print(classification_report(y_test,pred))
                precision    recall  f1-score   support

0 0.77 0.85 0.81 54
1 0.73 0.61 0.67 36

accuracy 0.76 90
macro avg 0.75 0.73 0.74 90
weighted avg 0.75 0.76 0.75 90
accuracy_rate = []

It Will take some time
for i in the range (1,40):

knn = KNeighborsClassifier(n_neighbors=i)
score=cross_val_score(knn,x_axis,y_axis,cv=10)
accuracy_rate.append(score.mean())
error_rate = []

# Will take some time
for i in range(1,40):

knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train,y_train)
pred_i = knn.predict(X_test)
error_rate.append(np.mean(pred_i != y_test))
plt.figure(figsize=(10,6))
plt.plot(range(1,40), accuracy_rate, color='blue', linestyle='dashed', marker='o',
markerfacecolor='red', markersize=10)
plt.title('Error Rate vs. K Value')
plt.xlabel('K')
plt.ylabel('Error Rate')

In Plain English

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response