将Mobilenet模型转换为TFLite会改变输入大小



现在我正试图将SavedModel转换为TFLite以用于树莓派。该模型是在自定义数据集上训练的MobileNet对象检测。SavedModel工作完美,并保留了(1, 150, 150, 3)相同的形状。但是,当我使用以下代码将其转换为TFLite模型时:

import tensorflow as tf
saved_model_dir = input("Model dir: ")
# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)

然后运行下面的代码来运行解释器:

import numpy as np
import tensorflow as tf
from PIL import Image
from os import listdir
from os.path import isfile, join
from random import choice, random
# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']
print(f"Required input shape: {input_shape}")

我得到[1 1 1 3]的输入形状,因此我不能使用150x150的图像作为输入。

我使用Tensorflow 2.4在Python 3.7.10与Windows 10。

我该如何解决这个问题?

您可以依靠TFLite转换器V1 API来设置输入形状。请查看https://www.tensorflow.org/api_docs/python/tf/compat/v1/lite/TFLiteConverter中的input_shapes参数。

在调用allocate_tensors()之前调用resize_tensor_input()如何?

interpreter.resize_tensor_input(0, [1, 150, 150, 3], strict=True)
interpreter.allocate_tensors()

最新更新