C#读取onnx每个节点的数据
时间: 2023-06-23 13:09:10 浏览: 161
要读取 ONNX 模型中每个节点的数据,可以使用 ONNX Runtime 库。以下是 C# 代码示例:
```csharp
using System;
using System.Collections.Generic;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
class Program
{
static void Main(string[] args)
{
// Load the ONNX model
var modelPath = "model.onnx";
var session = new InferenceSession(modelPath);
// Get the input and output node names
var inputName = session.InputMetadata.Keys.First();
var outputName = session.OutputMetadata.Keys.First();
// Prepare the input tensor
var tensor = new DenseTensor<float>(new[] { 1, 3 }, new float[] { 1, 2, 3 });
// Run the inference
var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor(inputName, tensor) };
var results = session.Run(inputs);
// Print the output tensor shape and data
var outputTensor = results.First().AsTensor<float>();
Console.WriteLine($"Output shape: {string.Join(",", outputTensor.Dimensions)}");
Console.WriteLine($"Output data: {string.Join(",", outputTensor.ToArray())}");
// Print the data for each node in the graph
foreach (var node in session.Graph.Nodes)
{
var nodeOutputName = node.Outputs.First();
var nodeOutput = results.First(output => output.Name == nodeOutputName).AsTensor<float>();
Console.WriteLine($"Data for node {node.Name}: {string.Join(",", nodeOutput.ToArray())}");
}
}
}
```
在上面的代码中,我们首先加载 ONNX 模型并获取输入和输出节点的名称。然后,我们准备输入张量并运行推理。最后,我们打印输出张量的形状和数据,并使用 foreach 循环遍历图中的每个节点并打印其输出数据。
阅读全文