如何设置 Tensorflow Lite C++ 的输入
Posted
技术标签:
【中文标题】如何设置 Tensorflow Lite C++ 的输入【英文标题】:how to set input of Tensorflow Lite C++ 【发布时间】:2018-10-13 12:16:23 【问题描述】:我正在尝试使用 TensorflowLite 模型测试简单的 tensorflow lite c++ 代码。
它有两个浮点数并进行异或。但是,当我更改输入时,输出不会改变。我猜interpreter->typed_tensor<float>(0)[0] = x
行是错误的,所以输入没有正确应用。我应该如何更改代码才能工作?
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/string_util.h"
#include "tensorflow/contrib/lite/tools/mutable_op_resolver.h"
int main()
const char graph_path[14] = "xorGate.lite";
const int num_threads = 1;
std::string input_layer_type = "float";
std::vector<int> sizes = 2;
float x,y;
std::unique_ptr<tflite::FlatBufferModel> model(
tflite::FlatBufferModel::BuildFromFile(graph_path));
if(!model)
printf("Failed to mmap model\n")
exit(0);
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);
if(!interpreter)
printf("Failed to construct interpreter\n");
exit(0);
interpreter->UseNNAPI(false);
if(num_threads != 1)
interpreter->SetNumThreads(num_threads);
int input = interpreter->inputs()[0];
interpreter->ResizeInputTensor(0, sizes);
if(interpreter->AllocateTensors() != kTfLiteOk)
printf("Failed to allocate tensors\n");
exit(0);
//read two numbers
std::printf("Type two float numbers : ");
std::scanf("%f %f", &x, &y);
interpreter->typed_tensor<float>(0)[0] = x;
interpreter->typed_tensor<float>(0)[1] = y;
printf("hello\n");
fflush(stdout);
if(interpreter->Invoke() != kTfLiteOk)
std::printf("Failed to invoke!\n");
exit(0);
float* output;
output = interpreter->typed_output_tensor<float>(0);
printf("output = %f\n", output[0]);
return 0;
这是我运行代码时出现的消息。
root@localhost:/home# ./a.out
nnapi error: unable to open library libneuralnetworks.so
Type two float numbers : 1 1
hello
output = 0.112958
root@localhost:/home# ./a.out
nnapi error: unable to open library libneuralnetworks.so
Type two float numbers : 0 1
hello
output = 0.112958
【问题讨论】:
【参考方案1】:通过改变解决
interpreter->typed_tensor<float>(0)[0] = x;
到
interpreter->typed_input_tensor<float>(0)[0] = x;
【讨论】:
【参考方案2】:input
var 应该有输入张量 ID。
你可以试试:
interpreter->typed_tensor<float>(input)[0] = x;
【讨论】:
以上是关于如何设置 Tensorflow Lite C++ 的输入的主要内容,如果未能解决你的问题,请参考以下文章
用于推理的 TensorFlow Lite C++ API 示例
Android Tensorflow Lite C++ .SO 库未在运行时链接
如何在 Tensorflow Lite 上为 CoreML 委托设置填充类型以修复未设置“PoolingLayerBuilder (MEAN)_1”。
如何将 TensorFlow Lite 构建为静态库并从单独的(CMake)项目链接到它?