Python NumPy 计算向量的范数 2 的平方

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35213592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:08:43  来源:igfitidea点击:

NumPy calculate square of norm 2 of vector

pythonnumpyinner-product

提问by Dubon

I have vector a.
I want to calculate np.inner(a, a)
But I wonder whether there is prettier way to calc it.

我有向量a
我想计算np.inner(a, a)
但我想知道是否有更漂亮的方法来计算它。

[The disadvantage of this way, that if I want to calculate it for a-bor a bit more complex expression, I have to do that with one more line. c = a - band np.inner(c, c)instead of somewhat(a - b)]

[这种方式的缺点是,如果我想计算它a-b或更复杂的表达式,我必须再用一行来完成。c = a - bnp.inner(c, c)不是somewhat(a - b)]

采纳答案by ali_m

Honestly there's probably not going to be anything faster than np.inneror np.dot. If you find intermediate variables annoying, you could always create a lambda function:

老实说,可能没有比np.inneror更快的了np.dot。如果你觉得中间变量很烦人,你总是可以创建一个 lambda 函数:

sqeuclidean = lambda x: np.inner(x, x)

np.innerand np.dotleverage BLAS routines, and will almost certainly be faster than standard elementwise multiplication followed by summation.

np.innernp.dot利用 BLAS 例程,几乎肯定会比标准的元素乘法和求和更快。

In [1]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)
((a - b) ** 2).sum()
   ....: 
The slowest run took 36.13 times longer than the fastest. This could mean that an intermediate result is being cached 
1 loops, best of 100: 6.45 ms per loop

In [2]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)                                                                                                                                                                              
np.linalg.norm(a - b, ord=2) ** 2
   ....: 
1 loops, best of 100: 2.74 ms per loop

In [3]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)
sqeuclidean(a - b)
   ....: 
1 loops, best of 100: 2.64 ms per loop

np.linalg.norm(..., ord=2)uses np.dotinternally, and gives very similar performance to using np.innerdirectly.

np.linalg.norm(..., ord=2)np.dot内部使用,并提供与np.inner直接使用非常相似的性能。

回答by Farseer

to calculate norm2

计算范数2

numpy.linalg.norm(x, ord=2) 

numpy.linalg.norm(x, ord=2)**2for square

numpy.linalg.norm(x, ord=2)**2对于正方形

回答by Blckknght

I don't know if the performance is any good, but (a**2).sum()calculates the right value and has the non-repeated argument you want. You can replace awith some complicated expression without binding it to a variable, just remember to use parentheses as necessary, since **binds more tightly than most other operators: ((a-b)**2).sum()

我不知道性能是否有任何好处,但(a**2).sum()计算出正确的值并具有您想要的非重复参数。您可以a用一些复杂的表达式替换而不将其绑定到变量,只要记住必要时使用括号,因为**绑定比大多数其他运算符更紧密:((a-b)**2).sum()