第1关:knn算法概述
import numpy as np
def topK(i,k,x,y):
'''
input:
i(int):第i个样本
k(int):最近邻样本个数
x(ndarray):数据特征
y(ndarray):数据标签
output:
topK(list):样本i的最近k个样本标签
'''
dis = np.sqrt(np.power(np.tile(x[i],(x.shape[0],1))-x,2).sum(axis=1))
est = np.argsort(dis)[1:k+1]
topK = [y[j] for j in est]
return topK
第2关:动手实现knn算法
import numpy as np
def knn_clf(k,train_feature,train_label,test_feature):
'''
input:
k(int):最近邻样本个数
train_feature(ndarray):训练样本特征
train_label(ndarray):训练样本标签
test_feature(ndarray):测试样本特征
output:
predict(ndarray):测试样本预测标签
'''
predict = np.zeros(test_feature.shape[0],).astype('int')
for i in range(test_feature.shape[0]):
distance = np.sqrt(np.power(np.tile(test_feature[i],(train_feature.shape[0],1))-train_feature,2).sum(axis=1))
distance_k = np.sort(distance)[:k]
nearest = np.argsort(distance)[:k]
topK = [train_label[i] for i in nearest]
votes = {}
max_count = 0
for j,label in enumerate(topK):
if label in votes.keys():
votes[label] += 1/(distance_k[j]+1e-10)
if votes[label] > max_count:
max_count = votes[label]
predict[i] = label
else:
votes[label] = 1/(distance_k[j]+1e-10)
if votes[label] > max_count:
max_count = votes[label]
predict[i] = label
return predict