我正在尝试使用TensorflowLite模型测试简单的tensorflow lite c ++代码。
它得到两个浮点数并做xor。但是,当我更改输入时,输出不会改变。我想行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
答案 0 :(得分:3)
通过更改
解决interpreter->typed_tensor<float>(0)[0] = x;
到
interpreter->typed_input_tensor<float>(0)[0] = x;
答案 1 :(得分:0)
input
var应该具有输入张量ID。
你可以尝试:
interpreter->typed_tensor<float>(input)[0] = x;