機器學習之路: python 支持向量機 LinearSVC 手寫字體識別

 

使用python3 學習sklearn中支持向量機api的使用python

能夠來到個人git下載源代碼:https://github.com/linyi0604/MachineLearninggit

 

 1 # 導入手寫字體加載器
 2 from sklearn.datasets import load_digits  3 from sklearn.cross_validation import train_test_split  4 from sklearn.preprocessing import StandardScaler  5 from sklearn.svm import LinearSVC  6 from sklearn.metrics import classification_report  7 
 8 '''
 9 支持向量機 10 根據訓練樣本的分佈,搜索全部可能的線性分類器最佳的一個。 11 從高緯度的數據中篩選最有效的少許訓練樣本。 12 節省數據內存,提升預測性能 13 可是付出更多的cpu和計算時間 14 '''
15 
16 '''
17 1 獲取數據 18 '''
19 # 經過數據加載器得到手寫字體數字的數碼圖像數據並存儲在digits變量中
20 digits = load_digits() 21 # 查看數據的特徵維度和規模
22 # print(digits.data.shape) # (1797, 64)
23 
24 '''
25 2 分割訓練集合和測試集合 26 '''
27 x_train, x_test, y_train, y_test = train_test_split(digits.data, 28  digits.target, 29                                                     test_size=0.25, 30                                                     random_state=33) 31 
32 '''
33 3 使用支持向量機分類模型對數字圖像進行識別 34 '''
35 # 對訓練數據和測試數據進行標準化
36 ss = StandardScaler() 37 x_train = ss.fit_transform(x_train) 38 x_test = ss.fit_transform(x_test) 39 
40 # 初始化線性假設的支持向量機分類器
41 lsvc = LinearSVC() 42 # 進行訓練
43 lsvc.fit(x_train, y_train) 44 # 利用訓練好的模型對測試集合進行預測 測試結果存儲在y_predict中
45 y_predict = lsvc.predict(x_test) 46 
47 '''
48 4 支持向量機分類器 模型能力評估 49 '''
50 print("準確率:", lsvc.score(x_test, y_test)) 51 print("其餘評估數據:\n", classification_report(y_test, y_predict, target_names=digits.target_names.astype(str))) 52 '''
53 準確率: 0.9488888888888889 54 其餘評估數據: 精確率 召回率 f1指標 數據個數 55  precision recall f1-score support 56 
57  0 0.92 0.97 0.94 35 58  1 0.95 0.98 0.96 54 59  2 0.98 1.00 0.99 44 60  3 0.93 0.93 0.93 46 61  4 0.97 1.00 0.99 35 62  5 0.94 0.94 0.94 48 63  6 0.96 0.98 0.97 51 64  7 0.90 1.00 0.95 35 65  8 0.98 0.83 0.90 58 66  9 0.95 0.91 0.93 44 67 
68 avg / total 0.95 0.95 0.95 450 69 '''
相關文章
相關標籤/搜索