k-NN算法实现数字识别案例

来源:互联网 发布:网络授权书 编辑:程序博客网 时间:2024/05/16 05:45
示例:使用允-近邻算法的手写识别系统
(1)收集数据:提供文本文件。
(2)准备数据:编写函数(^133310 ( ) ,将图像格式转换为分类器使用的制格式。

(3)分析数据:在?5^0^命令提示符中检查数据,确保它符合要求。

(4)训练算法:此步驟不适用于各近邻算法。
(5)测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本
的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记
为一个错误。
(6)使用算法:本例没有完成此步驟,若你感兴趣可以构建完整的应用程序,从图像中提
取数字,并完成数字识别,美国的邮件分拣系统就是一个实际运行的类似系统。

# -*- coding: utf-8 -*-# 这样也行# coding:utf-8from os import listdirfrom numpy import *import  operatorimport matplotlibimport matplotlib.pyplot as pltdef createDataSet():    group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])    labels=['A','A','B','B']    return group,labels#k近邻算法def classify0(inx,dataset,labels,k):    datasetsize=dataset.shape[0]   #获取矩阵的行数    #距离计算   以下完成欧氏距离计算 d = 」(xA0 - xB0)2 + (xA{- xBt )2    # tile用于将数组第一维度扩展4倍,第二维度扩展一倍,再减去dataset    diffmat=tile(inx,(datasetsize,1))-dataset    #对差值矩阵进行平方运算    sqdiffmat=diffmat**2    sqdistance=sqdiffmat.sum(axis=1)  #axis=1表示按行求和  ,axis=0表示按列求和    #进行开根号处理    distances=sqdistance**0.5  #欧式距离计算到此结束    sorteddistindiciles=argsort(distances)  #argsort函数返回的是数组值从小到大的索引值    classcount={}    #选择最小的k个点    for i in range(k):        voteilabel=labels[sorteddistindiciles[i]]    #获取对应的标签        classcount[voteilabel]=classcount.get(voteilabel,0)+1     #d对对应的标签进行计数累加        #排序        sortedclasscount=sorted(classcount.iteritems(),        key=operator.itemgetter(1),reverse=True)    #dictionary.iteritems()将classcount迭代成数组        #将字典分解为元组列表,然后使用程序第二行导入运算符模块的itemgetter ,按照第二个元素的次序对元组进行排序©。#排序为逆序,即按照从最大到最小次序排序,最后返回发生频率最高的元素标签    return sortedclasscount[0][0]#以下该函数用来读取文本文件转换为矩阵def file2matrix(filename):    fr = open(filename)    numberOfLines = len(fr.readlines())         #get the number of lines in the file   获取文件的行数    returnMat = zeros((numberOfLines,3))        #prepare matrix to return   准备一个numberOfLines行,3列的矩阵,并用0填充    classLabelVector = []                       #prepare labels return    fr = open(filename)    index = 0    for line in fr.readlines():   #这里是对每行进行循环        line = line.strip()   #去掉每行后的换行符        listFromLine = line.split('\t')  #去掉制表符        returnMat[index,:] = listFromLine[0:3]   #把每行的前三个数据存储到数组里去        classLabelVector.append(int(listFromLine[-1]))  #把每行的最后一个数据插入标签数组中        index += 1    return returnMat,classLabelVector#用于归一化def autoNorm(dataSet):    minVals = dataSet.min(0)  #这里的0表示取列里面的最小值而不是行的,,,,这里的minVals是一个1*3的矩阵    maxVals = dataSet.max(0)  #这里的0表示取列里面的最大值而不是行的,,,,这里的maxVals是一个1*3的矩阵    ranges = maxVals - minVals  #对应的矩阵进行相减    normDataSet = zeros(shape(dataSet))  #建立一个与dataSet维度相同的全0矩阵    m = dataSet.shape[0]  #获取dataset的第一维度的值    normDataSet = dataSet - tile(minVals, (m,1))   #tile(minVals, (m,1))用于把minVals扩充成与dataSet维度一样的矩阵    normDataSet = normDataSet/tile(ranges, (m,1))    #element wise divide   n e w V a l u e = {o l d V a l u e - m i n ) / (max-min)  这就是归一化的公式    return normDataSet, ranges, minValsdef datingClassTest():    hoRatio = 0.50      #hold out 10%    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file   #调用函数读文件    normMat, ranges, minVals = autoNorm(datingDataMat)      #对数据进行归一处理    m = normMat.shape[0]        #第一维度的行数    numTestVecs = int(m*hoRatio)    errorCount = 0.0    #用于错误计数    for i in range(numTestVecs):        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)  #调用分类器进行计算        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])        if (classifierResult != datingLabels[i]): errorCount += 1.0  #错误时进行累加    print "the total error rate is: %f" % (errorCount/float(numTestVecs))   #打印错误率    print errorCount   #打印错误个数#将文件进行转换为数组def img2vector(filename):    returnVect = zeros((1,1024))  #创建一个向量,初始值全为0    fr = open(filename)    #获取文件对象    for i in range(32):        lineStr = fr.readline()   #按行读        for j in range(32):         #按列进行访问            returnVect[0,32*i+j] = int(lineStr[j])  #把32*32的向量进行存储,存储到一维向量中    return returnVect  #返回该向量def handwritingClassTest():    hwLabels = []    trainingFileList = listdir('trainingDigits')           #load the training set   #获取目录内容,把目录下的文件名一次存储在trainingFileList中    m = len(trainingFileList)       #获取该目录下文件数目    trainingMat = zeros((m,1024))   #创建一个全0数组    for i in range(m):        fileNameStr = trainingFileList[i]   #循环依次获得每个文件的名字        fileStr = fileNameStr.split('.')[0]     #take off .txt   将获得每个文件名进行切片,[0]表示取第0个切片,这样就可以把文件名的后缀去掉        classNumStr = int(fileStr.split('_')[0])#把文件名再次进行切片,获取第0个切片        hwLabels.append(classNumStr)  #把获得的数字加入数组,,这里就是标记对应的数字        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)  #把获得的文件对应的向量存储到对应的数组中    testFileList = listdir('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('testDigits/%s' % fileNameStr)  #把对应要测试的存储到向量中,注意这里是存储在向量中而不是数组中        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)  #调用分类器进行分类,返回分类结果        if (classifierResult != classNumStr):            errorCount += 1.0  #进行错误记录            print "here is the wrong test ,the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)        else:            print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)    print "\nthe total number of errors is: %d" % errorCount    #输出错误数目    print "\nthe total error rate is: %f" % (errorCount/float(mTest))  #输出错误率handwritingClassTest()


原创粉丝点击