这可以通过最新版本的Numba(0.27)和numpy stride_tricks
实现。你需要小心处理,而且有点丑陋。阅读as_strided
的docstring确保你理解发生了什么,因为这不是“安全”的,它不检查形状或步幅。
import numpy as np
import numba as nb
a = np.random.randn(20, 10)
b = np.random.randn(20)
c = np.random.randn(10)
def toto(a, b, c):
d = a - b[:, np.newaxis] * c[np.newaxis, :]
return d
@nb.jit(nopython=True)
def toto2(a, b, c):
_b = np.lib.stride_tricks.as_strided(b, shape=(b.shape[0], 1), strides=(b.strides[0], 0))
_c = np.lib.stride_tricks.as_strided(c, shape=(1, c.shape[0]), strides=(0, c.strides[0]))
d = a - _b * _c
return d
x = toto(a,b,c)
y = toto2(a,b,c)
print np.allclose(x, y)
b.copy().reshape((-1,1))
。如果你的数组不是连续的,我相信这个操作仍然会进行复制,但不能百分之百确定。 - chrisb