Created
September 6, 2013 15:10
-
-
Save mgaitan/6465190 to your computer and use it in GitHub Desktop.
Computes the distance between m points using Euclidean distance (2-norm) as the distance metric between the points. The points are arranged as m n-dimensional row vectors in the matrix X.
This file contains 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(X): | |
""" | |
Computes the distance between m points using Euclidean distance (2-norm) | |
as the distance metric between the points. | |
The points are arranged as m n-dimensional row vectors in the matrix X. | |
""" | |
# agregamos una dimension. Ahora X.shape == (m, 1, n) | |
# Por ejemplo np.all(X[0] == X_dim_plus[0, 0]) | |
X_dim_plus = X[:, np.newaxis, :] | |
# elevamos los catetos de todos los puntos. genera una matriz de (m,m,n) | |
dist = (X_dim_plus - X)**2 | |
# aplanamos la matriz sumando la última dimension. Ahora será (m,m) | |
dist = np.sum(dist, axis=-1) | |
# y por ultimo calculamos su raiz cuadrada. | |
return np.sqrt(dist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment