def predict_labels(self, dists, k=1):
print("predict_labels")
"""
Given a matrix of distances between test points and training points,
predict a label for each test point.
Inputs:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
gives the distance betwen the ith test point and the jth training point.
Returns:
- y: A numpy array of shape (num_test,) containing predicted labels for the
test data, where y[i] is the predicted label for the test point X[i].
"""
num_test = dists.shape[0]
print(num_test)
y_pred = np.zeros(num_test)
for i in range(num_test):
closest_y = []
idx = np.argsort(dists[i])[:k]
closest_y = self.y_train[idx]
counter = np.zeros(np.max(self.y_train) + 1)
'''for j in closest_y:
counter[j] += 1'''
np.add.at(counter, closest_y, 1)
y_pred[i] = np.argmax(counter)
return y_pred```
开始感觉很难 其实知道后 很简单
|