機器學習實戰(8)—— 支持向量機代碼實現

郵政系統每天都會收到大量的信件,最爲要緊的一環是要根據信件上的收信人郵編進行識別和分類,以便確定信件的投送地。

原本這項任務是依靠大量的人工來進行,後來人們嘗試讓計算機來代替人工。然而,因爲多數的郵編都是手寫的數字,並且樣式各異,所以沒有統一編制的規則可以用於很好的識別和分類。

機器學習興起之後,大量研究表明 svm 可以在手寫體數字圖片的分類任務上展現出很好的性能。

首先,導入手寫字體:

# 從sklearn.datasets裏導入手寫體數字加載器。
from sklearn.datasets import load_digits
# 從通過數據加載器獲得手寫體數字的數碼圖像數據並儲存在digits變量中。
digits = load_digits()

可以看一下數據:

digits

數據如下,是 2 維向量形式,表示手寫數字:

{'DESCR'"Optical Recognition of Handwritten Digits Data Set\n===================================================\n\nNotes\n-----\nData Set Characteristics:\n    :Number of Instances: 5620\n    :Number of Attributes: 64\n    :Attribute Information: 8x8 image of integer pixels in the range 0..16.\n    :Missing Attribute Values: None\n    :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)\n    :Date: July; 1998\n\nThis is a copy of the test set of the UCI ML hand-written digits datasets\nhttp://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits\n\nThe data set contains images of hand-written digits: 10 classes where\neach class refers to a digit.\n\nPreprocessing programs made available by NIST were used to extract\nnormalized bitmaps of handwritten digits from a preprinted form. From a\ntotal of 43 people, 30 contributed to the training set and different 13\nto the test set. 32x32 bitmaps are divided into nonoverlapping blocks of\n4x4 and the number of on pixels are counted in each block. This generates\nan input matrix of 8x8 where each element is an integer in the range\n0..16. This reduces dimensionality and gives invariance to small\ndistortions.\n\nFor info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.\nT. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.\nL. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,\n1994.\n\nReferences\n----------\n  - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their\n    Applications to Handwritten Digit Recognition, MSc Thesis, Institute of\n    Graduate Studies in Science and Engineering, Bogazici University.\n  - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.\n  - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.\n    Linear dimensionalityreduction using relevance weighted LDA. School of\n    Electrical and Electronic Engineering Nanyang Technological University.\n    2005.\n  - Claudio Gentile. A New Approximate Maximal Margin Classification\n    Algorithm. NIPS. 2000.\n",
 'data': array([[ 0.,  0.,  5., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ..., 10.,  0.,  0.],
        [ 0.,  0.,  0., ..., 16.,  9.,  0.],
        ...,
        [ 0.,  0.,  1., ...,  6.,  0.,  0.],
        [ 0.,  0.,  2., ..., 12.,  0.,  0.],
        [ 0.,  0., 10., ..., 12.,  1.,  0.]]),
 'images': array([[[ 0.,  0.,  5., ...,  1.,  0.,  0.],
         [ 0.,  0., 13., ..., 15.,  5.,  0.],
         [ 0.,  3., 15., ..., 11.,  8.,  0.],
         ...,
         [ 0.,  4., 11., ..., 12.,  7.,  0.],
         [ 0.,  2., 14., ..., 12.,  0.,  0.],
         [ 0.,  0.,  6., ...,  0.,  0.,  0.]],

        [[ 0.,  0.,  0., ...,  5.,  0.,  0.],
         [ 0.,  0.,  0., ...,  9.,  0.,  0.],
         [ 0.,  0.,  3., ...,  6.,  0.,  0.],
         ...,
         [ 0.,  0.,  1., ...,  6.,  0.,  0.],
         [ 0.,  0.,  1., ...,  6.,  0.,  0.],
         [ 0.,  0.,  0., ..., 10.,  0.,  0.]],

        [[ 0.,  0.,  0., ..., 12.,  0.,  0.],
         [ 0.,  0.,  3., ..., 14.,  0.,  0.],
         [ 0.,  0.,  8., ..., 16.,  0.,  0.],
         ...,
         [ 0.,  9., 16., ...,  0.,  0.,  0.],
         [ 0.,  3., 13., ..., 11.,  5.,  0.],
         [ 0.,  0.,  0., ..., 16.,  9.,  0.]],

        ...,

        [[ 0.,  0.,  1., ...,  1.,  0.,  0.],
         [ 0.,  0., 13., ...,  2.,  1.,  0.],
         [ 0.,  0., 16., ..., 16.,  5.,  0.],
         ...,
         [ 0.,  0., 16., ..., 15.,  0.,  0.],
         [ 0.,  0., 15., ..., 16.,  0.,  0.],
         [ 0.,  0.,  2., ...,  6.,  0.,  0.]],

        [[ 0.,  0.,  2., ...,  0.,  0.,  0.],
         [ 0.,  0., 14., ..., 15.,  1.,  0.],
         [ 0.,  4., 16., ..., 16.,  7.,  0.],
         ...,
         [ 0.,  0.,  0., ..., 16.,  2.,  0.],
         [ 0.,  0.,  4., ..., 16.,  2.,  0.],
         [ 0.,  0.,  5., ..., 12.,  0.,  0.]],

        [[ 0.,  0., 10., ...,  1.,  0.,  0.],
         [ 0.,  2., 16., ...,  1.,  0.,  0.],
         [ 0.,  0., 15., ..., 15.,  0.,  0.],
         ...,
         [ 0.,  4., 16., ..., 16.,  6.,  0.],
         [ 0.,  8., 16., ..., 16.,  8.,  0.],
         [ 0.,  1.,  8., ..., 12.,  1.,  0.]]]),
 'target': array([0, 1, 2, ..., 8, 9, 8]),
 'target_names': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}
# 檢視數據規模和特徵維度。
digits.data.shape

手寫數字的圖像數據共有 1797 條,每幅圖片是 8*8=64 的像素矩陣表示, 在模型使用這些像素矩陣時,我們習慣將 2D 的圖片像素矩陣逐行收尾拼接爲 1D 的像素特徵向量。

接下來切分訓練集和測試集:

# 從sklearn.cross_validation中導入train_test_split用於數據分割。
from sklearn.cross_validation import train_test_split

# 隨機選取75%的數據作爲訓練樣本;其餘25%的數據作爲測試樣本。
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=33)
y_train.shape

y_test.shape

接下來導入數據標準化模塊,並且導入 SVM 模型

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

# 從sklearn.svm裏導入基於線性假設的支持向量機分類器LinearSVC。
from sklearn.svm import LinearSVC

對數據進行標準化

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

使用 SVM 進行訓練和預測:

# 初始化線性假設的支持向量機分類器LinearSVC。
lsvc = LinearSVC()
#進行模型訓練
lsvc.fit(X_train, y_train)
# 利用訓練好的模型對測試樣本的數字類別進行預測,預測結果儲存在變量y_predict中。
y_predict = lsvc.predict(X_test)

輸出預測精度:

# 使用模型自帶的評估函數進行準確性測評。
print('The Accuracy of Linear SVC is', lsvc.score(X_test, y_test))

輸出更詳細的評估報告:

# 依然使用sklearn.metrics裏面的classification_report模塊對預測結果做更加詳細的分析。
from sklearn.metrics import classification_report
print(classification_report(y_test, y_predict, target_names=digits.target_names.astype(str)))#轉爲字符

以上就是 Python 實現 SVM 對手寫字體識別分類,你學會了麼?

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/IK3EAkp5YgHarpo9fNvSbg