如何设置 Tensorflow Lite C++ 的输入

how to set input of Tensorflow Lite C++

我正在尝试使用 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

通过更改解决

interpreter->typed_tensor<float>(0)[0] = x;

interpreter->typed_input_tensor<float>(0)[0] = x;

input var 应该有输入张量 id。 你能试试吗:

interpreter->typed_tensor<float>(input)[0] = x;