#<GRADED> def l2distance(X,Z=None): """ function D=l2distance(X,Z) Computes the Euclidean distance matrix. Syntax: D=l2distance(X,Z) Input: X: nxd data matrix with n vectors (rows) of dimensionality d Z: mxd data matrix with m vectors (rows) of dimensionality d Output: Matrix D of size nxm D(i,j) is the Euclidean distance of X(i,:) and Z(j,:) call with only one input: l2distance(X)=l2distance(X,X) """ if Z is None: Z=X; n,d1=X.shape m,d2=Z.shape assert (d1==d2), "Dimensions of input vectors must match!" # Your code goes here .. raise NotImplementedError('Your code goes here!') return D # ... until here #</GRADED> without using for-loop
Question
#<GRADED> def l2distance(X,Z=None): """ function D=l2distance(X,Z)
Computes the Euclidean distance matrix.
Syntax:
D=l2distance(X,Z)
Input:
X: nxd data matrix with n vectors (rows) of dimensionality d
Z: mxd data matrix with m vectors (rows) of dimensionality d
Output:
Matrix D of size nxm
D(i,j) is the Euclidean distance of X(i,:) and Z(j,:)
call with only one input:
l2distance(X)=l2distance(X,X)
"""
if Z is None:
Z=X;
n,d1=X.shape
m,d2=Z.shape
assert (d1==d2), "Dimensions of input vectors must match!"
# Your code goes here ..
raise NotImplementedError('Your code goes here!')
return D
# ... until here
#</GRADED> without using for-loop
Solution
Sure, here's how you can implement the l2distance function without using a for loop:
import numpy as np
def l2distance(X, Z=None):
if Z is None:
Z = X
n, d1 = X.shape
m, d2 = Z.shape
assert (d1 == d2), "Dimensions of input vectors must match!"
# Compute the sum of squares for rows in X and Z
X_sq = np.sum(X**2, axis=1)
Z_sq = np.sum(Z**2, axis=1)
# Compute the dot product between rows in X and Z
XZ = np.dot(X, Z.T)
# Compute the Euclidean distance matrix
D = np.sqrt(X_sq[:, np.newaxis] + Z_sq - 2*XZ)
return D
In this implementation, we first check if Z is None and if so, we set Z = X. Then, we get the shapes of X and Z and check if their dimensions match.
Next, we compute the sum of squares for each row in X and Z. We also compute the dot product between rows in X and Z.
Finally, we compute the Euclidean distance matrix D using the formula sqrt(sum(X^2) + sum(Z^2) - 2*dot(X, Z)). This formula comes from the definition of the Euclidean distance and allows us to compute the distance matrix without using a for loop.
This implementation takes advantage of numpy's broadcasting and vectorized operations to compute the distance matrix efficiently.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.