如何使用随机输入配置ONNX模型,而不必指定输入形状?



我得到了几个ONNX模型。我想对他们进行侧写。在不指定输入形状的情况下,如何使用随机输入对它们进行分析?

我不喜欢手动找出每个模型的输入形状并相应地格式化我的随机输入。

如果你的模型是ONNX格式的,它有关于形状的信息存储在里面。因此,您不需要手动指定它们。因此,您需要通过onnx.load函数读取模型,然后从.graph.input(输入信息列表)属性中捕获每个输入的所有信息,然后创建随机输入。

下面的代码片段将有所帮助。它假设有时输入具有动态形状模糊(如'length'或'batch'模糊,可以在推理中可变):

import numpy as np
import onnx
from onnx import mapping
model = onnx.load('/path/to/model.onnx')

input_types = [
mapping.TENSOR_TYPE_TO_NP_TYPE[_input.type.tensor_type.elem_type]
for _input in model.graph.input
]
# random size for dynamic dims
input_dynamic_sizes = {
d.dim_param: np.random.randint(10, 20)
for _input in model.graph.input
for d in _input.type.tensor_type.shape.dim
if d.dim_param != ''
}
# parse shapes of inputs
# assign randomed value to dynamic dims
input_shapes = [
tuple(
d.dim_value if d.dim_value > 0 else input_dynamic_sizes[d.dim_param]
for d in _input.type.tensor_type.shape.dim
)
for _input in model.graph.input
]
# randomize inputs with given shape and types
# change this to match your required test inputs
inputs = [
(np.random.randn(*_shape) * 10).astype(_type)
for _shape, _type in zip(input_shapes, input_types)
]

model.graph.input示例:

[name: "input"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 1
}
dim {
dim_param: "sequence"
}
}
}
}
, name: "h0"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 2
}
dim {
dim_value: 1
}
dim {
dim_value: 64
}
}
}
}
, name: "c0"
type {
tensor_type {
elem_type: 1
shape {
dim {
dim_value: 2
}
dim {
dim_value: 1
}
dim {
dim_value: 64
}
}
}
}
]

相关内容

最新更新