我在一个包含两个不同类别的图像数据集上训练了一个模型,现在正尝试对新图像进行预测。我使用saved_model格式保存模型,并尝试加载并对模型进行单张图像的预测。我的代码如下
loaded = tf.keras.models.load_model('/Library/...')loaded.compile(loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1), optimizer=tf.keras.optimizers.SGD(lr=0.005, momentum=0.9), metrics=['accuracy'])test_image = image.load_img(img_path, target_size=(img_width, img_height))test_image = image.img_to_array(test_image)test_image = np.expand_dims(test_image, axis=0)test_image = test_image.reshape(img_width, img_height)result = loaded.predict(test_image)print(loaded.predict(test_image))print(result)
我得到的错误是:
Traceback (most recent call last): File "/Users/...", line 73, in <module> test_image = test_image.reshape(img_width, img_height)ValueError: cannot reshape array of size 268203 into shape (299,299)
我以为这是图像文件的问题,但这些图像与我用于训练的图像来自同一来源,并且在训练过程中没有遇到任何问题。所有文件都是RGB png格式(我以为问题出在它们是RGBA格式,但事实并非如此)。任何帮助将不胜感激!
回答:
你需要检查你的图像尺寸。你的数组元素数量必须是传递给.reshape
的参数的乘积。299*299不等于268203。
一个例子是
a = np.arange(6)
这些是有效的重塑方式:
a.reshape(1,6)a.reshape(2,3)a.reshape(3,2)a.reshape(6,1)
因为参数的乘积是6,这正是数组的长度。