机器学习实战笔记-K近邻算法3(手写识别系统)

1 准备数据:将图像转换为测试向量
这次数据集还是有两种,训练数据集和测试数据集,分别有2000个,900个。
我们将把一个32*32的二进制图像矩阵转换为1 x 1024的向量,这样前两节使用的分类器就可以处理数字图像信息了。
代码:

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

效果截图:
这里写图片描述
测试算法
代码:
def handWritingTest(): 
hwLabels = []
trainingFileList = os.listdir('trainingDigits')
trainingFileLength = len(trainingFileList)
trainingMat = zeros((trainingFileLength,1024))
for i in range(trainingFileLength):
fileNameStr = trainingFileList[i]
className = fileNameStr.split('_')[0]
hwLabels.append(int(className))
fileVector = img2vector('trainingDigits/' + fileNameStr)
trainingMat[i,:] = fileVector
testFileList = os.listdir('testDigits')
testFileLength = len(testFileList)
errorCount = 0.0
for i in range(testFileLength):
fileNameStr = testFileList[i]
className = int(fileNameStr.split('_')[0])
fileVector = img2vector('testDigits/' + fileNameStr)
testResult = classify0(fileVector,trainingMat,hwLabels,3)
print("the classifier came back with: %d, the real answer is: %d" % (testResult,className))
if(testResult != className):
errorCount+=1.0
errorRate = errorCount/float(testFileLength)
print("the errorRate is : %f" % errorRate)

结果截图:
这里写图片描述

分别将k改为4,5:
这里写图片描述
这里写图片描述
可以发现错误率逐渐增高

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值