2016-08-04 47 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