#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
author: Tiebiao Zhang 2021/11/2
"""
import operator
from numpy import array, tile
def createdataset():
group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
def classify0(inx, dataset, labels, k):
datasetsize = dataset.shape[0]
diffmat = tile(inx, (datasetsize, 1)) - dataset
sqdiffmat = diffmat ** 2
sqdistances = sqdiffmat.sum(axis=1)
distances = sqdistances ** 0.5
sorteddistindicies = distances.argsort() # argsort获得的是sort后的index
classcount = {}
for x in range(k):
voteilabel = labels[sorteddistindicies[x]]
classcount[voteilabel] = classcount.get(voteilabel, 0) + 1
sorteddistindicies = sorted(classcount.items(), key=operator.itemgetter(1), reverse=True) # operator.itemgetter(1) 获取对象的第1个域的值 reverse降序
return sorteddistindicies[0][0]
a, b = createdataset()
print(classify0([0, 0], a, b, 3))