uzh-rpg/rpg_feature_tracking_analysis

How to mitigate this indexerror: index 8309 is out of bounds for axis 0 with size 8000?

qyum opened this issue · 0 comments

qyum commented

Here is my code:

class KNearestNeighbor(object):
    def __init__(self):
        pass
    def train(self, X, y):
        self.X_train = X
        self.y_train = y
    def predict(self, X, k=1, num_loops=0):
        if num_loops == 0:
            dists = self.compute_distances(X)
        else:
            raise ValueError('Invalid value %d for num_loops' % num_loops)
        return self.predict_labels(dists, k=k)


    def compute_distances(self, X):
        num_test = X.shape[0]
        num_train = self.X_train.shape[0]
        dists = np.zeros((num_test, num_train)) 
        dists = np.sqrt(np.sum(np.square(self.X_train), axis=1) + np.sum(np.square(X), axis=1)[:, np.newaxis] - 2 * np.dot(X, self.X_train.T))
        pass
        return dists

    def predict_labels(self, dists, k=1):
        num_test = dists.shape[0]
        y_pred = np.zeros(num_test)
        for i in range(num_test):
            closest_y = []
            sorted_dist = np.argsort(dists[i])
            
           closest_y = list(self.y_train[sorted_dist[0:k]])
           pass   
         
            y_pred[i]= (np.argmax(np.bincount(closest_y)))
           pass
             
        return y_pred

classifier = KNearestNeighbor()
classifier.train(x_train_f, y_train)
#for task_1
y_pred = classifier.predict(x_test_f,k=10)
num_correct = np.sum(y_pred == y_test)
accuracy = float(num_correct)/n_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, n_test, accuracy))

Error that I found:

  IndexError                                Traceback (most recent call last)
  <ipython-input-26-b60bc0c18c8e> in <module>()
        6 #for task_1
        7 
  ----> 8 y_pred = classifier.predict(x_test_f,k=10)
        9 num_correct = np.sum(y_pred == y_test)
       10 accuracy = float(num_correct)/1000
  
  1 frames
  <ipython-input-21-6587aed220d9> in predict_labels(self, dists, k)
       29             sorted_dist = np.argsort(dists[i])
       30 
  ---> 31             closest_y = list(self.y_train[sorted_dist[0:k]])
       32 
       33             pass
  
  IndexError: index 8309 is out of bounds for axis 0 with size 8000