6

np.newaxisNumbaで使用する方法はありnopythonますか? 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[:, np.newaxis] * c[np.newaxis, :]
    return d

ありがとう

4

3 に答える 3

7

reshape を使用してこれを実現できます[:, 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
于 2016-08-04T11:44:43.723 に答える
1

これは、最新バージョンの 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
于 2016-08-05T16:36:04.257 に答える