【python】机器学习实战KNN算法之手写数字识别


python代码实现:

import numpy as np
import operator
import matplotlib.pyplot as plt  
from os import listdir
def classify(inX, dataset, labels, k):
    dataSetSize = dataset.shape[0] 
    diffMat =np. tile(inX, (dataSetSize, 1)) - dataset
    sqDiffMat = diffMat ** 2
    sqDistance = sqDiffMat.sum(axis=1)
    distance = sqDistance ** 0.5
    sortedDistIndicies = distance.argsort()
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]
    def img2vector(filename):
    """
    将图片数据转换为01矩阵。
    每张图片是32*32像素,也就是一共1024个字节。
    因此转换的时候,每行表示一个样本,每个样本含1024个字节。
    """
    # 每个样本数据是1024=32*32个字节
    returnVect = np.zeros((1,1024))
    fr = open(filename)
    # 循环读取32行,32列。
    for i in range(32):
        lineStr = fr.readline()
        #print(lineStr)
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

def handwritingClassTest():
    hwLabels = []
    # 加载训练数据 listdir()指定目录中的内容
    trainingFileList = listdir('C:\\Users\\蓝月亮\\Desktop\\机器学习实战源代码\\machinelearninginaction\\Ch02\\trainingDigits')           
    #print(trainingFileList)
    m = len(trainingFileList)   #求出指定路径中的内容也就是文件个数  m=1936
    trainingMat = np.zeros((m,1024))   #1936x1024的零矩阵
   
    for i in range(m):
        # 从文件名中解析出当前图像的标签,也就是数字是几
        # 文件名格式为 0_3.txt 表示图片数字是 0
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]     #spilt()之后是个列表,去取列表的第一个元素即去掉每个文件的后缀'.txt'.即由0_***.txt变成0_***
        classNumStr = int(fileStr.split('_')[0])  #将'_'切片由0_**得到数字0,1,2,3,4,5,6,7,8,9        
        hwLabels.append(classNumStr)              #得到一个长度为1934的列表
       
        trainingMat[i,:] = img2vector('C:\\Users\\蓝月亮\\Desktop\\机器学习实战源代码\\machinelearninginaction\\Ch02\\trainingDigits\\%s' % fileNameStr)
    
    # 加载测试数据
    testFileList = listdir('C:\\Users\\蓝月亮\\Desktop\\机器学习实战源代码\\machinelearninginaction\\Ch02\\testDigits')        #iterate through the test set
    errorCount = 0.0
    mTest = len(testFileList)              #  m=946
 
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        #print(fileStr)
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('C:\\Users\\蓝月亮\\Desktop\\机器学习实战源代码\\machinelearninginaction\\Ch02\\testDigits/%s' % fileNameStr)
        classifierResult = classify(vectorUnderTest, trainingMat, hwLabels, 3)
        print("the classifier came back with: %d, the real answer is: %d, The predict result is: %s" % (classifierResult, classNumStr, classifierResult==classNumStr))
        if (classifierResult != classNumStr): errorCount += 1.0
    print("\nthe total number of errors is: %d / %d" %(errorCount, mTest))
    print("\nthe total error rate is: %f" % (errorCount/float(mTest)))


结果:取k=3,正确率99%100,还是挺高的


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值