import numpy as np def Calculate_distance(x:np.array,y:np.array,ty=2)->np.array: #计算距离 ty=2 欧式距离 ty=1 曼哈顿距离 ty>2闵科夫斯基距离 if x.shape != y.shape: raise Exception('length is not equal !') return np.sum(np.abs(x-y)**ty,axis=1)**(1/ty)
第二步,预测向量的属性值。
1 2 3 4 5 6 7 8 9 10 11 12
from collections import Counter def classify(inp:np.array,dataSet:np.array,label:list,k:int,ty=2): #k 近邻分类器 inp 为输入需要预测的向量,dataset为训练数据框, #label 为训练数据框的结果 k为取最近的数的个数 ty为计算距离方式。 #inp.shape=(n,),dataSet.shape=(m,n),len(label)=m if (inp.shape[0]!=dataSet.shape[1] or dataSet.shape[0] != len(label)): raise Exception('length is not equal !') source=np.tile(inp,(dataSet.shape[0],1)) distances=Calculate_distance(source,dataSet,ty=ty) index=distances.argsort(kind='quicksort')#快速升序排序,返回索引列表。 d=Counter([label[i] for i in index[:k]]) return max(d,key=d.get)