import math import operator def euclideanDistance(inst1,inst2,length): distance=0 for x in range(length): distance+=pow((inst1[x]-inst2[x]),2) return math.sqrt(distance) def getNeightbors(trainningSet,testInstance,k): distances=[] length=len(testInstance)-1 for x in range(len(trainingSet)): dist=euclideanDistance(testInstance,trainingSet[x],length) distances.append((trainningSet[x],dist)) distances.sort(key=operator.itemgetter(1)) neighbors=[] for x in range(k): neighbors.append(distances[x][0]) return neighbors def getResponse(neighbors): classvotes={}#定义字典 for x in range(len(neighbors)): response=neighbors[x][-1] if response in classvotes: classvotes[response]+=1 else: classvotes[response]=1 sortedvotes=sorted(classvotes.items(),key=operator.itemgetter(1),reverse=True) return sortedvotes[0][0] trainingSet=[[1,1,1,'a'],[2,2,2,'a'],[1,1,3,'a'],[4,4,4,'b'],[0,0,0,'a'],[4,4.5,4,'b']] testInstance=[5,5,5] k=5 neighbors=getNeightbors(trainingSet,testInstance,k) response=getResponse(neighbors) print(neighbors) print(response)
python knn分类算法
最新推荐文章于 2022-11-05 21:41:28 发布