def knn(self, test_X = [], k = 3):
size = self.train_X.shape[0]
# Euclidean algorithm
diff = tile(test_X, (size, 1)) - self.train_X
dist_pow2 = diff ** 2
dist_sum = dist_pow2.sum(axis = 1)
dist_sqrt = dist_sum ** 0.5
dist = dist_sqrt.argsort()
# vote for neighbors
class_count = {}
for i in range(k):
vote_label = self.train_Y[dist[i]]
class_count[vote_label] = class_count.get(vote_label, 0) + 1
sorts = sorted(class_count.iteritems(), key = operator.itemgetter(1), reverse = True)
return sorts[0][0]
评论列表
文章目录