python-kNN

xiaoxiao2021-02-28  55

from numpy import * #引入科学计算包 import operator #经典python库 运算符模块#创建数据集 def CreatDataSet(): group = array([[1.0, 1.1],[1.0,1.0],[0,0],[0,0.1]]) labels = ['A','A','B','B'] return group,labels ''' inX:用于分类的输入向量 dataSet:输入的训练样本集 labels :标签向量 k:用于选择最近邻居的数目 其中,标签向量的元素数目和矩阵dataSet的行数相同 ''' def classify0(inX,dataSet,labels,k): #计算距离 dataSetSize = dataSet.shape[0] #得到数组的行数,即知道有几个训练数据 #tile函数位于python模块 numpy.lib.shape_base中,他的功能是重复某个数组。 # 比如tile(A,n),功能是将数组A重复n次,构成一个新的数组 diffMat = tile(inX,(dataSetSize,1)) - dataSet #diffMat得到了目标与训练数组的差值 sqDiffMat = diffMat ** 2 #各个元素分别平方 sqDistances = sqDiffMat.sum(axis = 1) #对应列相乘,即得到了每一个距离的平方?? distances = sqDistances ** 0.5 #开方得到距离 sortedDistIndicies = distances.argsort() #升序排列 #选择距离最小的k个点 classCount = {} for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 #排序 sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] import kNN group,labels = kNN.CreatDataSet() print(kNN.classify0([0,0],group,labels,3))

运行结果

(1)python中的矩阵运算

http://blog.csdn.net/taxueguilai1992/article/details/46581861

(2)argsort()

http://blog.csdn.net/yuan1125/article/details/69388446

http://blog.csdn.net/maoersong/article/details/21875705

(3)error:'dict' object has no attribute 'iteritems'

3.5以上iteritems为items

(4) diffMat = tile(inX,(dataSetSize,1)) - dataSet 

成员参数为什么是(dataSetSize,1)?

转载请注明原文地址: https://www.6miu.com/read-2629026.html

最新回复(0)