2.1.13.2.KNN with Python

1. 匯入基本的library

2.讀取資料並了解資料

df = pd.read_csv('Classified Data', index_col = 0)
df.head()

3.標準化資料

  • 變數的scale通常對結果有很大的影響, 當使用KNN classifier時通常會統一observation的尺度

  • 使用StandardScaler

  • 將標準化後的資料準轉成DataFrame

4.使用Skikit-learn library

  • 首先介紹train_test_split, 這個函式可以隨機劃分訓練集和測試集

5.使用KNN classifier進行預測

  • 設定n_neighbors(K)為1

6.評估模型的精度

  • 使用classification_report

  • confusion_matrix

7.調整K值

Last updated