|
| 1 | +from builtins import range |
| 2 | +from builtins import object |
| 3 | +import numpy as np |
| 4 | +from past.builtins import xrange |
| 5 | + |
| 6 | + |
| 7 | +class KNearestNeighbor(object): |
| 8 | + """ a kNN classifier with L2 distance """ |
| 9 | + |
| 10 | + def __init__(self): |
| 11 | + pass |
| 12 | + |
| 13 | + def train(self, X, y): |
| 14 | + """ |
| 15 | + Train the classifier. For k-nearest neighbors this is just |
| 16 | + memorizing the training data. |
| 17 | +
|
| 18 | + Inputs: |
| 19 | + - X: A numpy array of shape (num_train, D) containing the training data |
| 20 | + consisting of num_train samples each of dimension D. |
| 21 | + - y: A numpy array of shape (N,) containing the training labels, where |
| 22 | + y[i] is the label for X[i]. |
| 23 | + """ |
| 24 | + self.X_train = X |
| 25 | + self.y_train = y |
| 26 | + |
| 27 | + def predict(self, X, k=1, num_loops=0): |
| 28 | + """ |
| 29 | + Predict labels for test data using this classifier. |
| 30 | +
|
| 31 | + Inputs: |
| 32 | + - X: A numpy array of shape (num_test, D) containing test data consisting |
| 33 | + of num_test samples each of dimension D. |
| 34 | + - k: The number of nearest neighbors that vote for the predicted labels. |
| 35 | + - num_loops: Determines which implementation to use to compute distances |
| 36 | + between training points and testing points. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + - y: A numpy array of shape (num_test,) containing predicted labels for the |
| 40 | + test data, where y[i] is the predicted label for the test point X[i]. |
| 41 | + """ |
| 42 | + if num_loops == 0: |
| 43 | + dists = self.compute_distances_no_loops(X) |
| 44 | + elif num_loops == 1: |
| 45 | + dists = self.compute_distances_one_loop(X) |
| 46 | + elif num_loops == 2: |
| 47 | + dists = self.compute_distances_two_loops(X) |
| 48 | + else: |
| 49 | + raise ValueError('Invalid value %d for num_loops' % num_loops) |
| 50 | + |
| 51 | + return self.predict_labels(dists, k=k) |
| 52 | + |
| 53 | + def compute_distances_two_loops(self, X): |
| 54 | + """ |
| 55 | + Compute the distance between each test point in X and each training point |
| 56 | + in self.X_train using a nested loop over both the training data and the |
| 57 | + test data. |
| 58 | +
|
| 59 | + Inputs: |
| 60 | + - X: A numpy array of shape (num_test, D) containing test data. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + - dists: A numpy array of shape (num_test, num_train) where dists[i, j] |
| 64 | + is the Euclidean distance between the ith test point and the jth training |
| 65 | + point. |
| 66 | + """ |
| 67 | + num_test = X.shape[0] |
| 68 | + num_train = self.X_train.shape[0] |
| 69 | + dists = np.zeros((num_test, num_train)) |
| 70 | + for i in range(num_test): |
| 71 | + for j in range(num_train): |
| 72 | + ##################################################################### |
| 73 | + # TODO: # |
| 74 | + # Compute the l2 distance between the ith test point and the jth # |
| 75 | + # training point, and store the result in dists[i, j]. You should # |
| 76 | + # not use a loop over dimension, nor use np.linalg.norm(). # |
| 77 | + ##################################################################### |
| 78 | + # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 79 | + |
| 80 | + distance_ij = np.square(X[i] - self.X_train[j]) |
| 81 | + distance_ij = np.sqrt(np.sum(distance_ij)) |
| 82 | + |
| 83 | + dists[i, j] = distance_ij |
| 84 | + |
| 85 | + # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 86 | + return dists |
| 87 | + |
| 88 | + def compute_distances_one_loop(self, X): |
| 89 | + """ |
| 90 | + Compute the distance between each test point in X and each training point |
| 91 | + in self.X_train using a single loop over the test data. |
| 92 | +
|
| 93 | + Input / Output: Same as compute_distances_two_loops |
| 94 | + """ |
| 95 | + num_test = X.shape[0] |
| 96 | + num_train = self.X_train.shape[0] |
| 97 | + dists = np.zeros((num_test, num_train)) |
| 98 | + for i in range(num_test): |
| 99 | + ####################################################################### |
| 100 | + # TODO: # |
| 101 | + # Compute the l2 distance between the ith test point and all training # |
| 102 | + # points, and store the result in dists[i, :]. # |
| 103 | + # Do not use np.linalg.norm(). # |
| 104 | + ####################################################################### |
| 105 | + # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 106 | + |
| 107 | + dists[i, :] = np.sqrt(np.sum(np.square(X[i] - self.X_train), axis=1)) |
| 108 | + |
| 109 | + # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 110 | + return dists |
| 111 | + |
| 112 | + def compute_distances_no_loops(self, X): |
| 113 | + """ |
| 114 | + Compute the distance between each test point in X and each training point |
| 115 | + in self.X_train using no explicit loops. |
| 116 | +
|
| 117 | + Input / Output: Same as compute_distances_two_loops |
| 118 | + """ |
| 119 | + num_test = X.shape[0] |
| 120 | + num_train = self.X_train.shape[0] |
| 121 | + dists = np.zeros((num_test, num_train)) |
| 122 | + ######################################################################### |
| 123 | + # TODO: # |
| 124 | + # Compute the l2 distance between all test points and all training # |
| 125 | + # points without using any explicit loops, and store the result in # |
| 126 | + # dists. # |
| 127 | + # # |
| 128 | + # You should implement this function using only basic array operations; # |
| 129 | + # in particular you should not use functions from scipy, # |
| 130 | + # nor use np.linalg.norm(). # |
| 131 | + # # |
| 132 | + # HINT: Try to formulate the l2 distance using matrix multiplication # |
| 133 | + # and two broadcast sums. # |
| 134 | + ######################################################################### |
| 135 | + # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 136 | + |
| 137 | + train_matrix_tr = self.X_train.T |
| 138 | + |
| 139 | + sum_1 = np.sum(np.square(X), axis=1) |
| 140 | + sum_1 = sum_1.reshape((-1, sum_1.size)).T |
| 141 | + |
| 142 | + sum_2 = np.sum(np.square(train_matrix_tr), axis=0) |
| 143 | + |
| 144 | + dists = -2 * X.dot(train_matrix_tr) + sum_1 + sum_2 |
| 145 | + dists = np.sqrt(dists) |
| 146 | + |
| 147 | + # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 148 | + return dists |
| 149 | + |
| 150 | + def predict_labels(self, dists, k=1): |
| 151 | + """ |
| 152 | + Given a matrix of distances between test points and training points, |
| 153 | + predict a label for each test point. |
| 154 | +
|
| 155 | + Inputs: |
| 156 | + - dists: A numpy array of shape (num_test, num_train) where dists[i, j] |
| 157 | + gives the distance betwen the ith test point and the jth training point. |
| 158 | +
|
| 159 | + Returns: |
| 160 | + - y: A numpy array of shape (num_test,) containing predicted labels for the |
| 161 | + test data, where y[i] is the predicted label for the test point X[i]. |
| 162 | + """ |
| 163 | + num_test = dists.shape[0] |
| 164 | + y_pred = np.zeros(num_test) |
| 165 | + for i in range(num_test): |
| 166 | + # A list of length k storing the labels of the k nearest neighbors to |
| 167 | + # the ith test point. |
| 168 | + closest_y = [] |
| 169 | + ######################################################################### |
| 170 | + # TODO: # |
| 171 | + # Use the distance matrix to find the k nearest neighbors of the ith # |
| 172 | + # testing point, and use self.y_train to find the labels of these # |
| 173 | + # neighbors. Store these labels in closest_y. # |
| 174 | + # Hint: Look up the function numpy.argsort. # |
| 175 | + ######################################################################### |
| 176 | + # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 177 | + |
| 178 | + closet_indexes = np.argsort(dists[i]) |
| 179 | + closet_indexes = closet_indexes[:k] |
| 180 | + |
| 181 | + closest_y = self.y_train.take(closet_indexes) |
| 182 | + |
| 183 | + # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 184 | + ######################################################################### |
| 185 | + # TODO: # |
| 186 | + # Now that you have found the labels of the k nearest neighbors, you # |
| 187 | + # need to find the most common label in the list closest_y of labels. # |
| 188 | + # Store this label in y_pred[i]. Break ties by choosing the smaller # |
| 189 | + # label. # |
| 190 | + ######################################################################### |
| 191 | + # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 192 | + |
| 193 | + y_pred[i] = np.bincount(closest_y).argmax() |
| 194 | + |
| 195 | + # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** |
| 196 | + |
| 197 | + return y_pred |
0 commit comments