from numpy import * import operator def create_data_set(): # 训练集与标签 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 = create_data_set() def classify0(inX, data_set, labels, k): # inX 待分类向量 data_set训练集 labels标签向量 k最相近邻居的数目 # for 循环前步骤用于计算距离 距离公式:d = ((xA - xB)**2 + (yA - yB)**2)**0.5 data_set_size = data_set.shape[0] # 阵列的行数 diff_mat = tile(inX, (data_set_size, 1)) - data_set # 待分类向量 - 训练集中每行阵列 相当于计xA - xB,yA - yB sq_diff_mat = diff_mat ** 2 # 阵列平方,就是阵列每个对应数字平方 ,相当于将上一步的差平方(xA - xB)**2 sq_distances = sq_diff_mat.sum(axis=1) # 求和(xA - xB)**2 + (yA - yB)**2 distances = sq_distances ** 0.5 # 开方,得到距离 ((xA - xB)**2 + (yA - yB)**2)**0.5 sorted_dist_indicies = distances.argsort() # 根据距离从小到大排序排序,显示为对应索引 class_count = {} for i in range(k): # 选择距离最小的k个点 vote_ilabel = labels[sorted_dist_indicies[i]] # 从距离最近的开始取对应的索引,根据标签[索引]得到对应标签 class_count[vote_ilabel] = class_count.get(vote_ilabel, 0) + 1 # 字典中有该标签,则count+1,没有就新建 sorted_class_count = sorted(class_count.items(), key=operator.itemgetter(1), reverse=True) # 降序排序 return sorted_class_count print(classify0([0, 0], group, labels, 2))