ValueError:max_pooling2d_2层的输入0与该层不兼容:预期ndim = 4,找到的ndim = 5.收到的完整图形:[1,无,64、64、8] [英] ValueError: Input 0 of layer max_pooling2d_2 is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [1, None, 64, 64, 8]
问题描述
我正在进行CNN在线课程分配,该课程建立了卷积模型.说明如下:
I am doing a CNN online course assignment which builds a convolutional model. The instructions are listed as following:
练习2-卷积模型
实施下面的convolutional_model函数以构建以下模型: CONV2D->RELU->MAXPOOL->CONV2D->RELU->MAXPOOL->FLATTEN->DENSE .使用上面的功能!
Implement the convolutional_model function below to build the following model: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> DENSE. Use the functions above!
此外,为所有步骤插入以下参数:
Also, plug in the following parameters for all the steps:
- Conv2D:使用8个4×4过滤器,跨度1,填充为"SAME"
- ReLU
- MaxPool2D:使用8 x 8的滤镜大小和8 x 8的跨度,填充为"SAME"
- Conv2D:使用16个2 x 2过滤器,跨度1,填充为"SAME"
- ReLU
- MaxPool2D:使用4乘4的滤镜大小和4乘4的步幅,填充为"SAME"
- 平整先前的输出.
- 完全连接(密集)层:应用具有6个神经元和softmax激活的完全连接层.
代码在这里:
# GRADED FUNCTION: convolutional_model
def convolutional_model(input_shape):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> DENSE
Note that for simplicity and grading purposes, you'll hard-code some values
such as the stride and kernel (filter) sizes.
Normally, functions should take these values as function parameters.
Arguments:
input_img -- input dataset, of shape (input_shape)
Returns:
model -- TF Keras model (object containing the information for the entire training process)
"""
input_img = tf.keras.Input(shape=input_shape)
## CONV2D: 8 filters 4x4, stride of 1, padding 'SAME'
Z1 = tf.keras.layers.Conv2D(8,(4,4), strides=(1,1),padding='same')(input_img),
## RELU
A1 = tf.keras.layers.ReLU()(Z1),
## MAXPOOL: window 8x8, stride 8, padding 'SAME'
print("A1 size: ", str(A1)),
P1 = tf.keras.layers.MaxPool2D(pool_size=(8,8), strides=(8,8), padding='same')(A1),
#P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME')
## CONV2D: 16 filters 2x2, stride 1, padding 'SAME'
Z2 = tf.keras.layers.Conv2D(16,(2,2), strides=(1,1),padding='same' )(P1),
## RELU
A2 = tf.keras.layers.ReLU()(Z2),
## MAXPOOL: window 4x4, stride 4, padding 'SAME'
P2 = tf.keras.layers.MaxPool2D((4,4), strides=(4,4), padding='same')(A2),
## FLATTEN
F = tf.keras.layers.Flatten()(P2),
## Dense layer
## 6 neurons in output layer. Hint: one of the arguments should be "activation='softmax'"
outputs = tf.keras.layers.Dense(6, activation='softmax', name='fc')(F),
# YOUR CODE STARTS HERE
# YOUR CODE ENDS HERE
model = tf.keras.Model(inputs=input_img, outputs=outputs)
return model
但是,当我运行以下代码进行测试
However, when I run following code for testing
conv_model = convolutional_model((64, 64, 3))
conv_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
conv_model.summary()
output = [['InputLayer', [(None, 64, 64, 3)], 0],
['Conv2D', (None, 64, 64, 8), 392, 'same', 'linear', 'GlorotUniform'],
['ReLU', (None, 64, 64, 8), 0],
['MaxPooling2D', (None, 8, 8, 8), 0, (8, 8), (8, 8), 'same'],
['Conv2D', (None, 8, 8, 16), 528, 'same', 'linear', 'GlorotUniform'],
['ReLU', (None, 8, 8, 16), 0],
['MaxPooling2D', (None, 2, 2, 16), 0, (4, 4), (4, 4), 'same'],
['Flatten', (None, 64), 0],
['Dense', (None, 6), 390, 'softmax']]
comparator(summary(conv_model), output)
我收到错误消息:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-f1284300b767> in <module>
----> 1 conv_model = convolutional_model((64, 64, 3))
2 conv_model.compile(optimizer='adam',
3 loss='categorical_crossentropy',
4 metrics=['accuracy'])
5 conv_model.summary()
<ipython-input-23-610251af1ba8> in convolutional_model(input_shape)
28 ## MAXPOOL: window 8x8, stride 8, padding 'SAME'
29 print("A1 size: ", str(A1)),
---> 30 P1 = tf.keras.layers.MaxPool2D(pool_size=(8,8), strides=(8,8), padding='same')(A1),
31 #P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME')
32 ## CONV2D: 16 filters 2x2, stride 1, padding 'SAME'
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, *args, **kwargs)
924 if _in_functional_construction_mode(self, inputs, args, kwargs, input_list):
925 return self._functional_construction_call(inputs, args, kwargs,
--> 926 input_list)
927
928 # Maintains info about the `Layer.call` stack.
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in _functional_construction_call(self, inputs, args, kwargs, input_list)
1090 # TODO(reedwm): We should assert input compatibility after the inputs
1091 # are casted, not before.
-> 1092 input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
1093 graph = backend.get_graph()
1094 # Use `self._name_scope()` to avoid auto-incrementing the name.
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
178 'expected ndim=' + str(spec.ndim) + ', found ndim=' +
179 str(ndim) + '. Full shape received: ' +
--> 180 str(x.shape.as_list()))
181 if spec.max_ndim is not None:
182 ndim = x.shape.ndims
ValueError: Input 0 of layer max_pooling2d_2 is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [1, None, 64, 64, 8]
看起来像我的 MaxPool2D(pool_size =(8,8),stride =(8,8),padding ='same')
一样有问题.如指令所述,"MaxPool2D:使用8×8的过滤器尺寸和8×8的跨度,填充为"SAME",我对我的MaxPool2D无法正常工作感到困惑吗?我该如何纠正?非常感谢.
Looks like the my MaxPool2D(pool_size=(8,8), strides=(8,8), padding='same')
has problems.
As the instruction says, "MaxPool2D: Use an 8 by 8 filter size and an 8 by 8 stride, padding is "SAME"", I am confused on what my MaxPool2D is not working as it should? How should I correct it? Thanks a lot.
推荐答案
您(偶然)在每个层的末尾使用逗号(,
),这在构建模型时不正确.删除逗号,它应该可以工作.
You (accidentally) use commas (,
) at the end of each layer which is not right when you build the model. Remove the commas and it should work.
conv_model = convolutional_model((64, 64, 3))
conv_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
conv_model.summary()
conv_model = convolutional_model((64, 64, 3))
conv_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
conv_model.summary()
A1 size: KerasTensor(type_spec=TensorSpec(shape=(None, 64, 64, 8), dtype=tf.float32, name=None), name='re_lu_9/Relu:0', description="created by layer 're_lu_9'")
Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_9 (InputLayer) [(None, 64, 64, 3)] 0
_________________________________________________________________
conv2d_9 (Conv2D) (None, 64, 64, 8) 392
_________________________________________________________________
re_lu_9 (ReLU) (None, 64, 64, 8) 0
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 8, 8, 8) 0
_________________________________________________________________
conv2d_10 (Conv2D) (None, 8, 8, 16) 528
_________________________________________________________________
re_lu_10 (ReLU) (None, 8, 8, 16) 0
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 2, 2, 16) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 64) 0
_________________________________________________________________
fc (Dense) (None, 6) 390
=================================================================
Total params: 1,310
Trainable params: 1,310
Non-trainable params: 0
_________________________________________________________________
这篇关于ValueError:max_pooling2d_2层的输入0与该层不兼容:预期ndim = 4,找到的ndim = 5.收到的完整图形:[1,无,64、64、8]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!