Part 3: Implement knnclassifier [Graded]
Implement the function knnclassifier, which should perform k nearest neighbor classification on a given test data set. The call:
preds=knnclassifier(xTr,yTr,xTe,k)
should output the predictions for the data in xTe i.e. preds[i] will contain the prediction for xTe[i,:].
You may find it helpful to use flatten() in the implementation of this function. It will also be useful to refer back to the mode function you implemented in Additional NumPy Exercises.
def knnclassifier(xTr,yTr,xTe,k):
"""
function preds=knnclassifier(xTr,yTr,xTe,k);
k-nn classifier
Input:
xTr = nxd input matrix with n row-vectors of dimensionality d
xTe = mxd input matrix with m row-vectors of dimensionality d
k = number of nearest neighbors to be found
Output:
preds = predicted labels, ie preds(i) is the predicted label of xTe(i,:)
"""
# fix array shapes
yTr = yTr.flatten()
tup = findknn(xTr, xTe, k)
I = np.transpose(tup[0])
D = np.transpose(tup[1])
preds = []
for i in range(len(xTe)):
inds = I[i]
y = np.ndarray.flatten(yTr[inds])
m = mode(y)
preds.append(m)
preds = np.ndarray.flatten(np.array(preds))
return preds
# Run this self-test cell to check your code
def knn_classifier_test0():
# test if output is a numpy array, and of the right length
X = np.array([[1,0,0,1],[0,1,0,1]]).T
y = np.array([1,1,2,2])
preds=knnclassifier(X,y,X,1)
return type(preds)==np.ndarray and preds.shape==(4,)
def knn_classifier_test1():
X = np.array([[1,0,0,1],[0,1,0,1]]).T
y = np.array([1,1,2,2])
np.testing.assert_allclose(knnclassifier(X,y,X,1),y)
return np.testing.assert_allclose
def knn_classifier_test2():
X = np.array([[1,0,0,1],[0,1,0,1]]).T
y = np.array([1,1,2,2])
y2 = np.array([2,2,1,1])
return np.array_equal(knnclassifier(X,y,X,3),y2)