我正在尝试重新创建这个视频中完成的工作,演示代码的CppDay20Interoperable AI: ONNX & ONNXRuntime in C++ (M. Arena, M.Verasani).The github存储库是here .So far我已经使用TensorFlow训练了一个回归模型,并已转换为ONNX以便在c++中进行推理。但是创建的ONNX运行时会话无法读取我的模型的输入形状;输入形状返回值为-1。
Ort::Env env;
Ort::Session session{env,model_path, Ort::SessionOptions{} };
Ort::AllocatorWithDefaultOptions allocator;
auto* inputName = session.GetInputName(0, allocator);
std::cout << "Input name: " << inputName << "\n";
auto* outputName = session.GetOutputName(0, allocator);
std::cout << "Output name: " << outputName << "\n";
auto inputShape = session.GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape();
//model has 5 inputs
std::vector<float> inputValues = {1, 2, 3, 4, 5 };
// where to allocate the tensors
auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
// create the input tensor (this is not a deep copy!)
auto inputOnnxTensor = Ort::Value::CreateTensor<float>(memoryInfo,
inputValues.data(), inputValues.size(),
inputShape.data(), inputShape.size());
// the API needs the array of inputs you set and the array of outputs you get
array inputNames = { inputName };
array outputNames = { outputName };
// finally run the inference!
auto outputValues = session.Run(
Ort::RunOptions{ nullptr }, // e.g. set a verbosity level only for this run
inputNames.data(), &inputOnnxTensor, 1, // input to set
outputNames.data(), 1);
输出:
Number of model inputs: 1
Number of model outputs: 1
Input name: input_1
Output name: Identity
tried creating tensor with negative value in shape
有什么建议可以让推理代码正常工作吗?
发布于 2021-08-23 12:50:09
您的模型接受shape 的输入张量,第一维是未知的(通常是动态批量大小),因此当您调用session.GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape()
时,第一维应该是-1。
在将实际数据提供给模型之前,您需要为张量设置一个具体的形状,在您的情况下,您可能应该手动将第一个维度设置为1。
https://stackoverflow.com/questions/68204966
复制相似问题