赞
踩
一、准备工作
前面的博客已讲述了K近邻的概念,这里是一个K近邻算法的应用。
准备内容:
1.手写数字训练集trainingDigits
2.手写数字测试集testDigits
程序的基本内容:
1.原算法的第一步是导入数据,并进行矩阵化处理,这里的第一步是将图片转化成向量。图片在数据集中是以数字的形式保存,3232,将二维图片转化成11024一维的向量。一共有接近2000的训练集和900多的测试集
2.将每一个测试样本都调用KNN算法,KNN算法的参数为1.测试向量 2.训练样本 3.类别 4.k值
代码:
import numpy as np import operator import os # 图像转换为向量 def img2vector(filename): returnVect = np.zeros((1,1024)) # 生成一个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]) # 一个一个的加入1*1024的向量中 return returnVect # 返回这个1*1024向量 # KNN def classify0(inX,dataset,labels,k): dataSetSize = dataset.shape[0] # 下面计算距离 diffMat = np.tile(inX,(dataSetSize,1))-dataset # tile()复制函数 sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) # 进行行相加 distances = sqDistances**0.5 sortedDistIndicies = distances.argsort() #argsort()按照从小到大排序返回原序列元素的序号。 # 选择距离最小的K个点 classCount={} for i in range(k): voteIlabel =labels[sortedDistIndicies[i]] # 找到与数据最近的k个标签 classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 # 将各个标签的数量添加到字典中 # operator.itemgetter(1)选择字典的value进行排序,拍完序reserve反转 sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) # print(sortedClassCount) return sortedClassCount[0][0] # 测试手写数字识别 def handwritingClassTest(): hwlabels = [] trainingFileList = os.listdir('trainingDigits') m = len(trainingFileList) trainingMat = np.zeros((m,1024)) for i in range(m): fileNameStr = trainingFileList[i] # 获取训练样本名字 fileStr = fileNameStr.split('.')[0] #获取训练样本的名字去掉后缀 classNumStr = int(fileStr.split('_')[0]) # 获取‘0_13’前面数字,代表数字 hwlabels.append(classNumStr) # 类别标签保存到列表中 trainingMat[i,:] = img2vector('trainingDigits/%s' %fileNameStr) # 将全部训练样本组成一个矩阵 testFileList = os.listdir('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('testDigits/%s'%fileNameStr) # 转化成1*1024向量 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 number of error is : %d' %errorCount) print('the total error rate is :%f' % (errorCount/float(mTest))) handwritingClassTest()
结果:
the classifier came back with :0,the real answer is :0 the classifier came back with :0,the real answer is :0 the classifier came back with :0,the real answer is :0 the classifier came back with :0,the real answer is :0 the classifier came back with :0,the real answer is :0 the classifier came back with :0,the real answer is :0 . . the classifier came back with :2,the real answer is :2 the classifier came back with :2,the real answer is :2 the classifier came back with :2,the real answer is :2 the classifier came back with :2,the real answer is :2 the classifier came back with :2,the real answer is :2 the classifier came back with :3,the real answer is :3 the classifier came back with :3,the real answer is :3 the classifier came back with :3,the real answer is :3 . . the classifier came back with :9,the real answer is :9 the classifier came back with :9,the real answer is :9 the classifier came back with :9,the real answer is :9 the total number of error is : 11 the total error rate is :0.011628 Process finished with exit code 0
可以看到预测的错误率为1.1%。通过更改变量K值和修改函数的handwritingClassTest随机选取训练样本、改变训练样本的数目,都会对K近邻算法的错误率产生影响。
样本集下载:百度云链接
提取码:g64m
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。