如何通过C ++ API向tflite提供多维输入

问题描述 投票:0回答:1

我正在尝试使用tflite C ++ API来运行自己构建的模型。我通过以下代码片段将模型转换为tflite格式:

import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_keras_model_file('model.h5') 
tfmodel = converter.convert() 
open("model.tflite", "wb").write(tfmodel)

我正在遵循tflite official guide中提供的步骤,到目前为止,我的代码如下所示:>

// Load the model
std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile("model.tflite");

// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;

tflite::InterpreterBuilder builder(*model, resolver);
builder(&interpreter);
interpreter->AllocateTensors();

// Check interpreter state
tflite::PrintInterpreterState(_interpreter.get());

这显示我的输入层的形状为(1、2050、6)。为了从C ++提供输入,我遵循了this thread,而我的输入代码如下所示:

std::vector<std::vector<double>> tensor;     // I filled this vector, (dims are 2050, 6)

int input = interpreter->inputs()[0];
float* input_data_ptr = interpreter->typed_input_tensor<float>(input);
for (int i = 0; i < 2050; ++i) {
    for (int j = 0; j < 6; j++) {
        *(input_data_ptr) = (float)tensor[i][j];
        input_data_ptr++;
    }
}

此模型的最后一层返回单个浮点(概率)​​。我从以下代码获得输出。

interpreter->Invoke();
int output_idx = interpreter->outputs()[0];
float* output = interpreter->typed_output_tensor<float>(output_idx);
std::cout << "OUTPUT: " << *output << std::endl;

我的问题是,对于不同的输入,我得到的输出相同。此外,输出与tensorflow-python输出不匹配。

我不明白为什么会这样。另外,任何人都可以确认这是否是向模型提供输入的正确方法吗?

一些额外信息:

  1. 我从v1.14.0的源代码构建了tflite,使用命令:bazel build -c opt //tensorflow/contrib/lite:libtensorflowLite.so --cxxopt="-std=c++11" --verbose_failures

  2. 我使用tensorflow v2.0训练了我的模型并将其转换为另一台机器上的tflite

我正在尝试使用tflite C ++ API来运行自己构建的模型。我通过以下代码片段将模型转换为tflite格式:import tensorflow as tf converter = tf.lite.TFLiteConverter ....

c++ tensorflow tensorflow-lite tf-lite
1个回答
0
投票

这是错误的API用法。

© www.soinside.com 2019 - 2024. All rights reserved.