向 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()

但是每当我尝试在 las 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:


我的数据集如下所示:


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)

我在这里错过了什么?


小怪兽爱吃肉
浏览 91回答 1
1回答

慕妹3146593

当您使用函数式 API 时,您想要使用:x&nbsp;=&nbsp;layers.Dense(200,&nbsp;activation='relu')(x) x&nbsp;=&nbsp;layers.Dropout(0.1)(x)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python