
[英]"LinAlgError: 0-dimensional array given. Array must be at least two-dimensional" BUT I've know I'm passing a 2D argument
[英]Function vectorization says there is a 0-dimensional argument while the argument is an array
我正在实现这个等式并将其用于频率集nos
:
非矢量化代码有效:
import numpy as np
h = np.array([1,2,3])
nos = np.array([4, 5, 6, 7])
func = lambda h, no: np.sum([hk * np.exp(-1j * no * k) for k, hk in enumerate(h)])
# Not vectorized
resps = np.zeros(nos.shape[0], dtype='complex')
for i, no in enumerate(nos):
resps[i] = func(h, no)
print(resps)
> Out: array([-0.74378734-1.45446975j,
> -0.94989022+3.54991188j,
> 5.45190245+2.16854975j,
> 2.91801616-4.28579526j])
我想向量化调用以便立即传递nos
而不是显式迭代:
H = np.vectorize(func, excluded={'h'}, signature='(k),(n)->(n)')
resps = H(h, nos)
致电H
时:
错误:ValueError:0 维参数没有足够的维度用于所有核心维度('n',)
我正在使用签名参数,但我不确定我是否以正确的方式使用它。 如果没有此参数,则func
会出错:
TypeError: 'numpy.int32' object 不可迭代
我不明白问题出在哪里。
循环的列表理解版本:
In [15]: np.array([func(h,n) for n in nos])
Out[15]:
array([-0.74378734-1.45446975j, -0.94989022+3.54991188j,
5.45190245+2.16854975j, 2.91801616-4.28579526j])
vectorize
- 排除第一个参数(按 position,不是名称),并在第二个参数上进行标量迭代。
In [16]: f=np.vectorize(func, excluded=[0])
In [17]: f(h,nos)
Out[17]:
array([-0.74378734-1.45446975j, -0.94989022+3.54991188j,
5.45190245+2.16854975j, 2.91801616-4.28579526j])
无需使用signature
。
使用真正的 numpy 矢量化(不是伪np.vectorize
):
In [23]: np.sum(h * np.exp(-1j * nos[:,None] * np.arange(len(h))), axis=1)
Out[23]:
array([-0.74378734-1.45446975j, -0.94989022+3.54991188j,
5.45190245+2.16854975j, 2.91801616-4.28579526j])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.