Skip to content

Instantly share code, notes, and snippets.

@PhanDuc
Created February 11, 2018 20:32
Show Gist options
  • Save PhanDuc/fb897bde0e20f1bd83842b0035c7cf29 to your computer and use it in GitHub Desktop.
Save PhanDuc/fb897bde0e20f1bd83842b0035c7cf29 to your computer and use it in GitHub Desktop.
def nearest_neighbours(X, Y, norm=2.0):
"""Index the rows of `Y` in increasing order of distance from each row in `X`.
Parameters
----------
X : array, 2 dimensional, shape = (n_samples, n_dim)
The matrix, for the rows of which to find the closest row in `Y`.
Y : array, 2 dimensional, shape = (n_reference, n_dim)
The matrix, among the rows of which to seek the closest one for `X`.
norm : float, positive
The order of the l^p norm to use for computing the pairwise distances.
Returns
-------
index : 2 dimensional
The matrix of indices of the rows of `Y` for each vector in `X`
in increasing order of distnace with respect to the l^p norm.
"""
assert X.ndim == Y.ndim and X.ndim == 2
### BEGIN Solution
indixesY = list(range(0, Y.shape[0]))
def myfunction(x):
return list(map(lambda y_i: np.linalg.norm(x - Y[y_i,:], ord=norm), indixesY))
out = np.argsort(np.apply_along_axis(myfunction, axis=1, arr=X))
### END Solution
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment