Last active
May 3, 2020 16:25
-
-
Save dboyliao/bfb929f1c8e4028747d4448453433a29 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def distance_vec(X): | |
# (x - y)^2 = x^2 + y^2 - 2xy | |
prod = -2 * X.dot(X.T) | |
sq = (X ** 2).sum(axis=-1) | |
return sq + sq[:, None] + prod |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def distance_vec_v2(X): | |
# Thanks to Peter Cheng | |
diff = X[:, None, :] - X[None, :, :] | |
return (diff ** 2).sum(axis=-1) ** 0.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment