【機器學習】【監督學習】【算法01-實例02】K近鄰(k-nearest neighbor)-鳶尾花

鳶尾花的分類實例是一個非常經典的例子。也是sklearn中一個非常經典的數據集合。我們首先從數據集的結構特點來開始。

1.數據集的加載

# 從sklearn.datasets 導入 iris數據加載器。
from sklearn.datasets import load_iris
# 使用加載器讀取數據並且存入變量iris。
iris = load_iris()
# 查驗數據規模。
#如果想要在pycharm這類的編輯器裏面顯示,加上print函數即可
iris.data.shape

2.數據集的描述

#注意此處可能python3以上的版本需要添加print()
print iris.DESCR

簡單說明:這個數據集一共有150個樣本,分成三類。四個特徵:
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
單位均統一爲cm,

Data Set Characteristics:
:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information:
    - sepal length in cm
    - sepal width in cm
    - petal length in cm
    - petal width in cm
    - class:
            - Iris-Setosa
            - Iris-Versicolour
            - Iris-Virginica
:Summary Statistics:

============== ==== ==== ======= ===== ====================
                Min  Max   Mean    SD   Class Correlation
============== ==== ==== ======= ===== ====================
sepal length:   4.3  7.9   5.84   0.83    0.7826
sepal width:    2.0  4.4   3.05   0.43   -0.4194
petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)
============== ==== ==== ======= ===== ====================

:Missing Attribute Values: None
:Class Distribution: 33.3% for each of 3 classes.
:Creator: R.A. Fisher
:Donor: Michael Marshall (MARSHALL%[email protected])
:Date: July, 1988

3.數據集分割

獲得了數據,就可以開始我們的”機器學習“了~
首先,按照老樣子,我們先對數據集進行切割。
按照3:1的比例來切割訓練集以及測試集,當然也可以加入驗證集,但是由於我們數量較少,就沒有再設立驗證集了。

# 從sklearn.cross_validation裏選擇導入train_test_split用於數據分割。
from sklearn.cross_validation import train_test_split
# 從使用train_test_split,利用隨機種子random_state採樣25%的數據作爲測試集。
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25, random_state=33)

4.使用KNN對數據進行訓練

# 從sklearn.preprocessing裏選擇導入數據標準化模塊。
from sklearn.preprocessing import StandardScaler

# 從sklearn.neighbors裏選擇導入KNeighborsClassifier,即K近鄰分類器。
from sklearn.neighbors import KNeighborsClassifier

# 對訓練和測試的特徵數據進行標準化。
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)

# 使用K近鄰分類器對測試數據進行類別預測,預測結果儲存在變量y_predict中。
knc = KNeighborsClassifier()
knc.fit(X_train, y_train)
y_predict = knc.predict(X_test)

由於我們這裏做的是對於算法的應用實例,就沒有再自己去實現KNN算法來對數據進行訓練了。我非常推薦大家按照算法的描述自己實現每一個機器學習算法,但是在實際的開發中或者使用中,我們一般都使用成熟的封裝好的package
如需要請移步到本人的博客:

K近鄰(k-nearest neighbor)實現細節


5.性能評測

這裏我們常用常使用的準確率,召回率,精確率,以及F1指標來判定。

  • 首先可以直接用模型自帶的knc.score來看看準確率
# 使用模型自帶的評估函數進行準確性測評。
print 'The accuracy of K-Nearest Neighbor Classifier is', knc.score(X_test, y_test)

打印的結果:

The accuracy of K-Nearest Neighbor Classifier is 0.894736842105
  • 然後用更加詳細的分析模型代碼
#使用classification_report模塊對預測結果做更加詳細的分析。
from sklearn.metrics import classification_report
print classification_report(y_test, y_predict, target_names=iris.target_names)

輸出結果:

               precision    recall   f1-score   support

     setosa       1.00      1.00      1.00         8
 versicolor       0.73      1.00      0.85        11
  virginica       1.00      0.79      0.88        19

avg / total       0.92      0.89      0.90        38

#說明:平均準確率 0.92,召回率0.89,F1指標0.9


6.總結

雖然整個過程很簡單,但是我們需要明白的理解的點很多,包括數據集的獲取,分割,以及對於相應算法的使用。雖然我們在代碼的實現中,隱藏了很多原理性的東西。這有助於我們的快速開發,但是我認爲任何一名機器學習或者數據科學從業者,若是從事技術相關的工作和研究,對於原理的掌握還是必不可少的。

希望每個能夠看到博文的有緣人都自己嘗試去做一些這樣的實現。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章