gpt4 book ai didi

python - 使用带有 numba njit 函数的字典

转载 作者:行者123 更新时间:2023-12-03 14:51:40 25 4
gpt4 key购买 nike

当输入和返回是字典时,如何使用 numba 加速功能?

我熟悉将 numba 用于接受数字和返回数组的函数,如下所示:

@numba.jit('float64[:](int32,int32)',nopython=True)
def f(a, b):
# returns array 1d array

现在我有一个接受并返回字典的函数。我如何在这里申请 numba?
    def collocation(aeolus_data,val_data):

...

return sample_aeolus, sample_valdata

最佳答案

现在已在 Numba 版本中添加了对 Dictionary 的支持 43.0 .虽然它非常有限(不支持列表和设置为键/值)。但是,您可以阅读更新的文档 here for more info .

这是一个例子

import numpy as np
from numba import njit
from numba import types
from numba.typed import Dict

# First create a dictionary using Dict.empty()
# Specify the data types for both key and value pairs

# Dict with key as strings and values of type float array
dict_param1 = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64[:],
)

# Dict with keys as string and values of type float
dict_param2 = Dict.empty(
key_type=types.unicode_type,
value_type=types.float64,
)

# Type-expressions are currently not supported inside jit functions.
float_array = types.float64[:]

@njit
def add_values(d_param1, d_param2):
# Make a result dictionary to store results
# Dict with keys as string and values of type float array
result_dict = Dict.empty(
key_type=types.unicode_type,
value_type=float_array,
)

for key in d_param1.keys():
result_dict[key] = d_param1[key] + d_param2[key]

return result_dict

dict_param1["hello"] = np.asarray([1.5, 2.5, 3.5], dtype='f8')
dict_param1["world"] = np.asarray([10.5, 20.5, 30.5], dtype='f8')

dict_param2["hello"] = 1.5
dict_param2["world"] = 10

final_dict = add_values(dict_param1, dict_param2)

print(final_dict)
# Output : {hello: [3. 4. 5.], world: [20.5 30.5 40.5]}

Link to Google colab notebook .

引用文献:
- https://github.com/numba/numba/issues/3644
- https://numba.pydata.org/numba-doc/dev/reference/pysupported.html#dict

关于python - 使用带有 numba njit 函数的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com