[python函数学习]机器学习实战 - 手写数字识别的测试代码

[python函数学习]机器学习实战 - 手写数字识别的测试代码

from numpy import *
import operator #运算符模块 可执行排序操作
from os import listdir
# 将图像转换为向量 img to vector
def img2vector(filename): 
    returnVect = zeros((1, 1024))  #一维 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])
    return returnVect
# 测试代码
def handwritingClassTest():
    hwLabels = []
    pathTrain = "E:\\machine Learning in Action\\machinelearninginaction\\Ch02\\digits\\trainingDigits"
    trainingFileList = listdir(pathTrain) # 返回目录下文件名列表
    m = len(trainingFileList) # 文件个数
    trainingMat = zeros((m, 1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0] # 以 . 为分隔符,将数据分为两列 只取第一列数据,即删除后缀.txt
        classNumStr = int(fileStr.split('_')[0]) # 取0-9分类
        hwLabels.append(classNumStr)
        trainingMat[i, : ] = img2vector(pathTrain + '/' + fileNameStr) # img to vector
    # 测试集
    pathTest = "E:\\machine Learning in Action\\machinelearninginaction\\Ch02\\digits\\testDigits"
    testFileList = listdir(pathTest)
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]  # 以 . 为分隔符,将数据分为两列 只取第一列数据,即删除后缀.txt
        classNumStr = int(fileStr.split('_')[0]) # 取0-9分类
        vectorUnderTest = img2vector(pathTest + '/' + fileNameStr) #img to vector
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)  # 计算欧式距离 选择距离最小的3个点
        print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr))
        if(classifierResult != classNumStr): errorCount += 1.0
    print("\nthe total number of errors is: %d" % errorCount)
    print("\nthe total error rate is: %f" % (errorCount/float(mTest)))

os.listdir(path)

返回指定路径下的文件和文件夹列表
path – 是目录路径
eg:

from os import listdir
# 打开文件
path = ""
dirs = os.listdir(path)
# 输出所有文件和文件夹
for file in dirs
	print file
输出结果:
test.htm
stamp
faq.htm
_vti_txt
robots.txt
itemlisting
resumelisting
writing_effective_resume.htm
advertisebusiness.htm
papers
resume
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值