fork download
  1. import numpy as np
  2. import pandas as pd
  3.  
  4. import matplotlib.pyplot as plt
  5. from sklearn.metrics import accuracy_score
  6. from sklearn.datasets import make_blobs
  7. from sklearn.neighbors import KNeighborsClassifier
  8. from sklearn.model_selection import train_test_split
  9. X, y = make_blobs(n_samples = 500, n_features = 2, centers = 4,cluster_std = 1.5, random_state = 4)
  10.  
  11. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)
  12. knn5 = KNeighborsClassifier(n_neighbors = 5)
  13. knn1 = KNeighborsClassifier(n_neighbors=1)
  14. knn5.fit(X_train, y_train)
  15. knn1.fit(X_train, y_train)
  16.  
  17. y_pred_5 = knn5.predict(X_test)
  18. y_pred_1 = knn1.predict(X_test)
  19.  
  20. print("Accuracy with k=5", accuracy_score(y_test, y_pred_5)*100)
  21. print("Accuracy with k=1", accuracy_score(y_test, y_pred_1)*100)
  22. plt.style.use('seaborn')
  23. plt.figure(figsize = (10,10))
  24. plt.scatter(X[:,0], X[:,1], c=y, marker= '*',s=100,edgecolors='black')
  25. plt.show()
Success #stdin #stdout 3.7s 129184KB
stdin
Standard input is empty
stdout
Accuracy with k=5 93.60000000000001
Accuracy with k=1 90.4