You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Numba函数中使用typed.list与Numpy数组?遇类型转换报错求解

解决Numba中numba.typed.List转Numpy数组的问题

这个问题我之前也碰到过,核心原因是Numba的nopython模式下,np.array()并不支持直接将numba.typed.List转换为Numpy数组,报错里的NotImplementedError已经说得很清楚了——Numba的List类型没法直接映射为Numpy的dtype。下面给你两种可行的解决方案:

方法一:使用to_numpy()方法(推荐,Numba 0.55+可用)

Numba从0.55版本开始给typed.List添加了to_numpy()方法,可以直接把typed List转换成对应的Numpy数组。注意要确保传入函数的是预先创建好的numba.typed.List,而不是Python原生列表:

from numba import jit
from numba.typed import List as NBList
import numpy as np

@jit(nopython=True)
def water_added_to_pp_NBList(water_added: NBList[int], vessel_volume: int = 1000 ) -> np.ndarray:
    """convert list of amounts of water in mg to array of partial pressures for a given volume"""
    # 直接用to_numpy()转换typed List
    wadd_array = water_added.to_numpy()
    print(wadd_array)
    return np.divide(wadd_array, vessel_volume)

# 先把Python原生列表转为numba typed List
py_input = [10, 25, 50, 75, 100, 150, 200, 250]
nb_input = NBList(py_input)

output_NBListed = water_added_to_pp_NBList(nb_input)

方法二:手动创建数组并填充(兼容旧版Numba)

如果你用的是Numba 0.55之前的版本,或者需要更好的兼容性,可以手动创建Numpy数组,再遍历typed List填充元素:

from numba import jit
from numba.typed import List as NBList
import numpy as np

@jit(nopython=True)
def water_added_to_pp_NBList(water_added: NBList[int], vessel_volume: int = 1000 ) -> np.ndarray:
    """convert list of amounts of water in mg to array of partial pressures for a given volume"""
    # 创建对应长度的空数组,指定dtype
    wadd_array = np.empty(len(water_added), dtype=np.int64)
    # 遍历填充元素
    for idx in range(len(water_added)):
        wadd_array[idx] = water_added[idx]
    print(wadd_array)
    return np.divide(wadd_array, vessel_volume)

# 转换输入为typed List
py_input = [10, 25, 50, 75, 100, 150, 200, 250]
nb_input = NBList(py_input)

output_NBListed = water_added_to_pp_NBList(nb_input)

额外注意点

  1. 参数类型匹配:函数的参数注解要改成NBList[int],确保Numba能正确推断类型,避免反射警告。
  2. 输入转换时机:不要在nopython模式的函数内部转换Python原生列表为typed List——这种转换需要Python API支持,nopython模式下会报错,所以一定要在函数外部完成转换。
  3. 关于弃用警告:第一个函数的警告是因为Numba即将移除对Python原生列表的反射支持,所以用numba.typed.List是正确的方向,上面的两种方法都能彻底解决警告问题。

内容的提问来源于stack exchange,提问作者Yobmod

火山引擎 最新活动