基于Python手寫拼音識(shí)別
一、算法構(gòu)造
1.簡(jiǎn)單介紹一下knn算法
KNN算法,也叫K最近鄰算法。功能是分類。算法邏輯非常簡(jiǎn)單,說直白點(diǎn)就是:先找到跟你最近的k個(gè)鄰居(假設(shè)k=5),再看你的鄰居給哪個(gè)類別投票(即鄰居的標(biāo)簽),少數(shù)服從多數(shù),得票最多的結(jié)果就是你的類別。
在這個(gè)算法中最關(guān)鍵的三點(diǎn):
k值 :選擇距離最近的k個(gè)鄰居。
距離計(jì)算:計(jì)算距離的方法有歐式距離和曼哈頓距離,本文采用歐式距離,即先求差值的平方和,再開根號(hào)。
分類標(biāo)簽:本文的分類標(biāo)簽即a,b,c,d等字母
2.Python實(shí)現(xiàn)KNN
'''
k:k值
testdata:測(cè)試數(shù)據(jù)集
traindata:訓(xùn)練數(shù)據(jù)集
labels:分類標(biāo)簽
'''
def knn(k, testdata, traindata, labels):
? ? '''定義算法'''
? ? traindatasize = traindata.shape[0] #計(jì)算訓(xùn)練集的長(zhǎng)度
? ? dif = tile(testdata,(traindatasize,1)) - traindata #將測(cè)試集擴(kuò)展至訓(xùn)練集的長(zhǎng)度,再求差值
? ? sqrdif = dif**2 #求差值的平方
? ? sumsqrdif = sqrdif.sum(axis=1) #求平方和
? ? distance = sumsqrdif**0.5 #再開根號(hào),即所有的距離
? ? sorted_distance = distance.argsort() #對(duì)距離進(jìn)行排序,返回排序后的索引
? ? count = {} #準(zhǔn)備一個(gè)空字典,存放投票結(jié)果
? ? for i in range(0,k): ?
? ? ? ? vote = labels[sorted_distance[i]] #提取索引多對(duì)應(yīng)的標(biāo)簽值作為字典的key
? ? ? ? count[vote] = count.get(vote,0)+1 ?#票數(shù)作為字典的value
? ? sorted_count = sorted(count.items(),key=lambda x:x[1],reverse=True) #對(duì)最后的投票結(jié)果進(jìn)行排序
? ? return sorted_count[0][0] #返回得票最多的標(biāo)簽二、準(zhǔn)備數(shù)據(jù)
用最笨的方法,手寫了一批png格式的數(shù)字圖片:

圖片的尺寸都是統(tǒng)一的:32*32像素
圖片的命名也是統(tǒng)一的:數(shù)字標(biāo)簽+"_"+第n張圖+“.png"
1、將圖片轉(zhuǎn)換成數(shù)組矩陣
訓(xùn)練數(shù)據(jù)集與測(cè)試數(shù)據(jù)集都是標(biāo)準(zhǔn)化后的數(shù)組矩陣,而我們的試驗(yàn)對(duì)象是手寫體數(shù)字圖片,首先需要將圖片進(jìn)行一下數(shù)據(jù)化處理。
def img2Model(originDataPath, modelpath):
? ? list = os.listdir(originDataPath)
? ? for child in list:
? ? ? ? s_list = os.listdir(originDataPath + child)
? ? ? ? for i in s_list:
? ? ? ? ? ? filepath=originDataPath + child + '/' + i
? ? ? ? ? ? # print(filepath)
? ? ? ? ? ? img = cv2.imdecode(np.fromfile(filepath, dtype=np.uint8),0)
? ? ? ? ? ? img = cv2.resize(img, (32, 32))
? ? ? ? ? ? img = np.asarray(img)
? ? ? ? ? ? img[img > 127] = 255
? ? ? ? ? ? img[img <= 127] = 1
? ? ? ? ? ? img[img == 255] = 0
? ? ? ? ? ? dstFileName = modelPath + i.split('.')[0] + '.txt'
? ? ? ? ? ? np.savetxt(dstFileName, img, fmt='%d', delimiter=' ')三、處理數(shù)據(jù):訓(xùn)練集與測(cè)試集
1、區(qū)分訓(xùn)練集和測(cè)試集
# 隨機(jī)分揀出測(cè)試集,其他文件為訓(xùn)練集
def shutildata(modelpath, trainpath, testpath):
? ? txtlist = os.listdir(modelpath)
? ? index = [random.randint(0, len(txtlist)) for i in range(10)]
? ? # print(index)
? ? arr = [txtlist[i].split('.')[0].split("_")[1] for i in index]
? ? for i in txtlist:
? ? ? ? try:
? ? ? ? ? ? if i.split(".")[0].split("_")[1] in arr:
? ? ? ? ? ? ? ? shutil.copy(modelpath + "/" + i, testpath)
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? shutil.copy(modelpath + "/" + i, trainpath)
? ? ? ? except:
? ? ? ? ? ? pass2、加載數(shù)據(jù)
# 加載數(shù)據(jù) def load_data(dataFilePath): ? ? arr = np.loadtxt(dataFilePath, dtype=np.int) ? ? arr = arr.flatten() ? ? return arr
3、建立訓(xùn)練數(shù)據(jù)
# 建立訓(xùn)練數(shù)據(jù)集
def makeTrainData(trainpath):
? ? labels = []
? ? trainfile = os.listdir(trainpath)
? ? trainarr = np.zeros((len(trainfile), 1024))
? ? for i in range(0, len(trainfile)):
? ? ? ? # print(trainfile[i])
? ? ? ? thislabel = trainfile[i].split(".")[0].split("_")[0]
? ? ? ? if len(thislabel) != 0:
? ? ? ? ? ? labels.append(int(thislabel))
? ? ? ? trainarr[i, :] = load_data(trainpath + trainfile[i])
? ? return trainarr, labels四、測(cè)試數(shù)據(jù)
# 驗(yàn)證
def validate(testpath, trainpath, k):
? ? trainarr, labels = makeTrainData(trainpath)
? ? testfiles = os.listdir(testpath)
? ? count = 0
? ? # 讀取字典表
? ? with open('num_char.json', 'r') as f:
? ? ? ? dict = json.loads(f.read())
? ? ? ? # print(dict)
? ? for i in range(0, len(testfiles)):
? ? ? ? testpicname = testfiles[i].split("_")[0]
? ? ? ? testarr = load_data(testpath + testfiles[i])
? ? ? ? result = knn(k, testarr, trainarr, labels)
? ? ? ? testpicname = dict[str(testpicname)]
? ? ? ? result = dict[str(result)]
? ? ? ? print("真正字母:"+testfiles[i] +" ?" + testpicname + " ?" + "測(cè)試結(jié)果為:{}".format(result))
? ? ? ? if str(testpicname) == str(result):
? ? ? ? ? ? count += 1
? ? print("-----------------------------")
? ? print("測(cè)試集為:{}個(gè),其中正確了{(lán)}個(gè)".format(len(testfiles),count))
? ? print("正確率為{}".format(count / len(testfiles)))
? ? print()到此這篇關(guān)于基于Python手寫拼音識(shí)別的文章就介紹到這了,更多相關(guān)Python手寫拼音識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python Pandas數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)單介紹
這篇文章主要介紹了Python Pandas數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)單介紹的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
解決python給列表里添加字典時(shí)被最后一個(gè)覆蓋的問題
今天小編就為大家分享一篇解決python給列表里添加字典時(shí)被最后一個(gè)覆蓋的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Python編程實(shí)現(xiàn)二叉樹及七種遍歷方法詳解
這篇文章主要介紹了Python編程實(shí)現(xiàn)二叉樹及七種遍歷方法,結(jié)合實(shí)例形式詳細(xì)分析了Python二叉樹的定義及常用遍歷操作技巧,需要的朋友可以參考下2017-06-06
wxpython實(shí)現(xiàn)圖書管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了wxpython實(shí)現(xiàn)圖書管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
Python遍歷文件夾和讀寫文件的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python遍歷文件夾和讀寫文件的實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-08-08
django使用定時(shí)任務(wù)django_apscheduler的實(shí)現(xiàn)
定時(shí)任務(wù)無論是個(gè)人開發(fā)還是企業(yè)業(yè)務(wù)都是需要的,本文主要介紹了django使用定時(shí)任務(wù)django_apscheduler的實(shí)現(xiàn),減少請(qǐng)求時(shí)需要用戶等待的時(shí)間,感興趣的可以了解一下2021-08-08

