首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Numba函数参数类型不匹配定义ListType[数组(float64,2d,C)]错误

Numba函数参数类型不匹配定义ListType[数组(float64,2d,C)]错误
EN

Stack Overflow用户
提问于 2022-02-27 17:19:33
回答 1查看 796关注 0票数 2

我在Numba中有一个函数,它使用List(float64[:,::1])类型,这是一个用于尝试类型的虚拟函数,我将在for循环下执行很多操作。它有一种奇怪的行为,尽管to arr列表具有相同的numba.typeof()签名,但其中一个有效,另一个则不起作用,并告诉我它不是匹配类型。

这绝对是一种对象错误,但我可以搞清楚。

这是要加载的文件test.npy:

QXAhMA1v46PfeKnN/view?usp=共享

误差

代码语言:javascript
复制
    raise TypeError(msg)
TypeError: No matching definition for argument type(s) ListType[array(float64, 2d, C)]

代码语言:javascript
复制
import numpy as np
import numba
from numba.typed import List

branches = np.load('test.npy', allow_pickle=True).item()


@numba.njit('List(int64)(List(float64[:, ::1]))')
def not_test(branches):
    a_list = []
    for branch in branches:
        for i in range(len(branch)):
            a_list.append(i)
    return a_list

# this does not work
arr = []
for branch in branches.features[:2]:
    arr.append(np.asarray(branch.geometry.coordinates).copy())
arr = List(arr.copy())

print(numba.typeof(arr))
no_test(arr)

# this works
arr = List([np.array([np.array([7.0,7.3]), np.array([7.4,8.6])])])
print(numba.typeof(arr))
no_test(arr)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-01 07:28:55

对于被困在这种琐碎的事情中的人来说,正确的签名类型是:

代码语言:javascript
复制
@numba.njit('List(int64)(ListType(float64[:, ::1]))')

我不明白ListListType之间的区别,我在Numba官方网站上也找不到。我可以为装饰器中的类型编写一份备忘单,因为仅仅从函数的参数中找到的可用数据类型来推断它们应该如何编写并不容易。此外,让一个基于numba.typeof()返回的解析器函数能够创建装饰器的字符串也是非常有帮助的。

另外,到List()的转换非常慢,我在Numba GitHub上找到了一篇关于这个问题的文章。这是最初的帖子以Python为arg改进numba.typed.List构造函数的性能

代码语言:javascript
复制
def convert2(x, dtype=np.float64):
    try:
        # Try and convert x to a Numpy array. If this succeeds
        # then we have reached the end of the nesting-depth.
        y = np.asarray(x, dtype=dtype)
    except:
        # If the conversion to a Numpy array fails, then it can
        # be because not all elements of x can be converted to
        # the given dtype. There is currently no way to distinguish
        # if this is because x is a nested list, or just a list
        # of simple elements with incompatible types.

        # Recursively call this function on all elements of x.
        y = [convert2(x_, dtype=dtype) for x_ in x]

        # Convert Python list to Numba list.
        y = numba.typed.List(y)

    return y

编辑

我找到了一个超级有用的行来获取numba函数的类型签名

代码语言:javascript
复制
print(not_test.inspect_types())
#not_test (ListType[array(float64, 2d, C)], array(float64, 1d, A))
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71286902

复制
相关文章

相似问题

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