首页 > 解决方案 > 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)

标签: python-3.xtensorflowkerasconv-neural-network

解决方案


这个错误是因为模型输出和训练数据之间的形状不匹配。

请参考下面的示例代码

#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

推荐阅读