机器学习笔记--KNN算法2-实战部分

2022-11-01,,,,

本文申明:本系列的所有实验数据都是来自【美】Peter Harrington 写的《Machine Learning in Action,侵

一案例导入:玛利亚小姐最近寂寞了,然后她就准备在一个在线社交网站搞网恋,但是凡是都有一个选择,按照她以往的经验,她接触了三种人:

1:不喜欢的人

2:魅力一般的人

3:特别有魅力的人

但是啊,尽管发现了这三类人,但是她还是无法甄别她究竟喜欢哪种人。所以她就求助我们,如果给她当这个月老。---------那我们就把这个实践叫做月老实践吧。

二案件解决:玛利亚小姐根据常年的搞网恋经验发现她对对方每年获得的飞行常客里程数,玩视频游戏所耗时间百分比,以及每周消费的冰淇淋公升数比较感兴趣。那现在我们就把这三个feature构成我们的分类模型。

既然我们用分类问题那么就按照上节所述的KNN来试着解决这个问题。

三实验步骤:

1:首先进入python的开发环境之后,输入import KNN 导入我们的算法KNN算法模块:,然后创建变量group 和labels.然后输入看这两个变量是否正确,我们用了【0,0】这个数据,被分进了B类。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/ -->def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels

2:重新导入我们的KNN模块。reload(KNN)的作用是在我们更新模块里的代码的时候,用这个加载新的源代码,否则还是加载原来的代码。如下图的datingDataMat,datingLabels=KNN.file2matrix(‘datingTest2.txt’).这句话是我们使用file2matrix()这个函数读取我们的测试文件,当然这个测试文件必须在我们的工作目录中。成功导入之后输入参数,就会看到如下的矩阵数据。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/ -->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
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

3:归一化数据。还是那样重新加载模块。设置三个参数normMat,ranges,minVals然后把他归一化。上节我们都说过,如果不记得的童鞋可以上去在看看。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/ -->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)) #element wise divide
return normDataSet, ranges, minVals

4:现在我们用测试数据来测试我们的学习程序的正确率。

从上图可以看出 the total error rate is:6.4%.这个结果还是很不错的。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/ -->def 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

5:构建一个完整的系统,但是这一段我不想把数据跑出来给大家,大家还是自己动手实践一下比较好。我现在把代码贴出来,供大家参考。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/ -->def classifyPerson():
resultList=['not at all','in small doses','in large doses']
percentTats=float(raw_input("personttage of time spent playing video games?"))
ffMiles=float(raw_input("frequent flier miles earned per year?"))
iceCream=float(raw_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 this : ",resultList[classifierResult - 1]

本节到此结束,有需要源码的可以加我qq:759558806.

谢谢大家支持。

机器学习笔记--KNN算法2-实战部分的相关教程结束。

《机器学习笔记--KNN算法2-实战部分.doc》

下载本文的Word格式文档,以方便收藏与打印。