Compute the L2 distance at once using matrices and vectors

543 Views Asked by At

I have to implement the L2 distance, which has the geometric interpretation of computing the euclidean distance between two vectors. The distance takes the form:

$$d_2(I_1,I_2)=\sqrt{\sum_{p} \left( I^p_1 - I^p_2 \right)^2}$$

If $I_1$ has a size of (50000 x 3072) and $I_2$ a size of (3072).

I have to implement that distance using Python with Numpy, and I don't have to use loops. I have to do it using only multiplication and two broadcasting sums.

My problem is that I don't know how multiplication and broadcasting sums can do it. Maybe using $I_2$ transpose and multiply it to $I_1$, but I'm only guessing.

Is there a way to get L2 distance using matrix multiplication?

UDPATE.

I think, but I'm not sure, I can use:

$$(x-y)^2=x^2+y^2-2xy$$

1

There are 1 best solutions below

0
On

If I1 has shape (50000 x 3072) and I2 has shape (3072):

temp = I1 - I2 # substract I2 from each vector in I1, temp has shape of (50000 x 3072)
temp = temp ** 2 # do a element-wise square. temp has shape of (50000 x 3072)
temp = temp.sum(1) # do a sum on the second dimension. temp now hasshape of (50000,).

Then temp is your L2 distance.