机器学习之K近邻算法识别手写数字:
1.准备数据:将图像转换为测试向量
书中提供数据0到9如图所示,世纪图像存储在源代码的两个子目录里:目录trainingDigits中包含了大约2000个例子,每个例子的内容如下图所示,每个数字大约有200个样本;目录testDigits中包含了大约900个测试数据。两组数据没有重叠。
我们将把一个32*32的二进制图像矩阵转化为1*1024的向量,这样前两节使用的分类器可以处理数据图像信息了。实现代码:
def img2vector(filename):
"""
Function: 32*32图像转换为1*1024向量
Args: filename:文件名称字符串
Returns: returnVect:转换之后的1*1024向量
"""
#初始化要返回的1*1024向量
returnVect = zeros((1, 1024))
#打开文件
fr = open(filename)
#读取文件信息
for i in range(32):
#循环读取文件的前32行
lineStr = fr.readline()
for j in range(32):
#将每行的头32个字符存储到要返回的向量中
returnVect[0, 32*i+j] = int(lineStr[j])
#返回要输出的1*1024向量
return returnVect
输出结果:
>>> reload(kNN)
>>> testVector = kNN.img2vector('testDigits/0_13.txt')
>>> testVector[0,0:31]
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.])
>>> testVector[0,32:63]
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.])
2.算法测试
在之前的kNN.py代码中加入from os import listdir,然后编写下列测试程序即可测试算法
实现代码:
def handwritingClassTest():
"""
Function: 手写数字测试程序
Args: 无
Returns: returnVect:转换之后的1*1024向量
"""
#初始化手写数字标签列表
hwLabels = []
#获取训练目录信息
trainingFileList = listdir('trainingDigits')
#获取训练文件数目
m = len(trainingFileList)
#初始化训练矩阵
trainingMat = zeros((m,1024))
#开始提取训练集
for i in range(m):
#从文件名解析出分类数字
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
#存储解析出的分类数字到标签中
hwLabels.append(classNumStr)
#载入图像
trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr)
#获取测试目录信息
testFileList = 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('trainingDigits/%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("\nthe total number of errors is: %d" % errorCount)
#输出错误率
print("\nthe total error rate is: %f" % (errorCount/float(mTest)))
结果输出:
>>> reload(kNN)
>>> kNN.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: 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 errors is: 13
the total error rate is: 0.013742
K紧邻算法识别手写数字数据集,错误率为1.2%,改变变量K的值等都会对错误率产生影响。
3.总结
K近邻算法是分类数据最简单有效的算法,K近邻算法是基于实列的学习,使用算法时我们必须有接近实际数据的训练样本数据。
k-近邻算法必须保存全部数据集,并对数据集中的每个数据计算距离值,实际使用时耗时耗存储。
而且,它无法给出任何数据的基础结构信息,所以我们不知道平均实例样本与典型实例样本具有什么特征