簡體   English   中英

如何將 numba 與 functools.reduce() 一起使用

[英]How to use numba together with functools.reduce()

我有以下代碼,我嘗試使用numbafunctools.reduce()mul並行循環:

import numpy as np
from itertools import product
from functools import reduce
from operator import mul
from numba import jit, prange

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
arr = np.array(lst)
n = 3
flat = np.ravel(arr).tolist()
gen = np.array([list(a) for a in product(flat, repeat=n)])

@jit(nopython=True, parallel=True)
def mtp(gen):
    results = np.empty(gen.shape[0])
    for i in prange(gen.shape[0]):
        results[i] = reduce(mul, gen[i], initializer=None)
    return results
mtp(gen)

但這給了我一個錯誤:

---------------------------------------------------------------------------
TypingError                               Traceback (most recent call last)
<ipython-input-503-cd6ef880fd4a> in <module>
     10         results[i] = reduce(mul, gen[i], initializer=None)
     11     return results
---> 12 mtp(gen)

~\Anaconda3\lib\site-packages\numba\dispatcher.py in _compile_for_args(self, *args, **kws)
    399                 e.patch_message(msg)
    400 
--> 401             error_rewrite(e, 'typing')
    402         except errors.UnsupportedError as e:
    403             # Something unsupported is present in the user code, add help info

~\Anaconda3\lib\site-packages\numba\dispatcher.py in error_rewrite(e, issue_type)
    342                 raise e
    343             else:
--> 344                 reraise(type(e), e, None)
    345 
    346         argtypes = []

~\Anaconda3\lib\site-packages\numba\six.py in reraise(tp, value, tb)
    666             value = tp()
    667         if value.__traceback__ is not tb:
--> 668             raise value.with_traceback(tb)
    669         raise value
    670 

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<built-in function reduce>) with argument(s) of type(s): (Function(<built-in function mul>), array(int32, 1d, C), initializer=none)
 * parameterized
In definition 0:
    AssertionError: 
    raised from C:\Users\HP\Anaconda3\lib\site-packages\numba\parfor.py:4138
In definition 1:
    AssertionError: 
    raised from C:\Users\HP\Anaconda3\lib\site-packages\numba\parfor.py:4138
This error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: resolving callee type: Function(<built-in function reduce>)
[2] During: typing of call at <ipython-input-503-cd6ef880fd4a> (10)


File "<ipython-input-503-cd6ef880fd4a>", line 10:
def mtp(gen):
    <source elided>
    for i in prange(gen.shape[0]):
        results[i] = reduce(mul, gen[i], initializer=None)
        ^

我不確定我哪里出錯了。 任何人都可以指出我正確的方向嗎? 非常感謝。

您可以在 numba jitted 函數中使用 np.prod :

n = 3
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
arr = np.array(lst)
flat = np.ravel(arr).tolist()
gen = [list(a) for a in product(flat, repeat=n)]

@jit(nopython=True, parallel=True)
def mtp(gen):
    results = np.empty(len(gen))
    for i in prange(len(gen)):
        results[i] = np.prod(gen[i])
    return results

或者,您可以使用 reduce 如下(感謝@stuartarchibald 指出這一點),盡管並行化在下面不起作用(至少從 numba 0.48 開始):

import numpy as np
from itertools import product
from functools import reduce
from operator import mul
from numba import njit, prange

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
arr = np.array(lst)
n = 3
flat = np.ravel(arr).tolist()
gen = np.array([list(a) for a in product(flat, repeat=n)])

@njit
def mul_wrapper(x, y):
    return mul(x, y)

@njit
def mtp(gen):
    results = np.empty(gen.shape[0])
    for i in prange(gen.shape[0]):
        results[i] = reduce(mul_wrapper, gen[i], None)
    return results

print(mtp(gen))

或者,因為 Numba 內部有一些魔法可以發現將轉義函數並編譯它們的閉包。 (再次感謝@stuartarchibald),您可以在下面這樣做:

@njit
def mtp(gen):
    results = np.empty(gen.shape[0])
    def op(x, y):
        return mul(x, y)
    for i in prange(gen.shape[0]):
        results[i] = reduce(op, gen[i], None)
    return results

但同樣,從 numba 0.48 開始,並行在這里不起作用。

請注意,核心開發團隊成員推薦的方法是采用第一個使用np.prod解決方案。 它可以與並行標志一起使用,並且具有更直接的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM