前言
此程序基于手寫體數碼圖像識別實驗
支持向量機(svm)模型實現分類任務。
本程序可以流暢運行于Python3.6環境,但是Python2.x版本需要修正的地方也已經在注釋中說明。
requirements:pandas,numpy,scikit-learn
想查看其他經典算法實現可以關注查看本人其他文集。
實驗結果分析
由于精妙的模型假設,使得我們可以在海量甚至高維度的數據中,篩選對預測任務最為有效的少量訓練樣本,這樣做不僅節省了模型選擇學習所需要的數據內存,同事也提高了模型的預測性能。然而,要獲得如此的有事就必然要付出更多的計算代價(CPU資源和計算時間)
程序源碼
#import handwirtten digits loader from sklearn.datasets
from sklearn.datasets import load_digits
#load digits data
digits=load_digits()
#check the scale and features dimensions of data
#print(digits.data.shape)
#data preprocessing
#notes:you should use cross_valiation instead of model_valiation in python 2.7
#from sklearn.cross_validation import train_test_split #DeprecationWarning
from sklearn.model_selection import train_test_split #use train_test_split module of sklearn.model_valiation to split data
#take 25 percent of data randomly for testing,and others for training
X_train,X_test,y_train,y_test = train_test_split(digits.data,digits.target,test_size=0.25,random_state=33)
#check the scale of training set and test set respectively
#print(y_train.shape)
#print(y_test.shape)
#import data standardizition module from sklearn.preprocession
from sklearn.preprocessing import StandardScaler
#import svm classifier LinearSVC which based on linear hypothesis
from sklearn.svm import LinearSVC
#standardizing data
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
#initializing LinearSVC
lsvc = LinearSVC()
#traing svm classifier
lsvc.fit(X_train,y_train)
#predicting? digits and saving results in variable y_predict
y_predict=lsvc.predict(X_test)
#get accuracy by the score function in lsvc model
print('The accuracy of Linear SVC is',lsvc.score(X_test,y_test))
from sklearn.metrics import classification_report
#get? precision ,recall and f1-score from classification_report module
print(classification_report(y_test,y_predict,target_names=digits.target_names.astype(str)))
Ubuntu16.04 Python3.6 程序輸出結果:
The accuracy of Linear SVC is 0.9533333333333334
? ? ? ? ? ? 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
[Finished in 0.6s]
歡迎指正錯誤,包括英語和程序錯誤。有問題也歡迎提問,一起加油一起進步。
本程序完全是本人逐字符輸入的勞動結果,轉載請注明出處。