python svm實(shí)現(xiàn)手寫數(shù)字識(shí)別——直接可用
最近在做個(gè)圍棋識(shí)別的項(xiàng)目,需要識(shí)別下面的數(shù)字,如下圖:
我發(fā)現(xiàn)現(xiàn)在網(wǎng)上很多代碼是良莠不齊,…真是一言難盡,于是記錄一下,能夠運(yùn)行成功并識(shí)別成功的一個(gè)源碼。
1、訓(xùn)練
1.1、訓(xùn)練數(shù)據(jù)集下載——已轉(zhuǎn)化成csv文件
1.2 、訓(xùn)練源碼
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import pandas as pd from sklearn.decomposition import pca from sklearn import svm from sklearn.externals import joblib import time if __name__ = = "__main__" : train_num = 5000 test_num = 7000 data = pd.read_csv( 'train.csv' ) train_data = data.values[ 0 :train_num, 1 :] train_label = data.values[ 0 :train_num, 0 ] test_data = data.values[train_num:test_num, 1 :] test_label = data.values[train_num:test_num, 0 ] t = time.time() #pca降維 pca = pca(n_components = 0.8 , whiten = true) print ( 'start pca...' ) train_x = pca.fit_transform(train_data) test_x = pca.transform(test_data) print (train_x.shape) # svm訓(xùn)練 print ( 'start svc...' ) svc = svm.svc(kernel = 'rbf' , c = 10 ) svc.fit(train_x,train_label) pre = svc.predict(test_x) #保存模型 joblib.dump(svc, 'model.m' ) joblib.dump(pca, 'pca.m' ) # 計(jì)算準(zhǔn)確率 score = svc.score(test_x, test_label) print (u '準(zhǔn)確率:%f,花費(fèi)時(shí)間:%.2fs' % (score, time.time() - t)) |
2、預(yù)測(cè)單張圖片
2.1、待預(yù)測(cè)圖像
2.2、預(yù)測(cè)源碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
from sklearn.externals import joblib import cv2 if __name__ = = "__main__" : img = cv2.imread( "img_temp.jpg" , 0 ) #test = img.reshape(1,1444) tp_x = 10 tp_y = 10 tp_width = 20 tp_height = 20 img_temp = img[tp_y:tp_y + tp_height, tp_x:tp_x + tp_width] # 參數(shù)含義分別是:y、y+h、x、x+w cv2.namedwindow( "src" , 0 ) cv2.imshow( "src" , img_temp) cv2.waitkey( 1000 ) [height, width] = img_temp.shape print (width, height) res_img = cv2.resize(img_temp, ( 28 , 28 )) test = res_img.reshape( 1 , 784 ) #加載模型 svc = joblib.load( "model.m" ) pca = joblib.load( "pca.m" ) # svm print ( 'start pca...' ) test_x = pca.transform(test) print (test_x.shape) pre = svc.predict(test_x) print (pre[ 0 ]) |
2.3、預(yù)測(cè)結(jié)果
到此這篇關(guān)于使用python svm實(shí)現(xiàn)直接可用的手寫數(shù)字識(shí)別的文章就介紹到這了,更多相關(guān)python svm 手寫數(shù)字識(shí)別內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/mao_hui_fei/article/details/118358036