首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用numba njit函数的词典

使用numba njit函数的词典
EN

Stack Overflow用户
提问于 2019-03-09 15:01:39
回答 1查看 18K关注 0票数 16

当输入和返回都是字典时,如何加快numba的功能?

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

代码语言:javascript
复制
@numba.jit('float64[:](int32,int32)',nopython=True)
def f(a, b):
    # returns array 1d array

现在我有了一个函数,它接受并返回字典。我怎么才能在这里应用numba?

代码语言:javascript
复制
    def collocation(aeolus_data,val_data):

      ...

      return sample_aeolus, sample_valdata
EN

回答 1

Stack Overflow用户

发布于 2019-03-14 13:34:47

现在Numba版本的43.0中增加了对字典的支持。尽管它非常有限(不支持列表并设置为键/值)。不过,您可以阅读更新的文档这里有更多信息。下面是一个例子

代码语言:javascript
复制
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]}

链接到Google笔记本

参考资料:

票数 33
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55078628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档