首页 > 解决方案 > TensorFlow Lite 模型测试:正确的代码、类的概率

问题描述

我正在尝试使用 TensorflowLite 模型测试 TensorFlow lite c++ 代码。模型获取 256*256 的浮点数组(频谱图或图像)并对这些数据进行一些推断。TF Lite 模型旨在解决分类为 5 类的问题。它是通过转换从传统的 TF 模型导出的。我使用 TF Lite 2.0。

测试模型

这是我的代码:

#include <iostream>
#include <cstdio>
#include "../tensorflow/tensorflow/lite/interpreter.h"
#include "../tensorflow/tensorflow/lite/model.h"
#include "../tensorflow/tensorflow/lite/kernels/register.h"
#include "../tensorflow/tensorflow/lite/op_resolver.h"
#include <cstdlib>

int main(int argc, char** argv)
{

    const char* filename = argv[1];

    std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(filename);

    tflite::ops::builtin::BuiltinOpResolver resolver;
    std::unique_ptr<tflite::Interpreter> interpreter;
    tflite::InterpreterBuilder(*model, resolver)(&interpreter);

    interpreter->SetNumThreads(4);
    interpreter->AllocateTensors();

    for(int i = 0; i < 256*256; i++){
    float input = rand() % 10 + rand() % 10;
            interpreter->typed_input_tensor<float>(0)[i] = input;
            //printf("%f ", input);
    }
    //printf("\n");

    interpreter->Invoke();
    int output = interpreter->outputs()[0];

    printf("%d ",  output);

    for(int i = 0; i < 5; i++)
    {
        float output  = interpreter->typed_output_tensor<float>(0)[i];
        printf("%f ", (output));
    }
    printf("\n");
} 

我有一些疑问:

标签: c++tensorflowtensorflow-lite

解决方案


您的代码看起来正确。由于 Tensorflow Lite 以行优先格式查看张量,因此您分配输入的方式似乎是合理的。

你可能不需要这个:

int output = interpreter->outputs()[0];

printf("%d ",  output);

否则,事情看起来还不错。如果您以与训练期间相同的方式预处理输入图像/频谱图,您应该获得您期望的输出。


推荐阅读