1. 程式人生 > >深度學習cs231n之knn學習的一些記錄(2)

深度學習cs231n之knn學習的一些記錄(2)

防止在上篇文章上的修改產生覆蓋,我這裡就直接重啟一篇。繼續寫 當前在knn.ipynb 裡面的box 15

Now implement the function. predict_labels and run the code below: 現在執行classifier.predict_labels 這個函式。執行下面的程式碼來預測labels we use k = 1 (which is Nearest Neighbor)

y_test_pred = classifier.predict_labels(dists, k=1)

這個函式的實現同樣在cs231n/classifiers裡面的k_nearest_neighbor.py中。

from collections import Counter
def predict_labels(self, dists, k=1):
	"""
	Given a matrix of distances between test points and training points, 
	predict a label for each test point.
	給一個test點和train點之間歐式距離的矩陣,來為每一個test點預測一個label.
	Inputs:
	- dists: A numpy array of shape(num_test, num_train) where dists[i, j] gives the distance between 
	the ith test point and the jth training point.
	dists 就是上一篇文章裡面 compute_distances_two_loops的結果。
	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]. 
	返回的結果也是一個numpy陣列,shape為(num_test, ) 裡面是test data 的預測labels. y[i] 是對test point x[i] 的預測label.
	"""
num_test = dists.shape[0] y_pred = np.zeros(num_test) # 這個是要返回的結果。 for i in range(num_test): dists_i = dists[i] # 這裡其實是取出了針對預測圖片的一行的資料。5000大小的陣列。 closest_y = self.y_train[dists_i.argsort()[:k]] # argsort 會返回當前陣列排序的下標,這裡預設會把self.y_train裡面最小的前k給取出來。 y_pred[i] = Counter(closest_y).most_common(1
)[0][0] # 然後對返回的最小的陣列進行計數,Counter 就是投票,通過counter的most common 方法得到出現最多的label. return y_pred

argsort 舉例

>>> import numpy as np
>>> a = np.array([1, 3, 2])
>>> a.argsort()
array([0, 2, 1])
>>> a[a.argsort()[:1]]
array([1])
>>> a[a.argsort()[:2]]
array([1, 2])
>>> a[a.argsort()[:3]]
array([1, 2, 3])