机器学习实战笔记六_Python3

程序清单2-5,

伪代码

[python]  view plain  copy
  1. def classifyPerson():  
  2.     resultList = ['not at all','in small doses','in large doses']  
  3.     percentTats = float(input(\  
  4.         "percentage of time spent playing video games?"))  
  5.     ffMiles = float(input(\  
  6.         "frequent flier miles earned per year? "))  
  7.     iceCream = float(input(\  
  8.         "liters of ice cream consumed per year?"))  
  9.     datingDataMat,datingLabels = file2matrix('datingTestSet.txt')  
  10.     normMat, ranges, minVals = autoNorm(datingDataMat)  
  11.     inArr = array([ffMiles, percentTats, iceCream])  
  12.     clssifierResult = classify0((inArr-minVals)/ranges,\  
  13.                                 normMat,datingLabels,3)  
  14.     print("You will probably like this person:",\  
  15.           resultList[clssifierResult-1])  

完整

[python]  view plain  copy
  1. #批量注释、批量取消注释 Ctrl+/  
  2. # from __future__ import print_function  
  3. from  numpy import *  
  4. import operator#运算符模块  
  5. import matplotlib.pyplot as plt  
  6. def createDataSet():  
  7.     group = array([[1.0,1.1],[1.0,1.0],[0,0],[00.1]])  
  8.     labels = ['A','A','B','B']  
  9.     return group,labels  
  10.   
  11. group,labels=createDataSet()  
  12.   
  13. def classify0(inX, dataSet, labels, k): #inX: 待测试数据 ;  dataSet: 训练样本集;labels: 样本集的标签;k近邻  
  14.     dataSetSize = dataSet.shape[0]      #to get the rows of the matrix  
  15.     # to get the Xi-Yi of the dataSet  
  16.     diffMat = tile(inX, (dataSetSize,1)) - dataSet      #a=[1 2],b=[2 3];tile(a,b) to generate 2*3 matrix when  
  17.                                                         #the element all is a [1 2]  
  18.     sqDiffMat = diffMat**2  
  19.     sqDistances = sqDiffMat.sum(axis=1)         #使每行的元素相加,得到测试样本与各训练样本distance**2  
  20.                                                 #axis=0,按列相加;axis=1,按行相加;  
  21.     distances = sqDistances**0.5  
  22.     sortedDistIndicies = distances.argsort()    #将distance中的元素从小到大排列,  
  23.                                                 # 提取其对应的index(索引),然后输出到 sortedDistIndicies  
  24.    #声明一个dict:{key:value1,key2:value2}  
  25.     classCount={}  
  26.     for i in range(k):  
  27.         voteIlabel = labels[sortedDistIndicies[i]]  
  28.         #classCount= {'B': 2, 'A': 1},初始化后,classCount每得到一个相同的voteIlabel,就+1  
  29.         classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1       #当我们获取字典里的值的时候,一个是通过  
  30.                                                                         # 键值对,即dict['key'],另一个就是dict.get()方法  
  31.                                                                         # dict.get(voteIlabel,0) = 0, 此处0 to be initiated,  
  32.                                                                         #  之后就没有作用了。  
  33.     #items方法是可以将字典中的所有项,以列表方式返回。 iteritems方法与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器  
  34.     #Python3 中没有iteritems函数,需要用values()代替,并用list转为列表  
  35.     # sortedClassCount = sorted((key_label, value_num), key=operator.itemgetter(1), reverse=True)  
  36.     #python3中无法使用iteritems,需要对上面这句话改造,我们通过得到两个list,得到出现频率最高的label  
  37.     key_label=list(classCount.keys())  
  38.     value_num=list(classCount.values())  
  39.     #label出现频率由小到大排列,并返回索引index  
  40.     sortedvalue_num_indicies = argsort(value_num)  
  41.     #返回频率最大的label  
  42.     return key_label[len(sortedvalue_num_indicies)-1]  
  43.   
  44. # group,labels = createDataSet()  
  45. # a=classify0([0,0], group,labels,3)  
  46. # print(a)  
  47.   
  48. #自己根据Python3 改正后的函数  
  49. def file2matrix(filename): # 将数据分离为样本数据与标签  
  50.     #open a file, default: 'r'ead  
  51.     fr = open(filename)  
  52.     #一次读取所有行  
  53.     arrayOLines = fr.readlines()  
  54.     #得到行数  
  55.     numberOfLines = len(arrayOLines)  
  56.     #1000*3 zeros matrix,row-1000, column-3  
  57.     returnMat = zeros((numberOfLines,3))  
  58.     #声明  
  59.     classLabelVector = []  
  60.     classLabelVector_Value = []  
  61.     index = 0  
  62.     #逐行扫描  
  63.     for line in arrayOLines:  
  64.         #strip函数会删除头和尾的字符,中间的不会删除  
  65.         line = line.strip()  
  66.         #删除‘\t’字符,仅剩下数据,供使用  
  67.         listFromLine = line.split('\t')  
  68.         #得到前三列数据,即飞行时间,游戏,冰激凌  
  69.         returnMat[index, :] = listFromLine[0:3]  
  70.         #得到largeDoses,smallDoses,didntLike的label  
  71.         classLabelVector.append(listFromLine[-1])      #无法将largeDoses,smallDoses,didntLike  
  72.                                                        #转换为int。基于这个思想,我们在这里将得到的行矩阵建立  
  73.                                                        #一个数值矩阵与之对应,暂时这样处理,不合适再继续修改  
  74.         if classLabelVector[index] == 'largeDoses':  
  75.             classLabelVector_Value.append(3)  
  76.         elif classLabelVector[index] == 'smallDoses':  
  77.             classLabelVector_Value.append(2)  
  78.         else:  
  79.             classLabelVector_Value.append(1)  
  80.         index += 1  
  81.     return returnMat, classLabelVector_Value  
  82. # def file2matrix(filename):  
  83. #     fr = open(filename)  
  84. #     numberOfLines = len(fr.readlines())         #get the number of lines in the file  
  85. #     returnMat = zeros((numberOfLines,3))        #prepare matrix to return  
  86. #     classLabelVector = []                       #prepare labels return  
  87. #     fr = open(filename)  
  88. #     index = 0  
  89. #     for line in fr.readlines():  
  90. #         line = line.strip()  
  91. #         listFromLine = line.split('\t')  
  92. #         returnMat[index,:] = listFromLine[0:3]  
  93. #         classLabelVector.append(int(listFromLine[-1]))  
  94. #         index += 1  
  95. #     return returnMat,classLabelVector  
  96. def autoNorm(dataSet):#得到归一化后的数据样本,最大值最小值之差,与最小值  
  97.     #得到每一列的max,min  
  98.     minVals = dataSet.min(0)  
  99.     maxVals = dataSet.max(0)  
  100.     ranges = maxVals - minVals  
  101.     #initiate a zero-matrix like dataSet's shape  
  102.     normDataSet = zeros(shape(dataSet))  
  103.     #get the num of row in dataSet  
  104.     m = dataSet.shape[0]  
  105.     #init a matrix of minvals that the same rows to the dataSet, 从而使当前数据矩阵中的每个数减去最小值  
  106.     normDataSet = dataSet - tile(minVals, (m,1))        #tile(matrixlike,A) :init a matrix when the shape is same to A  
  107.                                                         #meanwhile, if A is a number, the matrix is A*1, if A is (m,n),the matrix  
  108.                                                         #is m*n matrix  
  109.     normDataSet = normDataSet/tile(ranges, (m,1))      #element wise divide  
  110.     return normDataSet, ranges, minVals  
  111.   
  112.   
  113. def datingClassTest():  
  114.     #使用10%的数据去测试分类器  
  115.     hoRatio = 0.10  # hold out 10%  
  116.     #datingTestSet2.txt中标签全部变为3,2,1,而不是字符串label,所以如果不想改file2matrix()函数,应用datingTestSet.txt  
  117.     #如果file2matrix()用书中原程序,可用datingTestSet.txt  
  118.     datingDataMat, datingLabels = file2matrix('datingTestSet.txt')  # 将数据分离为样本数据与标签  
  119.     normMat, ranges, minVals = autoNorm(datingDataMat)#得到归一化后的数据样本,最大值最小值之差,与最小值  
  120.     #get the num of the row  
  121.     m = normMat.shape[0]  
  122.     #get the test num of normMat  
  123.     numTestVecs = int(m * hoRatio)  
  124.     errorCount = 0.0  
  125.     for i in range(numTestVecs):  
  126.         #数据前numTestVecs个为测试数据,以后为样本训练集  
  127.         classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3)  # inX: 待测试数据 ;  dataSet: 训练样本集;labels: 样本集的标签;k近邻  
  128.         #测试结果与真正结果对照输出  
  129.         print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i]))  
  130.         if classifierResult != datingLabels[i]:  
  131.             errorCount += 1.0  
  132.     print("the total error rate is: %f"% (errorCount / float(numTestVecs)))  
  133.     print(errorCount)  
  134.   
  135. def classifyPerson():  
  136.     resultList = ['not at all','in small doses','in large doses']  
  137.     percentTats = float(input(\  
  138.         "percentage of time spent playing video games?"))  
  139.     ffMiles = float(input(\  
  140.         "frequent flier miles earned per year? "))  
  141.     iceCream = float(input(\  
  142.         "liters of ice cream consumed per year?"))  
  143.     datingDataMat,datingLabels = file2matrix('datingTestSet.txt')  
  144.     normMat, ranges, minVals = autoNorm(datingDataMat)  
  145.     inArr = array([ffMiles, percentTats, iceCream])  
  146.     clssifierResult = classify0((inArr-minVals)/ranges,\  
  147.                                 normMat,datingLabels,3)  
  148.     print("You will probably like this person:",\  
  149.           resultList[clssifierResult-1])  

测试

[python]  view plain  copy
  1. classifyPerson()  

完成!


#####################################

转自:https://blog.csdn.net/shunquanlan9446/article/details/79778086

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值