c++ - 矩阵数据数组的Tensorflow tflite c++ api推理

标签 c++ tensorflow tensorflow-lite

我正在创建一个类,该类将用于使用 tensorflow 的 tflite c++ api 在 c++ 中的嵌入式设备(不是树莓派)上运行推理。 Tensorflow 似乎没有关于如何对 n 个图像数据样本进行推理的体面文档。我在 python 中的数据形状是 (n, 5, 40, 1) [n 个样本,5 个高度,40 个宽度,1 个 channel ]。我无法弄清楚的是如何输入数据并在输出中接收每个样本的推断。我有两个类(class),所以我应该收到 n 个二维数组输出。有谁知道您是否可以传入任何数据类型,例如 Eigen?我正在使用形状 (1, 5, 2, 1) 的输入进行测试,以简化我的测试。

#include "classifier.h"
#include <iostream>

using namespace tflite;

Classifier::Classifier(std::string modelPath) {
    tflite::StderrReporter error_reporter;
    model = tflite::FlatBufferModel::BuildFromFile(modelPath.c_str(), &error_reporter);

    tflite::ops::builtin::BuiltinOpResolver resolver;
    tflite::InterpreterBuilder(*model, resolver)(&interpreter); // private class variable interpreter
    std::vector<int> sizes = {1, 5, 2, 1};
    interpreter->ResizeInputTensor(0, sizes);
    interpreter->AllocateTensors();


}

std::vector<std::vector<float> Classifier::getDataSamples() {
    std::vector<std::vector<float> test = {{0.02, 0.02}, {0.02, 0.02}, {0.02, 0.02},{0.02, 0.02},{0.02, 0.02},};
    return test;
}

float Classifier::predict() {


    std::vector<float> signatures = getDataSamples();
    for (int i = 0; i < signatures.size(); ++i) {
        interpreter->typed_input_tensor<float>(0)[i];
    }

    // float* input = interpreter->typed_input_tensor<float>(0);
    // *input = 1.0;

    interpreter->Invoke();

    float* output = interpreter->typed_output_tensor<float>(0);

    return *output;
}

最佳答案

从 Tensorflow 文档中,我们可以找到以下详细信息,

It should be noted that:

  • Tensors are represented by integers, in order to avoid string comparisons (and any fixed dependency on string libraries).
  • An interpreter must not be accessed from concurrent threads.
  • Memory allocation for input and output tensors must be triggered by calling AllocateTensors() right after resizing tensors.


您可以在 C++ here 中找到有关加载和运行模型的更多信息。 .

关于c++ - 矩阵数据数组的Tensorflow tflite c++ api推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61331898/

相关文章:

python - 有没有办法在 Raspberry Pi 4 上获得 GPU 加速以进行深度学习?

c++ - qt中的占位符

python - 使用tensorflow导出神经网络的权重

python - tf.where 具有多个条件

python - 提取 3 个嵌入层的 Keras 连接层,但它是一个空列表

python - Tensorflow 每 channel 量化

c++ - boost 元组部分迭代?

c++ - undefined reference to operator<<.... 是什么意思?在 C++ 中

c++ - 尝试转发声明时 '->' 是什么意思?

python - 更改输入大小后 tflite.allocate_tensors() 失败