【问题标题】:Tensorflow Lite model inference has very low accuracyTensorflow Lite 模型推理的准确率非常低
【发布时间】:2019-06-26 14:21:35
【问题描述】:

我想创建一个预测年龄和性别的模型,并将其集成到 Android 应用中。

我在 Ubuntu 16 上使用 Python 3.6、Tensorflow 1.13.1 和 Keras 2.2.4。

首先,我使用 IMDB 数据集训练不同的模型:来自 keras 的 Mobilenet V1V2,以及我自己编写的 VGG。 对于两个移动网络,我使用 imagenet 权重来初始化模型。

准确率相当不错,性别超过90%。

训练结束后,我尝试了几种方法来转换 tflite 中的模型:

  • 我直接从 .h5 文件转换的三种方式:
converter = tf.lite.TFLiteConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)
converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)
converter = tf.contrib.lite.TocoConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)
  • 我首先将模型转换为 tf 图,如this example 中所述

我也尝试在转换前使用这行代码:

tf.keras.backend.set_learning_phase(0)

最后我在 Android Studio 中加载了 .tflite 文件:

private ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap) {
        int SIZE_IMAGE = 96;
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*1*SIZE_IMAGE*SIZE_IMAGE*3);
        byteBuffer.order(ByteOrder.nativeOrder());
        int[] pixels = new int[SIZE_IMAGE * SIZE_IMAGE];
        bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
        int pixel = 0;
        for(int i=0; i < SIZE_IMAGE; i++){
            for(int j=0; j<SIZE_IMAGE;j++){
                final int val = pixels[pixel++];
                byteBuffer.putFloat((float) (((val >> 16) & 0xFF)/255));
                byteBuffer.putFloat((float) (((val >> 8) & 0xFF)/255));
                byteBuffer.putFloat((float) ((val & 0xFF)/255));

            }
        }    

public String recognizeImage(Bitmap bitmap) {
        ByteBuffer byteBuffer = convertBitmapToByteBuffer(bitmap);
        Map<Integer, Object> cnnOutputs = new HashMap<>();
        float[][] gender=new float[1][2];
        cnnOutputs.put(0,gender);
        float[][]age=new float[1][21];
        cnnOutputs.put(1,age);
        Object[] inputs = {byteBuffer};
        interpreter.runForMultipleInputsOutputs(inputs, cnnOutputs);
        String result = convertToResults(gender[0], age[0]);
        return result;
    }

在最终推理过程中,无论使用何种模型,准确率都非常低。要么解释器预测的总是完全相同的结果,要么预测的年龄略有变化但预测的性别总是“女性”。

我该怎么办?

提前致谢!

【问题讨论】:

    标签: android tensorflow keras tensorflow-lite


    【解决方案1】:

    尝试使用您的 keras 模型和 tflite 模型来处理一个输入数据并比较推理结果。可能输出不匹配。您可以从那里进行调试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2019-02-12
      • 2019-10-06
      • 2018-04-02
      相关资源
      最近更新 更多