我想通过上传一张图片来测试我的模型,但遇到了这个错误。我认为错误可能出现在这些代码行中,但我不知道如何修复。
IMAGE_SIZE = [244,720]inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet',include_top=False)
这是我上传测试图片的代码
picture = image.load_img('/content/DSC_0365.JPG', target_size=(244,720))img = img_to_array(picture)prediction = model.predict(img)print (prediction)
我在机器学习方面还是个新手,所以目前的知识还不够深入。
回答:
这主要是因为你没有为你的Inception模型准备好输入(其维度)。这里是一个可能的解决方案。
模型
from tensorflow.keras.applications import *IMAGE_SIZE = [244,720]inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)# 检查其输入形状 inception.input_shape(None, 244, 720, 3)
推断
让我们通过将一个样本传递给模型来进行测试。
from PIL import Image a = Image.open('/content/1.png').convert('RGB')display(a)
检查其基本属性。
a.mode, a.size, a.format('RGB', (297, 308), None)
因此,它的形状已经是(297 x 308 x 3
)。但为了能够将其传递给模型,我们需要一个额外的轴,即批处理轴。为了做到这一点,我们可以这样做
import tensorflow as tfimport numpy as np a = tf.expand_dims(np.array(a), axis=0)a.shapeTensorShape([1, 308, 297, 3])
这样更好。现在,我们可能需要根据模型输入形状来规范化我们的数据并调整其大小。为了做到这一点,我们可以这样做:
a = tf.divide(a, 255) a = tf.image.resize(a, [244,720]) a.shapeTensorShape([1, 244, 720, 3])
最后,将其传递给模型。
inception(a).shapeTensorShape([1, 6, 21, 2048])# 或者,保留预测以便后续分析 y_pred = inception(a)
更新
如果你使用的是[tf.keras]
图像处理函数,该函数将图像加载到PIL格式,那么我们可以简单地这样做:
image = tf.keras.preprocessing.image.load_img('/content/1.png', target_size=(244,720))input_arr = tf.keras.preprocessing.image.img_to_array(image)input_arr = np.array([input_arr]) # 将单张图像转换为批处理。inception(input_arr).shapeTensorShape([1, 6, 21, 2048])