我想在这个CNN架构中添加一个全局平均池化层,后面跟着几个全连接层:
img_input = layers.Input(shape=(img_size, img_size, 1))x = layers.Conv2D(16, (3,3), activation='relu', strides = 1, padding = 'same')(img_input)x = layers.MaxPool2D(pool_size=2)(x)x = layers.Conv2D(32, (3,3), activation='relu', strides = 2)(x)x = layers.MaxPool2D(pool_size=2)(x)x = layers.Conv2D(64, (3,3), activation='relu', strides = 2)(x)x = layers.MaxPool2D(pool_size=2)(x)x = layers.Conv2D(3, 5, activation='relu', strides = 2)(x)x = layers.Dense(200,activation='relu')x = layers.Dropout(0.1)output = layers.Flatten()(x)model = Model(img_input, output)model.summary()
但每当我尝试在最后一个Conv2D层之后添加一个全连接层时,我会得到以下错误:
---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-370-1cf54963b964> in <module> 11 x = layers.Dropout(0.1) 12 ---> 13 output = layers.Flatten()(x) 14 15 model = Model(img_input, output)/usr/local/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs) 885 # Eager execution on data tensors. 886 with backend.name_scope(self._name_scope()):--> 887 self._maybe_build(inputs) 888 cast_inputs = self._maybe_cast_inputs(inputs) 889 with base_layer_utils.autocast_context_manager(/usr/local/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in _maybe_build(self, inputs) 2120 if not self.built: 2121 input_spec.assert_input_compatibility(-> 2122 self.input_spec, inputs, self.name) 2123 input_list = nest.flatten(inputs) 2124 if input_list and self._dtype_policy.compute_dtype is None:/usr/local/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name) 161 spec.min_ndim is not None or 162 spec.max_ndim is not None):--> 163 if x.shape.ndims is None: 164 raise ValueError('Input ' + str(input_index) + ' of layer ' + 165 layer_name + ' is incompatible with the layer: 'AttributeError: 'Dropout' object has no attribute 'shape'
我的数据集看起来像这样:
print(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)(1600, 200, 200, 1) (400, 200, 200, 1) (1600, 3) (400, 3)
我在这里遗漏了什么?
回答:
由于您使用的是函数式API,您应该使用以下方式:
x = layers.Dense(200, activation='relu')(x)x = layers.Dropout(0.1)(x)