Params: -- matrix1: N1 x D -- matrix2: N2 x D Returns: -- dist: N1 x N2 dist[i, j] == distance(matrix1[i], matrix2[j])
(matrix1, matrix2)
| 4 | |
| 5 | # (X - X_train)*(X - X_train) = -2X*X_train + X*X + X_train*X_train |
| 6 | def euclidean_distance_matrix(matrix1, matrix2): |
| 7 | """ |
| 8 | Params: |
| 9 | -- matrix1: N1 x D |
| 10 | -- matrix2: N2 x D |
| 11 | Returns: |
| 12 | -- dist: N1 x N2 |
| 13 | dist[i, j] == distance(matrix1[i], matrix2[j]) |
| 14 | """ |
| 15 | assert matrix1.shape[1] == matrix2.shape[1] |
| 16 | d1 = -2 * np.dot(matrix1, matrix2.T) # shape (num_test, num_train) |
| 17 | d2 = np.sum(np.square(matrix1), axis=1, keepdims=True) # shape (num_test, 1) |
| 18 | d3 = np.sum(np.square(matrix2), axis=1) # shape (num_train, ) |
| 19 | dists = np.sqrt(d1 + d2 + d3) # broadcasting |
| 20 | return dists |
| 21 | |
| 22 | def calculate_top_k(mat, top_k): |
| 23 | size = mat.shape[0] |
no outgoing calls
no test coverage detected