2.1.13.2.KNN with Python
1. 匯入基本的library
pandas, numpy, matplotlib, seaborn
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns將圖表直接嵌入到Notebook之中
%matplotlib inline
2.讀取資料並了解資料
df = pd.read_csv('Classified Data', index_col = 0)
df.head()
3.標準化資料
變數的scale通常對結果有很大的影響, 當使用KNN classifier時通常會統一observation的尺度
使用StandardScaler
StandardScaler的作用是將數據減去平均值並除以方差, 公式為(X-mean)/std
將原始資料的TARGET CLASS drop掉後fit, 再transform
將標準化後的資料準轉成DataFrame
4.使用Skikit-learn library
首先介紹train_test_split, 這個函式可以隨機劃分訓練集和測試集
5.使用KNN classifier進行預測
設定n_neighbors(K)為1
6.評估模型的精度
使用classification_report

confusion_matrix

7.調整K值
重新預估k值
Last updated
Was this helpful?
