应用训练后量化后,我的自定义CNN模型缩小到其原始大小的1/4(从56.1MB到14MB)。我将要预测的图像(100x100x3)放入100x100x3 = 30,000字节的ByteBuffer中。但是,推论过程中出现以下错误:
java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite buffer with 120000 bytes and a ByteBuffer with 30000 bytes.**
at org.tensorflow.lite.Tensor.throwExceptionIfTypeIsIncompatible(Tensor.java:221)
at org.tensorflow.lite.Tensor.setTo(Tensor.java:93)
at org.tensorflow.lite.NativeInterpreterWrapper.run(NativeInterpreterWrapper.java:136)
at org.tensorflow.lite.Interpreter.runForMultipleInputsOutputs(Interpreter.java:216)
at org.tensorflow.lite.Interpreter.run(Interpreter.java:195)
at gov.nih.nlm.malaria_screener.imageProcessing.TFClassifier_Lite.recongnize(TFClassifier_Lite.java:102)
at gov.nih.nlm.malaria_screener.imageProcessing.TFClassifier_Lite.process_by_batch(TFClassifier_Lite.java:145)
at gov.nih.nlm.malaria_screener.Cells.runCells(Cells.java:269)
at gov.nih.nlm.malaria_screener.CameraActivity.ProcessThinSmearImage(CameraActivity.java:1020)
at gov.nih.nlm.malaria_screener.CameraActivity.access$600(CameraActivity.java:75)
at gov.nih.nlm.malaria_screener.CameraActivity$8.run(CameraActivity.java:810)
at java.lang.Thread.run(Thread.java:762)
模型的输入图像尺寸为:100x100x3。我目前一次预测一张图像。因此,如果我要创建字节缓冲区:100x100x3 = 30,000字节。但是,上面的日志信息显示TensorFlowLite缓冲区具有120,000字节。这使我怀疑转换后的tflite模型仍为浮点格式。这是预期的行为吗?如何从TensorFlow官方存储库中获得像example那样以8凹点精度获取输入图像的量化模型?
在示例代码中,用作tflite.run()输入的ByteBuffer对于量化模型具有8位精度。
但我还从Google文档中读到,“推断时,权重是从8位精度转换为浮点,然后使用浮点内核进行计算的。”这两个实例似乎相互矛盾。
private static final int BATCH_SIZE = 1;
private static final int DIM_IMG_SIZE = 100;
private static final int DIM_PIXEL_SIZE = 3;
private static final int BYTE_NUM = 1;
imgData = ByteBuffer.allocateDirect(BYTE_NUM * BATCH_SIZE * DIM_IMG_SIZE * DIM_IMG_SIZE * DIM_PIXEL_SIZE);
imgData.order(ByteOrder.nativeOrder());
... ...
int pixel = 0;
for (int i = 0; i < DIM_IMG_SIZE; ++i) {
for (int j = 0; j < DIM_IMG_SIZE; ++j) {
final int val = intValues[pixel++];
imgData.put((byte)((val >> 16) & 0xFF));
imgData.put((byte)((val >> 8) & 0xFF));
imgData.put((byte)(val & 0xFF));
// imgData.putFloat(((val >> 16) & 0xFF) / 255.0f);
// imgData.putFloat(((val >> 8) & 0xFF) / 255.0f);
// imgData.putFloat((val & 0xFF) / 255.0f);
}
}
... ...
tfLite.run(imgData, labelProb);
训练后量化代码:
import tensorflow as tf
import sys
import os
saved_model_dir = '/home/yuh5/Downloads/malaria_thinsmear.h5.pb'
input_arrays = ["input_2"]
output_arrays = ["output_node0"]
converter = tf.contrib.lite.TocoConverter.from_frozen_graph(saved_model_dir, input_arrays, output_arrays)
converter.post_training_quantize = True
tflite_model = converter.convert()
open("thinSmear_100.tflite", "wb").write(tflite_model)
答案 0 :(得分:2)
训练后量化不会更改输入或输出层的格式。您可以使用与训练所用格式相同的数据来运行模型。
您可能会研究量化感知训练以生成完全量化的模型,但是我对此没有经验。
至于句子“推断时,权重从8位精度转换为浮点并使用浮点内核进行计算”。这意味着权重被“反量化”为内存中的浮点值,并使用FP指令进行计算,而不是执行整数运算。