我的函数接受numpy数组列表和字典(或字典列表)作为输入参数,并返回值列表。numpy数组的列表很长,并且数组的形状可能不同。尽管我可以单独传递numpy数组,但出于内务处理的目的,我真的希望形成一个numpy数组元组,并将它们作为元组传递到我的函数中。
如果没有字典(它是根据numba>=0.43专门形成的),整个设置工作良好-请参阅下面的脚本。因为输入和输出的结构是元组形式的,所以JIT需要签名—如果没有签名,它就无法确定数据结构的类型。但是,无论我如何尝试将字典“d”声明到JIT装饰器中,我都无法使脚本正常工作。
请帮助想法或解决方案,如果存在的话。
非常感谢
“巨蟒:
import numpy as np
from numba import njit
from numba import types
from numba.typed import Dict
@njit( 'Tuple( (f8,f8) )(Tuple( (f8[:],f8[:]) ))' )
def somefunction(lst_arr):
arr1, arr2 = lst_arr
summ = 0
prod = 1
for i in arr2:
summ += i
for j in arr1:
prod *= j
result = (summ,prod)
return result
a = np.arange(5)+1.0
b = np.arange(5)+11.0
arg = (a,b)
print(a,b)
print(somefunction(arg))
# ~~ The Dict.empty() constructs a typed dictionary.
d = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64,)
d['k1'] = 1.5
d['k2'] = 0.5
'''
我希望将'd'-字典传递到'somefunction'中,并将其与dict键一起使用…形成如下示例:
result = (summ * d['k1'], prod * d['k2'])
import numpy as np
from numba import njit
from numba import types
from numba.typed import Dict
@njit( 'Tuple( (f8,f8) )(Tuple( (f8[:],f8[:]) ), Dict)' )
def somefunction(lst_arr, mydict):
arr1, arr2 = lst_arr
summ = 0
prod = 1
for i in arr2:
summ += i
for j in arr1:
prod *= j
result = (summ*mydict['k1'],prod*mydict['k2'])
return result
# ~~ Input numpy arrays
a = np.arange(5)+1.0
b = np.arange(5)+11.0
arg = (a,b)
# ~~ Input dictionary for the function
d = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64)
d['k1'] = 1.5
d['k2'] = 0.5
# ~~ Run function and print results
print(somefunction(arg, d))
最佳答案
我使用的是0.45.1
版本。您可以简单地传递字典,而不必在字典中声明类型:
d = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64[:],
)
d['k1'] = np.arange(5) + 1.0
d['k2'] = np.arange(5) + 11.0
# Numba will infer the type on it's own.
@njit
def somefunction2(d):
prod = 1
# I am assuming you want sum of second array and product of second
result = (d['k2'].sum(), d['k1'].prod())
return result
print(somefunction(d))
# Output : (65.0, 120.0)
作为参考,您可以查看官方文档中的this example。
更新:
在您的例子中,您可以让
jit
自己推断类型,它应该可以工作,下面的代码对我有效:import numpy as np
from numba import njit
from numba import types
from numba.typed import Dict
from numba.types import DictType
# Let jit infer the types on it's own
@njit
def somefunction(lst_arr, mydict):
arr1, arr2 = lst_arr
summ = 0
prod = 1
for i in arr2:
summ += i
for j in arr1:
prod *= j
result = (summ*mydict['k1'],prod*mydict['k2'])
return result
# ~~ Input numpy arrays
a = np.arange(5)+1.0
b = np.arange(10)+11.0 #<--------------- This is of different shape
arg = (a,b)
# ~~ Input dictionary for the function
d = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64)
d['k1'] = 1.5
d['k2'] = 0.5
# This works now
print(somefunction(arg, d))
您可以查看官方文档:
除非有必要,建议让Numba使用@jit的无签名变量来推断参数类型。
我尝试了各种方法,但这是唯一一个对你指定的问题有效的方法。
关于python - Numba词典:JIT()装饰器中的签名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58145487/