【问题标题】:How to specify the 'string' data type when using Numba?使用 Numba 时如何指定“字符串”数据类型?
【发布时间】:2019-10-21 02:54:18
【问题描述】:

Numba 无法识别字符串。如何更正以下代码?谢谢!

@nb.jit(nb.float64(nb.float64[:], nb.char[:]), nopython=True, cache=True)
def func(x, y='cont'):
    """
    :param x: is np.array, x.shape=(n,)
    :param y: is a string, 
    :return: a np.array of same shape as x
    """
    return result

【问题讨论】:

    标签: python string numba


    【解决方案1】:

    以下适用于 Numba 0.44:

    import numpy as np
    import numba as nb
    
    from numba import types
    
    @nb.jit(nb.float64[:](nb.float64[:], types.unicode_type), nopython=True, cache=True)
    def func(x, y='cont'):
        """
        :param x: is np.array, x.shape=(n,)
        :param y: is a string, 
        :return: a np.array of same shape as x
        """
        print(y)
        return x
    

    但是,如果您尝试运行 func 而不指定 y 的值,您将会收到错误消息,因为在您的签名中您说第二个参数是必需的。我试图弄清楚如何处理可选参数(查看types.Omitted),但无法完全弄清楚。我可能会考虑不指定签名并让 numba 进行正确的类型推断:

    @nb.jit(nopython=True, cache=True)
    def func2(x, y='cont'):
        """
        :param x: is np.array, x.shape=(n,)
        :param y: is a string, 
        :return: a np.array of same shape as x
        """
        print(y)
        return x
    

    【讨论】:

    • 谢谢你,乔希。确实,正如您所说,当没有将 y 值传递给函数时会出现错误。据我了解,Numba 并不完全支持所有 python 功能。
    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2015-09-24
    相关资源
    最近更新 更多