2016-08-04 48 views
2

有没有办法使用np.newaxis与Numba nopython?为了在python上应用广播功能而不需要备份?np.newaxis与Numba nopython

例如

@jit(nopython=True) 
def toto(): 
    a = np.random.randn(20, 10) 
    b = np.random.randn(20) 
    c = np.random.randn(10) 
    d = a - b[:, np.newaxis] * c[np.newaxis, :] 
    return d 

感谢

回答

2

你可以做到这一点使用重塑,它看起来像目前不支持[:, None]索引。请注意,这可能不会比做python快很多,因为它已经被矢量化了。

@jit(nopython=True) 
def toto(): 
    a = np.random.randn(20, 10) 
    b = np.random.randn(20) 
    c = np.random.randn(10) 
    d = a - b.reshape((-1, 1)) * c.reshape((1,-1)) 
    return d 
+0

我试过了,但是我得到了''reshape()支持连续数组只。当然,'toto()'不是我的实际功能 – EntrustName

+0

你可以做'b.copy()。reshape(( - 1,1))''。如果你的数组不是连续的,我相信这将会复制,尽管不是100%确定的。 – chrisb

1

这可以用最新版本的Numba(0.27)和numpy stride_tricks完成。你需要小心这个,它有点难看。请阅读docstringas_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