Warm tip: This article is reproduced from serverfault.com, please click

Determining the Distance between two matrices using numpy

发布于 2020-11-28 00:09:18

I am developing my own Architecture Search algorithm using Pythons numpy. Currently I am trying to determine how to develop a cost function that can see the distance between X and Y, or two matrices. I'd like to reduce the difference between the two, to a meaningful scalar value.

Ideally between 0 and 1, so that if both sets of elements within the matrices are the same numerically and positionally, a 0 is returned.

In the example below, I have the output of my algorithm X. Both X and Y are the same shape. I tried to sum the difference between the two matrices; however I'm not sure that using summation will work in all conditions. I also tried returning the mean. I don't think that either approach will work though. Aside from looping through both matrices and comparing elements directly, is there a way to capture the degree of difference in a scalar?

Y = np.arange(25).reshape(5, 5)

for i in range(1000):
    X = algorithm(Y)
    
    # I try to reduce the difference between the two matrices to a scalar value
    cost = np.sum(X-Y)
Questioner
lazylama
Viewed
0
DYZ 2020-11-28 08:40:31

There are many ways to calculate a scalar "difference" between two matrices. Here are just two examples.

  1. The mean square error:

    ((m1 - m2) ** 2).mean() ** 0.5
    
  2. The max absolute error:

    np.abs(m1 - m2).max()
    

The choice of the metric depends on your problem.