Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

knn compute_distances_one_loop

def compute_distances_one_loop(self, X):
    """
    Compute the distance between each test point in X and each training point
    in self.X_train using a single loop over the test data.

    Input / Output: Same as compute_distances_two_loops
    """
    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train))
    for i in range(num_test):
      # Note axis=1 computes norm along rows
      dists[i] = np.linalg.norm(X[i]-self.X_train, axis=1)

    return dists

Difference was: 0.000000
Good! The distance matrices are the same
Source by colab.research.google.com #
 
PREVIOUS NEXT
Tagged: #knn
ADD COMMENT
Topic
Name
1+1 =