资源简介
手写体数字识别数据-digits.zip——手写体数据和KNN实现
代码片段和文件信息
‘‘‘
kNN: k Nearest Neighbors
Input: inX: vector to compare to existing dataset (1xN)
dataSet: size m data set of known vectors (NxM)
labels: data set labels (1xM vector)
k: number of neighbors to use for comparison (should be an odd number)
Output: the digit label
‘‘‘
from numpy import *
import operator
from os import listdir
# KNN分类方法
def classify0(inX dataSet labels k):
# 距离计算——使用欧氏距离,计算两个向量点的距离
dataSetSize = dataSet.shape[0]
diffMat = tile(inX (dataSetSize1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
# 把距离从小到大排序
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k):
# 统计距离最 近的 k 个 数据的 标签分类出现次数
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel0) + 1
# 对 标签分类出现次数 进行 从大到小 排序
sortedClassCount = sorted(classCount.items() key=operator.itemgetter(1) reverse=True)
return sortedClassCount[0][0]
# 这里把 32 * 32 的 二进制图像矩阵 转换为 1 * 1024 的向量
def img2vector(filename):
returnVect = zeros((11024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVect[032*i+j] = int(lineStr[j])
return returnVect
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir(‘digits/trainingDigits‘) #load the training set
m = len(trainingFileList)
trainingMat = zeros((m1024))
for i in range(m):
fileNameStr = trainingFileList[i]
# 获取文件名
fileStr = fileNameStr.split(‘.‘)[0] #take off .txt
# 获取标签数值
classNumStr = int(fileStr.split(‘_‘)[0])
# 待识别图片数字的 标签数值 保存在 hwLabels 中
hwLabels.append(classNumStr)
trainingMat[i:] = img2vector(‘digits/trainingDigits/%s‘ % fileNameStr)
testFileList = listdir(‘digits/testDigits‘) #iterate through the test set
errorCount = 0.0
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split(‘.‘)[0] #take off .txt
classNumStr = int(fileStr.split(‘_‘)[0])
vectorUnderTest = img2vector(‘digits/testDigits/%s‘ % fileNameStr)
# 调用KNN分类方法
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(“\n the total number of errors is: %d“ % errorCount)
print(“\n the total error rate is: %f“ % (errorCount/float(mTest)))
print(“测试的手写体数字个数为 %d “ % mTest)
# 调用方法
handwritingClassTest()
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 739988 2011-05-04 15:43 数据和KNN实现代码\digits.zip
文件 3138 2019-05-22 18:11 数据和KNN实现代码\handIdentify.py
目录 0 2019-05-22 18:19 数据和KNN实现代码\
评论
共有 条评论