我已经用80x80x3图像样本训练了AutoML Vision。培训已成功完成,我下载了Edge tflite模型。当在python中实现tflite模型时,根据此tutorial by tensorflow,我意识到tflite模型的输入大小为224x224x3。
我的问题是:
为了获得更好的预测性能,我希望按照训练期间AutoML Vision处理图像的方式来处理新图像。
向模型输入具有输入形状(1、80、80、3)的80x80图像时,出现异常“无法设置张量:尺寸不匹配”,请参见下面的代码。
馈送224x224图像无例外。但是,我想使用80x80x3的图像,就像我用于训练的图像一样。或像在AutoML Vision中训练时一样对80x80x3图像进行预处理,例如,将它们调整为224x224x3大小,或者由AutoML Vision处理。
test_sample.shape
Out: (80, 80, 3)
test_sample = test_sample.reshape(1, 80, 80, 3)
Out: (1, 80, 80, 3)
# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
print(interpreter.get_input_details())
Out: [{'name': 'image', 'index': 0, 'shape': array([ 1, 224, 224, 3], dtype=int32), 'dtype': <class 'numpy.uint8'>, 'quantization': (0.007874015718698502, 128)}]
output_details = interpreter.get_output_details()
# Test model on input data.
input_data = np.array(test_sample, dtype=np.uint8)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
Out: ValueError: Cannot set tensor: Dimension mismatch
ValueError Traceback (most recent call last)
in engine
----> 1 interpreter.set_tensor(input_details[0]['index'], input_data)
/home/cdsw/.local/lib/python3.6/site-packages/tensorflow/lite/python/interpreter.py in set_tensor(self, tensor_index, value)
173 ValueError: If the interpreter could not set the tensor.
174 """
--> 175 self._interpreter.SetTensor(tensor_index, value)
176
177 def resize_tensor_input(self, input_index, tensor_size):
/home/cdsw/.local/lib/python3.6/site-packages/tensorflow/lite/python/interpreter_wrapper/tensorflow_wrap_interpreter_wrapper.py in SetTensor(self, i, value)
134
135 def SetTensor(self, i, value):
--> 136 return _tensorflow_wrap_interpreter_wrapper.InterpreterWrapper_SetTensor(self, i, value)
137
138 def GetTensor(self, i):
ValueError: Cannot set tensor: Dimension mismatch
我建议您使用此实现
设置dtype
# check the type of the input tensor
floating_model = input_details[0]['dtype'] == np.float32
根据所需的模型高度和宽度调整图像大小
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
img = Image.open(args.image).resize((width, height))
设置输入数据
input_data = np.expand_dims(img, axis=0)
这里是完整的示例https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py