《机器学习实战》阅读笔记(三)

接上篇

2.2.3准备数据:归一化数值

由于数值较大的值会产生较大的影响,所以需要归一化,公式如下:

newValue=(oldValue-min)/(max-min)

归一化函数如下

def autoNorm(dataSet):
    minVals=dataSet.min(0)
    maxVals=dataSet.max(0)
    ranges=maxVals-minVals
    normDataSet=zeros(shape(dataSet))
    m=dataSet.shape[0]
    normDataSet=dataSet-tile(minVals,(m,1))
    normDataSet=normDataSet/tile(ranges,(m,1))
    return normDataSet,ranges,minVals

在交互式界面

>>> from numpy import *
>>> import kNN
>>> datingDataMat,datingLabels=kNN.file2matrix('datingTestSet2.txt')
>>> normMat,ranges,minVals=kNN.autoNorm(datingDataMat)
>>> normMat

2.2.4测试算法:作为完整程序验证分类器

用已有数据的90%作为训练样本,剩余10%去测试分类器,检验分类器的正确率。10%的样本是随机选择的。

def datingClassTest():
    hoRatio=0.10
    datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
    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)))

测试函数如上,其中遇到了两个问题,一是我用的python3,所以print()要加括号,否则会报错;二是https://blog.csdn.net/tao_627/article/details/44274543

2.2.5 使用算法:构建完整可用系统

def classifyPerson():
    resultList=['not at all','in small doses','in large doses']
    percentTats=float(input("percentage of time spent playing vedio games?"))
    ffMiles=float(input("frequent filer miles earns per year?"))
    iceCream=float(input("liters of ice cream consumed per year?"))
    datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
    normMat,ranges,minVals=autoNorm(datingDataMat)
    inArr=array([ffMiles,percentTats,iceCream])
    classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)
    print("You will probably like the person:%s"%resultList[classifierResult-1])

还是要注意print(),python3把raw_input()改为了input()

约会内容到此结束了~

2.3示例:手写识别系统

步骤:

1.收集数据:提供文本文件

2.准备数据:编写函数classify0(),将图像格式转化为分类器使用的list格式。

3.分析数据:在python命令提示符中检查数据,确保它符合要求。

4.训练算法:此步骤不适用于k近邻算法。

5.测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。

6.使用算法:本例没有完成此步骤。

2.3.1准备数据:将图像转化为测试向量

def img2Vector(filename):
    returnVect=zeros((1,1024))
    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

2.3.2测试算法:使用k近邻算法识别手写数字

def handwritingClassTest():
    hwLabels=[]
    trainingFileList=listdir('trainingDigits')
    m=len(trainingFileList)
    trainingMat=zeros((m,1024))
    for i in range(m):
        fileNameStr=trainingFileList[i]
        fileStr=fileNameStr.split('.')[0]
        classNumStr=int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:]=img2Vector('trainingDigits/%s' %fileNameStr)
    testFileList=listdir('testDigits')
    errorCount=0.0
    mTest=len(testFileList)
    for i in range(mTest):
        fileNameStr=testFileList[i]
        fileStr=fileNameStr.split('.')[0]
        classNumStr=int(fileStr.split('_')[0])
        vectorUnderTest=img2Vector('testDigits/%s' %fileNameStr)
        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("\nthe total number of error rate is %f" %(errorCount/float(mTest)))

2.4本章小结

介绍了k近邻算法,并给出了两个示例。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值