标签:create data label code created 1.2 png 统计 sha
from numpy import * import operator def createDataSet() : group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 1.1]]) labels = [‘A‘, ‘A‘, ‘B‘, ‘B‘] return group, labels ‘‘‘ tile(array, (intR, intC): 对矩阵进行组合,纵向复制intR次, 横向复制intC次 比如 : tile([1,2,3], (3, 2)) 输出 [ [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3] ] array减法, 两个 行列数相等的矩阵,对应位置做减法 argsort(array, axis) 对矩阵进行排序,axis=0 按列排序, axis=1 按行排序 输出的是排序的索引。比如输出[0,2,1], 排序结果结果为 array[0],array[2].array[1] aorted(iteratorItems, key, reverse) 对可迭代的对象进行排序 ‘‘‘ def classify0(intX, dataSet, labels, k) : # 假设输入 intX = [0, 0], dataSet = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 1.1]]), labels = [‘A‘, ‘A‘, ‘B‘, ‘B‘], k = 3 dataSetSize = dataSet.shape[0]; # 行数 dataSetSize = 4 diffMat = tile(intX, (dataSetSize, 1)) - dataSet # 矩阵差 diffMat = array([[-1.0, -1.1], [-1.0, -1.0], [0, 0], [0, -1.1]]) sqDiffMat = diffMat ** 2 # 平方 sqDiffMat = array([[1, 1.21], [1, 1], [0, 0], [0, 1.21]]) sqDistances = sqDiffMat.sum(axis=1) # 行和,axis=0时输出纵和 sqDistances = array([2.21, 2, 0, 1.21]) distances = sqDistances ** 0.5 # 开平方 distances = array([1.41, 1.48, 0, 1.1]) sortedDistIndicies = distances.argsort() # 排序 sortedDistIndicies = array([2, 3, 0, 1]) classCount = {} for i in range(k) : voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # {label:count}, 取距离最小的三个, 统计label出现的次数,最终 classCount = {‘B‘: 2, ‘A‘: 1} sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) # 对dict按照v值(distance)进行倒序排序 sortedClassCount = [(‘B‘, 2), (‘A‘, 1)] return sortedClassCount[0][0] # 返回第一个tuple的第一个值,也就是出现次数最高的label, 这里返回‘B’ if __name__ == "__main__": group, labels = createDataSet() classify0([0, 0], group, labels, 3)
标签:create data label code created 1.2 png 统计 sha
原文地址:https://www.cnblogs.com/yeyeck/p/9900908.html