数据集
链接:https://pan.baidu.com/s/1XCyuW3wbvWk8X28jvgS-WQ
提取码:jwsf
代码
from os import listdir
import numpy as np
def img2vector(filename):
vector=np.zeros((1,1024))
fp=open(filename)
for i in range(32):
fstr=fp.readline()
for j in range(32):
vector[0,32*i+j]=int(fstr[j])
return vector
def getmat():
labels=[]
listname=listdir('D:\\qq杂物\\347801313\\FileRecv\\MobileFile\\knn_data\\trainingDigits')
m=len(listname)
mat=[]
for i in range(m):
strname=listname[i].split('.')[0]
str=strname.split('_')[0]
labels.append(int(str))
mat.extend(img2vector('D:\\qq杂物\\347801313\\FileRecv\\MobileFile\\knn_data\\trainingDigits/%s'%listname[i]))
testlist=listdir('D:\\qq杂物\\347801313\\FileRecv\\MobileFile\\knn_data\\testDigits')
n=len(testlist)
rightnum=0
for i in range(n):
strname=testlist[i].split('.')[0]
str=strname.split('_')[0]
out=int(str)
testmat=img2vector('D:\\qq杂物\\347801313\\FileRecv\\MobileFile\\knn_data\\testDigits/%s'%testlist[i])
classfyresult=classfy0(testmat,mat,labels)
print("Classfy is",classfyresult,"Answer is",out)
if classfyresult==out:
rightnum=rightnum+1
print('Right Rate=',rightnum/n)
def classfy0(test,train,labels):
diff1=train-np.tile(test,(np.size(train,0),1))
diff2=diff1**2
distance=diff2.sum(axis=1)**0.5
sorteddis=distance.argsort()
k=3
labellist=np.zeros((1,10))
for i in range(k):
new_label=labels[sorteddis[i]]
labellist[0,new_label]=labellist[0,new_label]+1
finallabel=labellist.argsort()
return finallabel[0,9]
原文链接:https://blog.csdn.net/cj12345657582255/article/details/108978221