【问题标题】:Predict_classes() keras model ValueError: Input 0 of layer sequential_1 is incompatible with the layer:Predict_classes() keras model ValueError: Input 0 of layer sequence_1 is in compatible with the layer:
【发布时间】:2021-08-18 17:11:11
【问题描述】:

好的,我是新手,我正在尝试对交通标志图像进行分类,我实际上是在构建 Keras 模型之后,关注 Kaggle 的笔记本

from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout

model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(43, activation='softmax'))

#Compilation of the model
model.compile(
    loss='categorical_crossentropy', 
    optimizer='adam', 
    metrics=['accuracy']
)

现在对于模型拟合后的测试部分,我找到的代码是这样的

y_test=pd.read_csv("C:/Users/Louay/input/test.csv")
labels=y_test['Path'].to_numpy()
y_test=y_test['ClassId'].values

data=[]

for f in labels:
    image=cv2.imread('C:/Users/Louay/input/Test/'+f.replace('Test/', ''))
    image_from_array = Image.fromarray(image, 'RGB')
    size_image = image_from_array.resize((height, width))
    data.append(np.array(size_image))

X_test=np.array(data)
X_test = X_test.astype('float32')/255 
pred = model.predict_classes(X_test)

这很有效,它可以正确预测测试集中所有图像的类别我的问题是,当我试图从测试集中仅预测 1 个图像时,好吧,我想我会重复相同的图像处理部分,然后使用 predict_classes()所以我的代码应该是这样的

image=cv2.imread('C:/Users/Louay/input/Test/00000.png')
image_from_array = Image.fromarray(image, 'RGB')
size_image = image_from_array.resize((height, width))
test=np.array(size_image)

pred = model.predict_classes(test.astype('float32')/255)

好的,我正在处理 1 张图像,所以我认为我不需要添加所有已处理图像的 data[] 列表,但是当我运行代码时出现此错误

   ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, None, 3]

我知道我做错了什么,但在更正我的代码之前,我真的很想了解为什么会出现此错误,是什么原因造成的,实际发生了什么?

【问题讨论】:

  • 如果您这样做test=np.array([size_image]) 是否会更好,因此当您将单个图像转换为数组时,它会在列表中?这看起来更像是当你有多个测试图像时发生的事情。如果可行,您可以查看两个不同版本的 test(带和不带 [])以了解数组有何不同。
  • 等等,我刚试过test=np.array(size_image),然后test=np.array([test]),它对我有用,但为什么呢?我的意思是看起来我在np.array 的列表上做np.array
  • 试试type(size_image) 看看它是什么。其他尝试的方法可能是test.shapetest.sizelen(test)。还有help(model.predict_classes).
  • 尝试 tf.expand_dims 为您的单个图像添加维度。示例:tensorflow.org/api_docs/python/tf/expand_dims

标签: python tensorflow keras tf.keras predict


【解决方案1】:

Conv2D 需要 4+D 张量,形状为:batch_shape + (channels, rows, cols),如果 data_format='channels_first',或 4+D 张量,形状:batch_shape + (rows, cols, channels),如果 data_format='channels_last'。

使用tf.expand_dims为您的输入添加额外的维度

工作示例代码

import tensorflow as tf

image = tf.zeros([10,10,3])
input_shape = tf.expand_dims(image, axis=0).shape.as_list()

x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv2D(
2, 3, activation='relu', input_shape=input_shape[1:])(x)
print(y.shape)

输出

(1, 8, 8, 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2022-11-06
    • 2022-09-30
    • 2022-01-03
    • 2021-05-05
    • 2021-06-29
    • 2022-09-24
    相关资源
    最近更新 更多