程序清单2-3,归一化特征值
newValue = (oldValue -min)/(max - min)
该程序没什么难点,主要是公式的矩阵化处理,先上伪代码:
- def autoNorm(dataSet):
- #得到每一列的max,min
- minVals = dataSet.min(0)
- maxVals = dataSet.max(0)
- ranges = maxVals - minVals
- #initiate a zero-matrix like dataSet's shape
- normDataSet = zeros(shape(dataSet))
- #get the num of row in dataSet
- m = dataSet.shape[0]
- #init a matrix of minvals that the same rows to the dataSet, 从而使当前数据矩阵中的每个数减去最小值
- normDataSet = dataSet - tile(minVals, (m,1)) #tile(matrixlike,A) :init a matrix when the shape is same to A
- #meanwhile, if A is a number, the matrix is A*1, if A is (m,n),the matrix
- #is m*n matrix
- normDataSet = normDataSet/tile(ranges, (m,1)) #element wise divide
- return normDataSet, ranges, minVals
完整代码:
- #批量注释、批量取消注释 Ctrl+/
- # from __future__ import print_function
- from numpy import *
- import operator#运算符模块
- import matplotlib.pyplot as plt
- 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
- group,labels=createDataSet()
- def classify0(inX, dataSet, labels, k): #inX: 待测试数据 ; dataSet: 训练样本集
- dataSetSize = dataSet.shape[0] #to get the rows of the matrix
- # to get the Xi-Yi of the dataSet
- diffMat = tile(inX, (dataSetSize,1)) - dataSet #a=[1 2],b=[2 3];tile(a,b) to generate 2*3 matrix when
- #the element all is a [1 2]
- sqDiffMat = diffMat**2
- sqDistances = sqDiffMat.sum(axis=1) #使每行的元素相加,得到测试样本与各训练样本distance**2
- #axis=0,按列相加;axis=1,按行相加;
- distances = sqDistances**0.5
- sortedDistIndicies = distances.argsort() #将distance中的元素从小到大排列,
- # 提取其对应的index(索引),然后输出到 sortedDistIndicies
- #声明一个dict:{key:value1,key2:value2}
- classCount={}
- for i in range(k):
- voteIlabel = labels[sortedDistIndicies[i]]
- #classCount= {'B': 2, 'A': 1},初始化后,classCount每得到一个相同的voteIlabel,就+1
- classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 #当我们获取字典里的值的时候,一个是通过
- # 键值对,即dict['key'],另一个就是dict.get()方法
- # dict.get(voteIlabel,0) = 0, 此处0 to be initiated,
- # 之后就没有作用了。
- #items方法是可以将字典中的所有项,以列表方式返回。 iteritems方法与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器
- #Python3 中没有iteritems函数,需要用values()代替,并用list转为列表
- # sortedClassCount = sorted((key_label, value_num), key=operator.itemgetter(1), reverse=True)
- #python3中无法使用iteritems,需要对上面这句话改造,我们通过得到两个list,得到出现频率最高的label
- key_label=list(classCount.keys())
- value_num=list(classCount.values())
- #label出现频率由小到大排列,并返回索引index
- sortedvalue_num_indicies = argsort(value_num)
- #返回频率最大的label
- return key_label[len(sortedvalue_num_indicies)-1]
- # group,labels = createDataSet()
- # a=classify0([0,0], group,labels,3)
- # print(a)
- def file2matrix(filename):
- #open a file, default: 'r'ead
- fr = open(filename)
- #一次读取所有行
- arrayOLines = fr.readlines()
- #得到行数
- numberOfLines = len(arrayOLines)
- #1000*3 zeros matrix,row-1000, column-3
- returnMat = zeros((numberOfLines,3))
- #声明
- classLabelVector = []
- classLabelVector_Value = []
- index = 0
- #逐行扫描
- for line in arrayOLines:
- #strip函数会删除头和尾的字符,中间的不会删除
- line = line.strip()
- #删除‘\t’字符,仅剩下数据,供使用
- listFromLine = line.split('\t')
- #得到前三列数据,即飞行时间,游戏,冰激凌
- returnMat[index, :] = listFromLine[0:3]
- #得到largeDoses,smallDoses,didntLike的label
- classLabelVector.append(listFromLine[-1]) #无法将largeDoses,smallDoses,didntLike
- #转换为int。基于这个思想,我们在这里将得到的行矩阵建立
- #一个数值矩阵与之对应,暂时这样处理,不合适再继续修改
- if classLabelVector[index] == 'largeDoses':
- classLabelVector_Value.append(3)
- elif classLabelVector[index] == 'smallDoses':
- classLabelVector_Value.append(2)
- else:
- classLabelVector_Value.append(1)
- index += 1
- return returnMat, classLabelVector_Value
- def autoNorm(dataSet):
- #得到每一列的max,min
- minVals = dataSet.min(0)
- maxVals = dataSet.max(0)
- ranges = maxVals - minVals
- #initiate a zero-matrix like dataSet's shape
- normDataSet = zeros(shape(dataSet))
- #get the num of row in dataSet
- m = dataSet.shape[0]
- #init a matrix of minvals that the same rows to the dataSet, 从而使当前数据矩阵中的每个数减去最小值
- normDataSet = dataSet - tile(minVals, (m,1)) #tile(matrixlike,A) :init a matrix when the shape is same to A
- #meanwhile, if A is a number, the matrix is A*1, if A is (m,n),the matrix
- #is m*n matrix
- normDataSet = normDataSet/tile(ranges, (m,1)) #element wise divide
- return normDataSet, ranges, minVals
程序验证:
- datingDataMat,datingLabels = file2matrix('datingTestSet.txt')
- a,b,c = autoNorm(datingDataMat)
- print(a)
- print(b)
- print(c)
任务达成!
- [[0.44832535 0.39805139 0.56233353]
- [0.15873259 0.34195467 0.98724416]
- [0.28542943 0.06892523 0.47449629]
- ...
- [0.29115949 0.50910294 0.51079493]
- [0.52711097 0.43665451 0.4290048 ]
- [0.47940793 0.3768091 0.78571804]]
- [9.1273000e+04 2.0919349e+01 1.6943610e+00]
- [0. 0. 0.001156]
- Process finished with exit code 0
########################################
转自:https://blog.csdn.net/shunquanlan9446/article/details/79774051