Numpy: Single loop vectorized code slow compared to two loop iteration
问题 The following codes iterates over each element of two array to compute pairwise euclidean distance. def compute_distances_two_loops(X, Y): num_test = X.shape[0] num_train = Y.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): for j in range(num_train): dists[i][j] = np.sqrt(np.sum((X[i] - Y[j])**2)) return dists The following code serves the same purpose but with single loop. def compute_distances_one_loop(X, Y): num_test = X.shape[0] num_train = Y.shape[0] dists = np