为了保持“只有一种明显的方法来做到这一点”,如何在Numpy中获得矢量(1D数组)的大小?

def mag(x): 
    return math.sqrt(sum(i**2 for i in x))

上述功能是有效的,但我无法相信我必须自己指定这样一个微不足道的核心功能。


当前回答

使用scipy中的函数规范。Linalg(或numpy.linalg)

>>> from scipy import linalg as LA
>>> a = 10*NP.random.randn(6)
>>> a
  array([  9.62141594,   1.29279592,   4.80091404,  -2.93714318,
          17.06608678, -11.34617065])
>>> LA.norm(a)
    23.36461979210312

>>> # compare with OP's function:
>>> import math
>>> mag = lambda x : math.sqrt(sum(i**2 for i in x))
>>> mag(a)
     23.36461979210312

其他回答

您需要的函数是numpy. linalgg .norm。(我认为它应该以基数numpy作为数组的属性——比如x.m om()——但哦,好吧)。

import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)

你也可以为你想要的n阶范数输入一个可选的词。假设你想要1范数:

np.linalg.norm(x,ord=1)

等等。

使用scipy中的函数规范。Linalg(或numpy.linalg)

>>> from scipy import linalg as LA
>>> a = 10*NP.random.randn(6)
>>> a
  array([  9.62141594,   1.29279592,   4.80091404,  -2.93714318,
          17.06608678, -11.34617065])
>>> LA.norm(a)
    23.36461979210312

>>> # compare with OP's function:
>>> import math
>>> mag = lambda x : math.sqrt(sum(i**2 for i in x))
>>> mag(a)
     23.36461979210312

我发现最快的方法是通过inner1d。下面是它与其他numpy方法的比较:

import numpy as np
from numpy.core.umath_tests import inner1d

V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)   
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))

print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]

import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)')              # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))')             # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))')            # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))')                 # 2 function calls in 0.009 seconds

Inner1d比linalg快3倍。Norm,比einsum快一点点

给出一个单个5D向量的例子:

x = np.array([1,-2,3,-4,5])

通常你会这样编码:

from scipy import linalg 
mag = linalg.norm(x)

对于不同类型的输入(矩阵或5D向量的堆栈(批)),请检查一致描述API的参考文档。 https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html

OR

如果虚拟环境是新鲜的,scipy是缺失的,只需输入

mag = np.sqrt(x.dot(x))

取每个指标的平方,然后求和,然后开根号。

import numpy as np  

def magnitude(v):
    return np.sqrt(np.sum(np.square(v))) 
print(magnitude([3,4]))