机器学习实战笔记四_Python3

程序清单2-3,归一化特征值

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

该程序没什么难点,主要是公式的矩阵化处理,先上伪代码:

[python]  view plain  copy
  1. def autoNorm(dataSet):  
  2.     #得到每一列的max,min  
  3.     minVals = dataSet.min(0)  
  4.     maxVals = dataSet.max(0)  
  5.     ranges = maxVals - minVals  
  6.     #initiate a zero-matrix like dataSet's shape  
  7.     normDataSet = zeros(shape(dataSet))  
  8.     #get the num of row in dataSet  
  9.     m = dataSet.shape[0]  
  10.     #init a matrix of minvals that the same rows to the dataSet, 从而使当前数据矩阵中的每个数减去最小值  
  11.     normDataSet = dataSet - tile(minVals, (m,1))        #tile(matrixlike,A) :init a matrix when the shape is same to A  
  12.                                                         #meanwhile, if A is a number, the matrix is A*1, if A is (m,n),the matrix  
  13.                                                         #is m*n matrix  
  14.     normDataSet = normDataSet/tile(ranges, (m,1))      #element wise divide  
  15.     return normDataSet, ranges, minVals  

完整代码:

[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: 训练样本集  
  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. def file2matrix(filename):  
  49.     #open a file, default: 'r'ead  
  50.     fr = open(filename)  
  51.     #一次读取所有行  
  52.     arrayOLines = fr.readlines()  
  53.     #得到行数  
  54.     numberOfLines = len(arrayOLines)  
  55.     #1000*3 zeros matrix,row-1000, column-3  
  56.     returnMat = zeros((numberOfLines,3))  
  57.     #声明  
  58.     classLabelVector = []  
  59.     classLabelVector_Value = []  
  60.     index = 0  
  61.     #逐行扫描  
  62.     for line in arrayOLines:  
  63.         #strip函数会删除头和尾的字符,中间的不会删除  
  64.         line = line.strip()  
  65.         #删除‘\t’字符,仅剩下数据,供使用  
  66.         listFromLine = line.split('\t')  
  67.         #得到前三列数据,即飞行时间,游戏,冰激凌  
  68.         returnMat[index, :] = listFromLine[0:3]  
  69.         #得到largeDoses,smallDoses,didntLike的label  
  70.         classLabelVector.append(listFromLine[-1])      #无法将largeDoses,smallDoses,didntLike  
  71.                                                        #转换为int。基于这个思想,我们在这里将得到的行矩阵建立  
  72.                                                        #一个数值矩阵与之对应,暂时这样处理,不合适再继续修改  
  73.         if classLabelVector[index] == 'largeDoses':  
  74.             classLabelVector_Value.append(3)  
  75.         elif classLabelVector[index] == 'smallDoses':  
  76.             classLabelVector_Value.append(2)  
  77.         else:  
  78.             classLabelVector_Value.append(1)  
  79.         index += 1  
  80.     return returnMat, classLabelVector_Value  
  81.   
  82. def autoNorm(dataSet):  
  83.     #得到每一列的max,min  
  84.     minVals = dataSet.min(0)  
  85.     maxVals = dataSet.max(0)  
  86.     ranges = maxVals - minVals  
  87.     #initiate a zero-matrix like dataSet's shape  
  88.     normDataSet = zeros(shape(dataSet))  
  89.     #get the num of row in dataSet  
  90.     m = dataSet.shape[0]  
  91.     #init a matrix of minvals that the same rows to the dataSet, 从而使当前数据矩阵中的每个数减去最小值  
  92.     normDataSet = dataSet - tile(minVals, (m,1))        #tile(matrixlike,A) :init a matrix when the shape is same to A  
  93.                                                         #meanwhile, if A is a number, the matrix is A*1, if A is (m,n),the matrix  
  94.                                                         #is m*n matrix  
  95.     normDataSet = normDataSet/tile(ranges, (m,1))      #element wise divide  
  96.     return normDataSet, ranges, minVals  

程序验证:

[python]  view plain  copy
  1. datingDataMat,datingLabels = file2matrix('datingTestSet.txt')  
  2. a,b,c = autoNorm(datingDataMat)  
  3. print(a)  
  4. print(b)  
  5. print(c)  

任务达成!

[python]  view plain  copy
  1. [[0.44832535 0.39805139 0.56233353]  
  2.  [0.15873259 0.34195467 0.98724416]  
  3.  [0.28542943 0.06892523 0.47449629]  
  4.  ...  
  5.  [0.29115949 0.50910294 0.51079493]  
  6.  [0.52711097 0.43665451 0.4290048 ]  
  7.  [0.47940793 0.3768091  0.78571804]]  
  8. [9.1273000e+04 2.0919349e+01 1.6943610e+00]  
  9. [0.       0.       0.001156]  
  10.   
  11. Process finished with exit code 0    

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值