我在Numba
中有一个函数,它使用List(float64[:,::1])
类型,这是一个用于尝试类型的虚拟函数,我将在for循环下执行很多操作。它有一种奇怪的行为,尽管to arr列表具有相同的numba.typeof()签名,但其中一个有效,另一个则不起作用,并告诉我它不是匹配类型。
这绝对是一种对象错误,但我可以搞清楚。
这是要加载的文件test.npy:
误差
raise TypeError(msg)
TypeError: No matching definition for argument type(s) ListType[array(float64, 2d, C)]
码
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)
发布于 2022-03-01 07:28:55
对于被困在这种琐碎的事情中的人来说,正确的签名类型是:
@numba.njit('List(int64)(ListType(float64[:, ::1]))')
我不明白List
和ListType
之间的区别,我在Numba
官方网站上也找不到。我可以为装饰器中的类型编写一份备忘单,因为仅仅从函数的参数中找到的可用数据类型来推断它们应该如何编写并不容易。此外,让一个基于numba.typeof()返回的解析器函数能够创建装饰器的字符串也是非常有帮助的。
另外,到List()的转换非常慢,我在Numba GitHub上找到了一篇关于这个问题的文章。这是最初的帖子以Python为arg改进numba.typed.List构造函数的性能
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函数的类型签名
print(not_test.inspect_types())
#not_test (ListType[array(float64, 2d, C)], array(float64, 1d, A))
https://stackoverflow.com/questions/71286902
复制相似问题