python-3.x - ValueError:检查目标时出错:预期 conv2d_37 的形状为 (57, 57, 16) 但数组的形状为 (120, 120, 3)
问题描述
我的训练变量形状是 (264, 120, 120, 3) 试图将图像的 numpy 数组作为输入
model = Sequential()
model.add(Conv2D(8, (3, 3), activation='relu', strides=2,input_shape=(image_height,image_width,channels)))
model.add(Conv2D(16, (3, 3), activation='relu'))
model.summary()
model.compile(optimizer='rmsprop', loss='mse')
model.fit(x=X_train, y=y_train, batch_size=1, epochs=1, verbose=1)
下面是错误信息
________________________________________________________________
Layer (type) Output Shape Param
=================================================================
conv2d_36 (Conv2D) (None, 59, 59, 8) 224
_________________________________________________________________
conv2d_37 (Conv2D) (None, 57, 57, 16) 1168
=================================================================
Total params: 1,392
Trainable params: 1,392
Non-trainable params: 0
ValueError: Error when checking target: expected conv2d_37 to have shape (57, 57, 16) but got array with shape (120, 120, 3)
解决方案
这个错误是因为模型输出和训练数据之间的形状不匹配。
请参考下面的示例代码
#Import Dependencies
import keras
from keras.models import Model, Sequential
from keras.layers import Conv2D, Flatten, Dense
# Model Building
model = Sequential()
model.add(Conv2D(8, (3, 3), activation='relu', strides=2, input_shape=(28,28,1)))
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['mse'])
# Generate dummy data
import numpy as np
data = np.random.random((100, 28, 28, 1))
labels = np.random.randint(2, size=(100, 10))
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=5, batch_size=32)
输出:
Epoch 1/5
100/100 [==============================] - 0s 1ms/step - loss: 1.2342 - mse: 0.4195
Epoch 2/5
100/100 [==============================] - 0s 234us/step - loss: 1.2183 - mse: 0.4167
Epoch 3/5
100/100 [==============================] - 0s 222us/step - loss: 1.2104 - mse: 0.4151
Epoch 4/5
100/100 [==============================] - 0s 255us/step - loss: 1.2019 - mse: 0.4131
Epoch 5/5
100/100 [==============================] - 0s 239us/step - loss: 1.1938 - mse: 0.4120
推荐阅读
- docker - 如何启动具有主机名和 IP 地址的容器,以便它们连续运行?
- bash - 使用输入从文件运行 bash 脚本
- sql-server - 使用两个连接到同一个表的慢速执行 T-SQL 查询
- url - 从 Google 表格中复制的文本中提取 URL
- sql - 以 5 年为增量获得多个计数
- ruby-on-rails - 服务器重新启动,网站给出 502 Bad Gateway
- powershell - 为变量转义 Powershell 中的所有密码特殊字符
- react-native - React Native - 如何检查 URL 是否为有效图像
- javascript - 使用 match() 进行正则表达式反应应用程序出错
- javascript - 什么是迭代器/生成器/可迭代?(Javascript)