【发布时间】:2021-04-10 00:45:10
【问题描述】:
我正在尝试使用 @guvectorize 装饰器,它将从开始和停止向量返回数组的 axis=0 方法,例如,如果:
values = array([[82, 3],
[76, 7],
[23, 8],
[46, 5],
[38, 6]])
starts = array([ 0, 1, 1, 1, 4])
stops = array([ 1, 4, 4, 4, 5])
我的函数会返回:
array([[82. , 3. ],
[48.33333333, 6.66666667],
[48.33333333, 6.66666667],
[48.33333333, 6.66666667],
[38. , 6. ]])
按照simple example in the numba documentation,这是我想出的(函数对一列的向量进行操作):
@guvectorize([(int64[:], int64[:], int64[:], float64[:])], '(n),(n),(n)->(n)', nopython=True)
def variable_window_avg(values, starts, stops, means):
for i in range(values.shape[0]):
means[i] = np.nanmean(values[starts[i]:stops[i]])
当values 是向量时,这很有效,但当值是所需的 ndarray 时,它不会按比例放大:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-128-8a213e6ace9c> in <module>
----> 1 variable_window_avg(arr[:,:2], arr[:,1], arr[:,2])
ValueError: variable_window_avg: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n),(n),(n)->(n) (size 100 is different from 2)
错误表明形状没有通过 Numpy 通用通用函数 API 正确广播在一起,确实
res = variable_window_avg(values.T, starts, stops)
res = res.T
有效。但是修改输入和输出布局签名似乎是避免两个转置的更好解决方案。我也不明白为什么 numba 文档中的示例但我的代码失败了。
【问题讨论】: