1 回答
TA贡献1805条经验 获得超9个赞
您可以在 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
添加回答
举报