Sum of root of difference squared

Question:

I am trying to figure out a formula in a code that I am trying to run. Can you help me to know what they are trying to measure here? it seems a kind of evaluation metric that is similar to Euclidean distance but with minor changes. I searched online but no luck

print ("%f"%np.sum(np.sqrt((matrix1-matrix2)**2)))
Asked By: saad

||

Answers:

It is computing the sum of the Euclidean distances between all of the items in the matrices/vectors matrix1 and matrix2.

This code is generic code that gets the Euclidean distance between two matrices:

np.sqrt((matrix1-matrix2)**2)

And then, at the end, the distances are summed up via np.sum.

Here is an example which demonstrates how it works:

matrix1 = np.array([1, 2, 3, 4, 5])
matrix2 = np.array([2, 4, 6, 8, 10])
subtracted = matrix1-matrix2 # result: [-1 -2 -3 -4 -5]
squared = subtracted**2 # result: [ 1  4  9 16 25]
rooted = squared ** 0.5 # result: [1. 2. 3. 4. 5.]
summed = np.sum(rooted) # result: 15.0
print(summed) # output: 15.0

When you are confused by some code and aren’t sure what it’s doing, it’s really helpful to break it up into steps like that, then step through each one in a debugger (or just print the results for each line of code). You can much more easily tell what’s going on with code when you play around with it in a test script, generally.

Answered By: Random Davis