### 向CNN中添加全连接层

我想在这个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)

Related Posts

将一个模型的输出与另一个模型结合

我目前正在开发一个模型,根据产品描述预测其类别。模型的…

使用f2分数评估多个分类器

我正在尝试对一些模型进行二元分类。我希望根据分数和f2…

GridSearchCV 不显示详细级别

GridSearchCV 函数中的 Verbose 参…

在Keras中创建采样层

我正在尝试构建一个自定义的Keras层,该层从前一个s…

为什么XGBoost在全零数据集上返回非零预测?

我最近开发了一个完全功能的随机森林回归软件,使用的是s…

在Caret中显式设置Random Forest的ntree和mtry

我试图在使用Caret的Random Forest算法…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注