這可以用最新版本的Numba(0.27)和numpy stride_tricks
完成。你需要小心這個,它有點難看。請閱讀docstring的as_strided
以確保您瞭解發生了什麼,因爲這不是「安全」的,因爲它不會檢查形狀或步幅。
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) # True
我試過了,但是我得到了''reshape()支持連續數組只。當然,'toto()'不是我的實際功能 – EntrustName
你可以做'b.copy()。reshape(( - 1,1))''。如果你的數組不是連續的,我相信這將會複製,儘管不是100%確定的。 – chrisb