knn.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:Machine-Learning 作者: grasses 项目源码 文件源码
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]
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号