k-近邻算法 手写识别系统

博客围绕机器学习实战展开,但具体内容缺失,推测会涉及机器学习在实际场景中的应用、操作等信息技术相关关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import matplotlib.pyplot as plt
import os
import operator
def img2vector(filename):
    returnVect=np.zeros((1,1024))
    f=open(filename,'r')
    for i in range(32):
        lineStr=f.readline()
        for j in range(32):
            returnVect[0,32*i+j]=int(lineStr[j])
    return returnVect
def classify0(inX,dataSet,labels,k):
    dataSetSize = dataSet.shape[0]
    diffMat = np.tile(inX,(dataSetSize,1))-dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis = 1)
    distances = sqDistances ** 0.5
    sortedDistIndicies = distances.argsort()  #indices
    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 handwritingClassTest():
    hwLabels=[]
    trainingFilelist=os.listdir('E:\\machine learning\\machine learning ex\\digits\\digits\\trainingDigits')
    m=len(trainingFilelist)
    trainingMat=np.zeros((m,1024))
    for i in range(m):
        fileNameStr=trainingFilelist[i]
        hwLabels.append(fileNameStr.split('_')[0])
        trainingMat[i,:]=img2vector('E:\\machine learning\\machine learning ex\\digits\\digits\\trainingDigits\\'+fileNameStr)
    
    
    testFileList=os.listdir('E:\\machine learning\\machine learning ex\\digits\\digits\\testDigits')
    errorCount=0.0
    mTest=len(testFileList)
    for i in range(mTest):
        fileNameStr=testFileList[i]
        classNumberStr=fileNameStr.split('_')[0]
        vectorUnderTest=img2vector('E:\\machine learning\\machine learning ex\\digits\\digits\\trainingDigits\\'+fileNameStr)
        classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)
        print('预测结果:',classifierResult,"真实结果:",classNumberStr)
        if(classifierResult!=classNumberStr):
            errorCount+=1
    print('错误率为:',errorCount/float(mTest))
    
path='E:\\machine learning\\machine learning ex\\digits\\digits\\trainingDigits\\0_13.txt'
handwritingClassTest()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值