Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎么打印 ONNX 模型输入、输出和形状?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

拿到模型文件,可以看 model.graph.input 和 model.graph.output,从各项的 type 读取元素类型和维度。已知维度是数字,符号维度可能显示诸如 batch 的名字。

讲清原理

运行前可调 session.get_inputs()、session.get_outputs()。它们告诉调用方要用的输入名、运行时类型和形状。符号维度还没有本轮具体值。

例子与易错点

例如元信息为 [batch, 2],提交时可给形状 [3, 2] 的 float32 矩阵。示例实际创建会话并核对运行时把第一维读成了符号名。

import onnxruntime as ort
from onnx import TensorProto, helper

x = helper.make_tensor_value_info("features", TensorProto.FLOAT, ["batch", 2])
y = helper.make_tensor_value_info("prediction", TensorProto.FLOAT, ["batch", 2])
graph = helper.make_graph([helper.make_node("Identity", ["features"], ["prediction"])],
                          "signature", [x], [y])
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)],
                          ir_version=10)
session = ort.InferenceSession(model.SerializeToString(), providers=["CPUExecutionProvider"])
for tensor in session.get_inputs() + session.get_outputs():
    assert tensor.type == "tensor(float)" and tensor.shape == ["batch", 2]
    print(tensor.name, tensor.type, tensor.shape)

相关题:第 8 题、第 9 题、第 15 题、第 21 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。