Question: #Apply this method to the code below labels = ['brick', 'ball', 'cylinder'] random_integer = np.random.randint(low = 0, high = 3) return labels[random_integer] #to this code
|
#Apply this method to the code below | |
| labels = ['brick', 'ball', 'cylinder'] | |
| random_integer = np.random.randint(low = 0, high = 3) | |
| return labels[random_integer] |
#to this code
""" These images can be classified using K nearest neighbors In K nearest neighbor algorithm we just calculate the distance between the given image and all the training points. And then we will find the nearest training points which means the nearest labels. """
import numpy as np
labels = ['brick', 'ball', 'cylinder'] """ Brick = 0; ball = 1; cylinder = 2; """
class KNN(object): """ a kNN classifier with L2 distance """
def __init__(self): pass
def train(self, X, y): """Training is just easy we just store or memorize the data """ self.X_train = X self.y_train = y
def classify(self, X, k=1): """ Predicting the label using trained data """ distances = L2Distance(X)
return self.predictLabels(distances)
def L2Distance(self, X): #Computing distance between Test image and each training point num_test = X.shape[0] num_train = self.X_train.shape[0] dists = np.zeros((num_test, num_train))
dists = np.sqrt(np.sum(X**2, axis=1).reshape(num_test, 1) + np.sum(self.X_train**2, axis=1) - 2 * X.dot(self.X_train.T)) return dists
def predictLabels(self, dists, k=1): """ We found the distances using L2Distance now we need to find the nearest one to test image """ num_test = dists.shape[0] y_pred = np.zeros(num_test) for i in range(num_test):
closest_y = []
top_k_indx = np.argsort(dists[i])[:k] closest_y = self.y_train[top_k_indx] vote = Counter(closest_y) count = vote.most_common()
y_pred[i] = count[0][0] return y_pred
""" #See this to have a intuition about how to initialize knn classifer
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
label = classifier.classify(im)
if im ==0: out = "brick" elif(im==1): out = "ball" else: out = "cylinder" """
#code also showing errors:
def __init__(self): pass
def train(self, X, y):
#saying expected an indented block. please fix all debug errors.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
