python - 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]
我知道我做错了什么,但在更正我的代码之前,我真的很想了解为什么我会收到这个错误是什么导致它,实际发生了什么?
解决方案
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)
推荐阅读
- javascript - 来自服务器 json 对象的数据表
- html - HTML:如何删除两个按钮之间的 <
- docker - osx docker 运行 elasticsearch 进行开发
- javascript - Coffeescript 相当于 On Document Ready
- c# - 在 C# 中使用 Html Agility Pack 获取 InnerText 忽略脚本节点
- sql - 同时进行枢轴和交叉连接
- java - 如何在@RequestBody 中传递 2 个对象?
- java - schtasks 以管理员权限返回错误 5
- c# - 如何修复 System.Data.SqlClient.SqlException:用户登录失败
- python - 通过http python发送图像