lihang-code
lihang-code copied to clipboard
knn的 predict的优化
手动实现向量化的norm,应该通用性更好一些, 是否可行,请指正: def predict_leon(self, X): dist = np.power(X - self.X_train, self.p).sum(axis=1) dist = np.power(dist, 1 / self.p) knn = self.y_train[np.argsort(dist)[:self.n]]
# 统计
count_pairs = Counter(knn)
max_count = sorted(count_pairs.items(), key=lambda x: x[1])[-1][0]
return max_count
同样是这个问题, 原代码中 max_count = sorted(count_pairs.items(), key=lambda x: x[1])[-1][0] 可以直接用 max_count=count_pairs.most_common(1)[0][0] 代替