# 0415学习笔记：2.3手写识别系统-k近邻算法

1.二进制图像转换为1x1024的向量

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


2.测试

from os import listdir #列出给定目录的文件名
def handwritingCClassTest():
hwLabels = []
trainingFileList = listdir(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/traingDigits') #获取目录内容
m = len(trainingFileList) #目录中的文件数
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = traingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('.')[0])
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/traingDigits/%s'%fileNameStr)
testFileList = listdir(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/traingDigits')
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(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/traingDigits/%s'%fileNameStr)
classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
print('the classifier came back with:%d,the real answer is:%d'\
%(classifierResult,classNumStr) )
if (classifierResult != classNumStr):
errorCount += 1.0
print("the total error rate is :%f" % (errorCount / float(mTest)))  # 计算错误率


k近邻算法缺点：

必须保存全部数据集，耗用大量存储空间;

耗时

无法给出任何数据的基础结构信息，所以我们无法知道平均实例样本和典型实例样本有什么特征。