k近邻算法识别手写数字

from numpy import *
import operator
from os import listdir
“””
knn.py
author:uestcprince
date:2018/8/15
“””
inX:用于分类的输入向量
dataset:训练样本集
labels:标签向量
k:最近邻的数目
“””
def classify0(inX,dataset,labels,k):
dataSetSize=dataset.shape[0]
diffMat=tile(inX,(dataSetSize,1))-dataset #tile复制inX
sqDiffMat=diffMat**2 #每个元素平方
sqDistances=sqDiffMat.sum(axis=1) #按行求和
distances=sqDistances**0.5 #每个元素开方
sortedDistIndicies=distances.argsort()
classCount={}
for i in range(k):
voteIlabel=labels[sortedDistIndicies[i]]
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]

def img2vector(filename):
returnVect=zeros((1,1024))
fr=open(filename)
for i in range(32):
lineStr=fr.readline()
for j in range(32):
returnVect[0,32*i+j]=int(lineStr[j])
return returnVect

def handwritingClassTest():
hwLabels=[]
trainingFileList=listdir(‘D:/datasets/digits/trainingDigits’)
m=len(trainingFileList)
trainingMat=zeros((m,1024))
for i in range(m):
fileNameStr=trainingFileList[i]
#理解这段代码要知道文件的命名方式,这里是这样命名的9_45.txt,9表示分类,45表示第#45个。
fileStr=fileNameStr.split(‘.’)[0]
classNumStr=int(fileStr.split(‘_’)[0])
hwLabels.append(classNumStr)
trainingMat[i,:]=img2vector(‘D:/datasets/digits/trainingDigits/%s’%fileNameStr)
testFileList=listdir(‘D:/datasets/digits/testDigits’)
errorCount=0.0
mTest=len(testFileList)
for i in range(mTest):
fileNameStr=testFileList[i]
fileStr=fileNameStr.split(‘.’)[0]
classNumStr=int(fileStr.split(‘_’)[0])
vectorUnderTest=img2vector(‘D:/datasets/digits/testDigits/%s’%fileNameStr)
classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)
print(“the classifier cmae back with: %d,the real answer is %d”%(classifierResult,classNumStr))
if(classifierResult!=classNumStr):
errorCount+=1.0
print(“\nthe total number of errors is: %d” %errorCount)
print (“\nthe total error rate is: %f” %(errorCount/float(mTest)))
if name == “main“:
handwritingClassTest() # 欢迎使用Markdown编辑器写博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值