输入0与模型model_1不兼容:预期形状为(None, 244, 720, 3),实际发现形状为(None, 720, 3)

我想通过上传一张图片来测试我的模型,但遇到了这个错误。我认为错误可能出现在这些代码行中,但我不知道如何修复。

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)

enter image description here

检查其基本属性。

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])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注