k邻近算法:【回归】手写数字识别
分部代码
将图像转化为向量 img2vector(filename)
将32×32的图像以1×1024的向量输出
:param filename: 输入文件名
:return: 向量形式的数组,每行1024列
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
kNN算法程序 classify0(inX, dataSet, labels, k)
见《约会数据分类》
测试算法 handwritingClassTest()
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = zeros((m, 1024))
for i in range(m):
fileNameStr = trainingFileList[i]
file