生活随笔
收集整理的這篇文章主要介紹了
机器学习之KNN结合微信机器人实现手写数字识别终极API
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
機器學習之KNN結合微信機器人實現手寫數字識別終極API
手寫數字識別
功能概述
微信機器人接收到的手寫數字圖片,傳送給已經經過機器學習訓練過的knn分類器,進行預測,輸出數字結果。
實現步驟
- 將手寫數字圖片轉變為32*32的矩陣
因為機器學習的訓練數據集是DBRHD數據集(訓練數據集已上傳到我的資料可以自行下載),圖片均歸一化為以數字為中心的32*32規格的矩陣:空白區域用0表示,字跡部分用1表示。所以首先就需要將手寫數字圖片轉換成文本形式。
ps:DBRHD數據集我已上傳到我的資源
from PIL
import Image
import matplotlib
.pylab
as plt
import numpy
as np
def picTo01(filename
):"""將圖片轉化為32*32像素的文件,用0 1表示:param filename::return:"""img
= Image
.open(filename
).convert
('RGBA')raw_data
= img
.load
()for y
in range(img
.size
[1]):for x
in range(img
.size
[0]):if raw_data
[x
, y
][0] < 90:raw_data
[x
, y
] = (0, 0, 0, 255)for y
in range(img
.size
[1]):for x
in range(img
.size
[0]):if raw_data
[x
, y
][1] < 136:raw_data
[x
, y
] = (0, 0, 0, 255)for y
in range(img
.size
[1]):for x
in range(img
.size
[0]):if raw_data
[x
, y
][2] > 0:raw_data
[x
, y
] = (255, 255, 255, 255)img
= img
.resize
((32, 32), Image
.LANCZOS
)img
.save
('test.png')array
= plt
.array
(img
)gray_array
= np
.zeros
((32, 32))for x
in range(array
.shape
[0]):for y
in range(array
.shape
[1]):gary
= 0.299 * array
[x
][y
][0] + 0.587 * array
[x
][y
][1] + 0.114 * array
[x
][y
][2]if gary
== 255:gray_array
[x
][y
] = 0else:gray_array
[x
][y
] = 1name01
= filename
.split
('.')[0]name01
= name01
+ '.txt'np
.savetxt
(name01
, gray_array
, fmt
='%d', delimiter
='')if __name__
== '__main__':picTo01
('picture.jpg')
- 手寫數字識別代碼編寫
KNN的輸入是圖片矩陣展開的1024維向量;輸出是一個數字。
KNN手寫數字識別實體構建
1.建立工程并導入sklearn包
2.加載訓練數據
3.構建knn分類器
4.測試集評價
5.進行預測
6.將預測結果寫入txt文件
"""
Created on Sat Aug 3 16:24:13 2019@author: 53592
"""import numpy
as np
from os
import listdir
from sklearn
import neighbors
def img2vector(filename
):retMat
= np
.zeros
([1024],int)fr
= open(filename
)lines
= fr
.readlines
()for i
in range(32):for j
in range(32):retMat
[32*i
+j
] = lines
[i
][j
]return retMat
def readDataSet(path
):fileList
= listdir
(path
)numFiles
= len(fileList
)dataSet
= np
.zeros
([numFiles
,1024],int)hwLabels
= np
.zeros
([numFiles
])for i
in range(numFiles
):filePath
= fileList
[i
]digit
= int(filePath
.split
('_')[0])hwLabels
[i
] = digitdataSet
[i
] = img2vector
(path
+'/'+filePath
)return dataSet
,hwLabelstrain_dataSet
,train_hwLabels
= readDataSet
('trainingDigits')
test_dataSet
,test_hwLabels
= readDataSet
('testDigits')knn
= neighbors
.KNeighborsClassifier
(algorithm
='kd_tree',n_neighbors
=3)
knn
.fit
(train_dataSet
,train_hwLabels
)
res
= knn
.predict
(test_dataSet
)
num
= len(test_dataSet
)
error_num
= np
.sum(res
!= test_hwLabels
)
correct_num
= np
.sum(res
== test_hwLabels
)
print("Total num:",num
,"Wrong num:",error_num
,"WrongRate:",error_num
/float(num
),'correct_num:',correct_num
,'CorrectRate:',correct_num
/float(num
))
- 微信機器人的實現
此處又用到了強大的wxpy
官方說明書:點此進入
from wxpy
import *bot
= Bot
(cache_path
=True)
client
= bot
.friends
().search
('friend')[0]
client
.send
("輸入‘功能’,查看微信機器人功能")@bot
.register
()
def response_function(msg
):
if(msg
.text
=='功能'):client
.send
("手寫數字識別,請發送一張手寫數字圖片")@bot
.register
(client
,msg_types
=PICTURE
)
def handdigit_recongnition(msg
):client
.send
("手寫數字識別中。。。")msg
.get_file
(save_path
='D:\Python\digit.jpg')'''此時執行圖片轉換成矩陣的代碼還要進行knn.predict()將預測結果寫到文件digit.txt中'''with open("D:\\Python\\digit.txt",'r') as f
:f
.seek
(0)b
=f
.read
()f
.close
()client
.send
(b
)embed
()
結果展示
改進之處和TIPS
- 設置鄰居數量可以對比預測準確率
- 設置交叉驗證可以檢測分類器的準確率
- KNN算法只是方法之一,還可以利用神經網絡進行識別,添加不同個數的神經元進行訓練,最后預測。
- 由于神經網絡對于小數據容易過擬合沒所以準確率上面KNN大于MLP(多層感知機),MLP對于參數調整比較敏感,若參數不合理容易得到較差的分類結果,所以參數設計對于MLP至關重要。
- 微信機器人還可以進行其他有趣的功能,除了我之前寫的微信實現遠程控制,我后續還會發一些有趣的實例
- 代碼分開了所以有的銜接我沒放,給大家想象的空間,自己繼續探索吧!
總結
以上是生活随笔為你收集整理的机器学习之KNN结合微信机器人实现手写数字识别终极API的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。