TensorFlow图像分类模型预测时输入形状不匹配报错如何解决
报错原因
- 调用
tf.image.decode_image解码图片后输出张量没有固定静态形状,TensorFlow无法正确识别输入的20x20尺寸 - 单张图片预测时缺少batch维度,模型要求输入格式为
(batch_size, 宽度, 高度, 通道数),单张样本需要补充第一维的batch_size参数(值为1) - 调用
model.predict()时多余的列表包装会被识别为多输入参数,加剧维度解析错误
最简解决方案
方案1(推荐,一次修改适配所有测试样本)
修改prepare_for_test函数,补充尺寸校准、形状声明、batch维度添加逻辑:
def prepare_for_test(filepath): img_array = tf.io.read_file(filepath) img_array = tf.image.decode_image(img_array, channels=3, dtype=tf.float32) # 强制校准为训练用的20x20尺寸,避免测试样本尺寸不一致 img_array = tf.image.resize(img_array, (20, 20)) # 手动声明静态形状,解决decode_image的形状丢失问题 img_array.set_shape((20, 20, 3)) # 新增batch维度,匹配模型输入要求 img_array = tf.expand_dims(img_array, axis=0) return img_array
同步修改predict调用代码,去掉多余的列表包装:
prediction = model.predict(prepare_for_test('avia-test/00a90c41-965e-45d0-90c2-391e20cb25b7.png')) print(prediction)
方案2(无需修改原函数,临时调试用)
直接在预测代码中补充维度处理逻辑:
test_img = prepare_for_test('avia-test/00a90c41-965e-45d0-90c2-391e20cb25b7.png') # 校准尺寸+添加batch维度 test_img = tf.expand_dims(tf.image.resize(test_img, (20, 20)), 0) prediction = model.predict(test_img) print(prediction)
验证方式
修改完成后可先打印输入张量的形状,输出为(1, 20, 20, 3)即符合模型输入要求:
print(prepare_for_test('你的测试图片路径').shape)
内容的提问来源于stack exchange,提问作者svetadomoi
相关产品推荐
相关产品推荐

