简体   繁体   English

np.linalg.norm ord=2 不给出欧几里得范数

[英]np.linalg.norm ord=2 not giving Euclidean norm

I'm attempting to compute the Euclidean distance between two matricies which I would expect to be given by the square root of the element-wise sum of squared differences.我正在尝试计算两个矩阵之间的欧几里得距离,我希望它由元素平方差的平方和的平方根给出。

This seems to me to be exactly the calculation computed by numpy's linalg.norm function, however it doesn't appear to match my expected result.在我看来,这正是 numpy 的linalg.norm function 计算的结果,但它似乎与我的预期结果不符。

For example this code returns different values ( 5.385 vs 5.339 )例如,此代码返回不同的值( 5.385 vs 5.339

import numpy as np

a = np.arange(6).reshape(2, 3)
b = np.array([[1,2,3], [-1,1,4]])

print(np.sqrt(np.sum(np.square(a-b))))
print(np.linalg.norm(a-b, 2))

Have I misinterpreted the linalg.norm function?我是否误解了linalg.norm function? Why are the two above calculation methodologies not returning the same value?为什么上述两种计算方法没有返回相同的值?

From what I can see in the DocString of np.linalg.norm , it looks like for arrays with dim>2, it takes the largest singular value for ord=2 , meaning np.linalg.norm(a, ord=2) is the same as np.linalg.svd(a)[1].max() .从我在 np.linalg.norm 的np.linalg.norm中可以看到,对于 Dim>2 的 arrays 来说,它采用ord=2的最大奇异值,这意味着np.linalg.norm(a, ord=2)是与np.linalg.svd(a)[1].max()相同。 So in your case that's gonna be:所以在你的情况下,这将是:

print(np.sqrt(np.sum(np.square(a-b))))
print(np.linalg.norm(a-b, 2))
print(np.linalg.svd(a-b)[1].max())

And this will return 5.385 , 5.339 , 5.339 .这将返回5.3855.3395.339

The mathematical formulation is given on Wikipedia , where the distinction is made between 2-norm (which is ord=2 ) and Frobenius norm ( ord=None ). Wikipedia 上给出了数学公式,其中区分了 2 范数(即ord=2 )和 Frobenius 范数( ord=None )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM