欢迎访问宙启技术站
智能推送

Python中的onnx.numpy_helper.from_array()方法解析及使用示例

发布时间:2023-12-17 09:27:40

onnx.numpy_helper.from_array() 方法是 ONNX Python 包中的一个函数,用于从一个 NumPy 数组创建一个 ONNX 张量。

该函数的定义如下:

import numpy as np
import onnx
from onnx import numpy_helper

def from_array(array, name=None):
    tensor = numpy_helper.from_array(array)
    if name is not None:
        tensor.name = name
    return tensor

onnx.numpy_helper.from_array() 函数接受两个参数:

- array:一个 NumPy 数组,用于创建 ONNX 张量。

- name(可选):指定 ONNX 张量的名称。

该函数返回一个 ONNX 张量。

下面是一个示例,展示了如何使用 onnx.numpy_helper.from_array() 函数:

import numpy as np
import onnx
from onnx import numpy_helper

# 创建一个 NumPy 数组
array = np.array([[1, 2, 3], [4, 5, 6]])

# 使用 from_array() 函数从 NumPy 数组创建 ONNX 张量
tensor = numpy_helper.from_array(array, name="my_tensor")

# 打印 ONNX 张量的属性
print(tensor)

输出结果如下所示:

name: "my_tensor"
data_type: 7
dims: 2
dims: 3
raw_data: "\001\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\003\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\005\000\000\000\000\000\000\000\006\000\000\000\000\000\000\000"