首页 > 解决方案 > Predict_classes() keras model ValueError: Input 0 of layer sequence_1 is in compatible with the layer:

问题描述

好的,我对此很陌生,我正在尝试对交通标志图像进行分类,我实际上是在构建 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]

我知道我做错了什么,但在更正我的代码之前,我真的很想了解为什么我会收到这个错误是什么导致它,实际发生了什么?

标签: pythontensorflowkerastf.keraspredict

解决方案


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)

推荐阅读