TensorFlow lite:将模型转换为 tflite 后精度损失较大

jb *_*son 5 tensorflow tensorflow-lite

我一直在尝试 TFLite 来提高 Android 上的检测速度,但奇怪的是我的 .tflite 模型现在几乎只检测 1 个类别。

\n\n

我已经对重新训练 mobilenet 后获得的 .pb 模型进行了测试,结果很好,但由于某种原因,当我将其转换为 .tflite 时,检测结果相差甚远......

\n\n

对于重新训练,我使用了Tensorflow for Poets 2中的 retrain.py 文件

\n\n

我使用以下命令来重新训练、优化推理并将模型转换为 tflite:

\n\n
python retrain.py \\\n--image_dir ~/tf_files/tw/ \\\n--tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v1_100_224/feature_vector/1 \\\n--output_graph ~/new_training_dir/retrainedGraph.pb \\\n-\xe2\x80\x93saved_model_dir ~/new_training_dir/model/ \\\n--how_many_training_steps 500 \n\nsudo toco \\\n--input_file=retrainedGraph.pb \\\n--output_file=optimized_retrainedGraph.pb \\\n--input_format=TENSORFLOW_GRAPHDEF \\\n--output_format=TENSORFLOW_GRAPHDEF \\\n--input_shape=1,224,224,3 \\\n--input_array=Placeholder \\\n--output_array=final_result \\\n\nsudo toco \\\n--input_file=optimized_retrainedGraph.pb \\\n--input_format=TENSORFLOW_GRAPHDEF \\\n--output_format=TFLITE \\\n--output_file=retrainedGraph.tflite \\\n--inference_type=FLOAT \\\n--inference_input_type=FLOAT \\\n--input_arrays=Placeholder \\\n--output_array=final_result \\\n--input_shapes=1,224,224,3\n
Run Code Online (Sandbox Code Playgroud)\n\n

我在这里做错了什么吗?准确性的损失从何而来?

\n

Sus*_*nth 5

当我尝试将 .pb 模型转换为 .lite 时,我遇到了同样的问题。

事实上,我的准确率会从 95 下降到 30!

事实证明,我犯的错误不是在将 .pb 转换为 .lite 期间,也不是在执行此操作所涉及的命令中。但实际上是在加载图像并对其进行预处理时,然后将其传递到精简模型并使用推断

interpreter.invoke()
Run Code Online (Sandbox Code Playgroud)

命令。

您看到的下面的代码就是我所说的预处理的意思:

test_image=cv2.imread(file_name)
test_image=cv2.resize(test_image,(299,299),cv2.INTER_AREA)
test_image = np.expand_dims((test_image)/255, axis=0).astype(np.float32)
interpreter.set_tensor(input_tensor_index, test_image)
interpreter.invoke()
digit = np.argmax(output()[0])
#print(digit)
prediction=result[digit]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,一旦使用“imread()”读取图像,就会在图像上完成两个关键的命令/预处理:

i) 图像大小应调整为训练期间使用的输入图像/张量的“input_height”和“input_width”值的大小。在我的例子中(inception-v3),“input_height”和“input_width”都是 299。(阅读该值的模型文档,或者在用于训练或重新训练模型的文件中查找该变量

ii) 上述代码中的下一个命令是:

test_image = np.expand_dims((test_image)/255, axis=0).astype(np.float32)
Run Code Online (Sandbox Code Playgroud)

我从“公式”/模型代码中得到了这个:

test_image = np.expand_dims((test_image-input_mean)/input_std, axis=0).astype(np.float32)
Run Code Online (Sandbox Code Playgroud)

阅读文档发现,对于我的架构,input_mean = 0 和 input_std = 255。

当我对代码进行上述更改时,我得到了预期的准确性 (90%)。

希望这可以帮助。


小智 0

请在 GitHub https://github.com/tensorflow/tensorflow/issues上提交问题并在此处添加链接。另请添加更多有关您重新训练最后一层的详细信息。