### 向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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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