【问题标题】:Android TensorFlow Lite interpreter: How to fix "DataType error: cannot resolve DataType of java.lang.Float"Android TensorFlow Lite 解释器:如何修复“DataType 错误:无法解析 java.lang.Float 的 DataType”
【发布时间】:2019-01-17 11:58:55
【问题描述】:

在运行 TFLite 解释器时,将包含浮点数的 ByteBuffer 作为输入,应用程序会抛出异常:

“DataType 错误:无法解析 java.lang.Float 的 DataType”

模型本身在 Keras 上进行训练,然后转换为 TF,然后再转换为 TFLite。

对于转换,我使用了 TF(1.5.0 版)toco 转换器。

toco 的输入参数:

toco --input_file=converted.pb --output_file=model.tflite --input_format=TENSORFLOW_GRAPHDEF --input_shape=1,224,224,3 --input_array=main_input --output_array=main_output/Sigmoid --inference_type=FLOAT --output_format =TFLITE --input_type=FLOAT

我还手动创建了一个 float[][][][] 数组,而不是 ByteBuffer,该数组的尺寸预期作为模型的输入:[1,224,224,3]

导致与 ByteBuffer 相同的错误。

请注意,我将浮点数除以 255 以获得 [0,1] 范围内的像素值。

import org.tensorflow.lite.Interpreter;
import java.nio.ByteBuffer;


public Interpreter tflite;

tflite = new Interpreter(loadModelFile(Test_TFLite.this,modelFile));

ByteBuffer bytebuffer_float = convertBitmapToByteBuffer_float(image, 1, 
    224, 3);

float out = 0;

tflite.run(bytebuffer_float,out);


private ByteBuffer convertBitmapToByteBuffer_float(Bitmap bitmap, int 
    BATCH_SIZE, int inputSize, int PIXEL_SIZE) {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * BATCH_SIZE * 
    inputSize * inputSize * PIXEL_SIZE); //float_size = 4 bytes
        byteBuffer.order(ByteOrder.nativeOrder());
        int[] intValues = new int[inputSize * inputSize];
        bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, 
    bitmap.getWidth(), bitmap.getHeight());
        int pixel = 0;
        for (int i = 0; i < inputSize; ++i) {
            for (int j = 0; j < inputSize; ++j) { 
                final int val = intValues[pixel++];


                byteBuffer.putFloat( ((val >> 16) & 0xFF)* (1.f/255.f)); 
                byteBuffer.putFloat( ((val >> 8) & 0xFF)* (1.f/255.f)); 
                byteBuffer.putFloat( (val & 0xFF)* (1.f/255.f)); 
            }
        }
        return byteBuffer;
    }

我希望将 [0,1] 范围内的单个浮点值作为输出。由于解释器抛出异常,因此没有实际输出。

“DataType 错误:无法解析 java.lang.Float 的 DataType”

【问题讨论】:

    标签: java android tensorflow tensorflow-lite


    【解决方案1】:

    我自己从未使用过用于 Java 的 TF-Lite。 但是,根据docstflite.run() 的两个参数都必须是张量。但是对于 output 参数,您只传递了一个 float。所以,我很确定这是您的错误“无法解析 java.lang.Float 的 DataType”的根本原因。

    注意:同样根据文档,支持原始ByteBuffers 以​​及支持数据类型(floatintlongbyte)的多维数组。因此,您的两种方法ByteBufferfloat[][][][] 都应该有效。您只需对输出执行相同操作即可。

    【讨论】:

    • 是的,解决了! :) 似乎需要将输出定义为浮点数组!
    • 链接失效了。 kotlin 中的相应输出变量是什么?
    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多