1. 程式人生 > >08 支持向量機(SVM)

08 支持向量機(SVM)

cto 分類 acc ros rom 圖像識別 total 使用 inter

支持向量機分類器(Support Vector Classifer),根據訓練樣本的分布,搜索所有可能的線性分類器中最佳的那個。 使用支持向量機分類器處理Scikit-learn內部繼承的手寫體數字圖片數據集。
#coding=UTF-8

######手寫體數據讀取代碼樣例

#從sklearn.datasets裏導入手寫體數字加載器
from sklearn.datasets import load_digits
#通過數據加載器獲得手寫體數字的數碼圖像數據,並儲存在digits變量中
digits=load_digits()
#檢視數據規模和特征維度
digits.data
.shape #[out]:(1797L, 64L) #輸出結果表明:該手寫體數字的數碼圖像數據共有1797條 #並且每幅圖片是由8x8=64的像素矩陣表示 #依照慣例,對於沒有直接提供測試樣本的數據 #要通過數據分割獲取75%的訓練樣本和25%的測試樣本 ######手寫體數據分割代碼樣例 #從sklearn.cross_validation中導入train_test_split用於數據分割 #若:from sklearn.cross_validation import train_test_split #會:DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
# "This module will be removed in 0.20.", DeprecationWarning) #所以:sklearn.cross_validation報警告,將其改為sklearn.model_selection from sklearn.model_selection 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) #分別檢視訓練與測試數據規模 print y_train.shape #[out]:(1347L,) print y_test.shape #[out]:(450L,) ######使用支持向量機(分類)對手寫體數字圖像進行識別 #從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) #初始化線性假設的支持向量機分類器LinearSVC lsvc=LinearSVC() #進行模型訓練 lsvc.fit(X_train,y_train) #利用訓練好的模型對測試樣本的數字類別進行預測,預測結果儲存在變量y_predict中 y_predict=lsvc.predict(X_test) ######性能評測:使用準確率、召回率、精確率和F1指標,對SVM分類模型從事手寫體數字圖像識別任務進行性能評估 #支持向量機(分類)模型對手寫體數字圖像識別能力的評估 #使用模型自帶的評估函數進行準確性評測 print ‘The Accuracy of Linear SVC is‘,lsvc.score(X_test,y_test) #[out]:The Accuracy of Linear SVC is 0.953333333333 #使用sklearn.metrics裏面的classification_report模塊對預測結果做更詳細的分析 from sklearn.metrics import classification_report print classification_report(y_test,y_predict,target_names=digits.target_names.astype(str)) #[out]: # precision recall f1-score support # 0 0.92 1.00 0.96 35 # 1 0.96 0.98 0.97 54 # 2 0.98 1.00 0.99 44 # 3 0.93 0.93 0.93 46 # 4 0.97 1.00 0.99 35 # 5 0.94 0.94 0.94 48 # 6 0.96 0.98 0.97 51 # 7 0.92 1.00 0.96 35 # 8 0.98 0.84 0.91 58 # 9 0.95 0.91 0.93 44 # avg / total 0.95 0.95 0.95 450

08 支持向量機(SVM)