AttributeError:“扁平”对象没有属性“形状”
Posted
技术标签:
【中文标题】AttributeError:“扁平”对象没有属性“形状”【英文标题】:AttributeError: 'Flatten' object has no attribute 'shape' 【发布时间】:2022-01-14 23:25:51 【问题描述】:我是 TensorFlow 新手,正在尝试使用 tf.keras.layers
API 实现 CNN 模型。这是我正在尝试实现的代码。
def convolutional_model(input_shape):
input_img = tf.keras.Input(shape=input_shape)
Z1 = tf.keras.layers.Conv2D(filters = 16 , kernel_size= (4,4), strides = (1,1), padding='same')(input_img)
A1 = tf.keras.layers.ReLU()
P1 = tf.keras.layers.MaxPool2D(pool_size=(8,8), strides=(8, 8), padding='same')
Z2 = tf.keras.layers.Conv2D(filters = 16 , kernel_size= (2,2), strides = (1,1), padding='same')(input_img)
A2 = tf.keras.layers.ReLU()
P2 = tf.keras.layers.MaxPool2D(pool_size=(4,4), strides=(4, 4), padding='valid')
F = tf.keras.layers.Flatten()
outputs = tf.keras.layers.Dense(units=6, activation='softmax')(F)
model = tf.keras.Model(inputs=input_img, outputs=outputs)
return model
当我尝试运行它时,我收到以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-66-12f400853748> in convolutional_model(input_shape)
43 P2 = tf.keras.layers.MaxPool2D(pool_size=(4,4), strides=(4, 4), padding='valid')
44 F = tf.keras.layers.Flatten()
---> 45 outputs = tf.keras.layers.Dense(units=6, activation='softmax')(F)
46
47 # YOUR CODE ENDS HERE
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, *args, **kwargs)
980 with ops.name_scope_v2(name_scope):
981 if not self.built:
--> 982 self._maybe_build(inputs)
983
984 with ops.enable_auto_cast_variables(self._compute_dtype_object):
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in _maybe_build(self, inputs)
2616 if not self.built:
2617 input_spec.assert_input_compatibility(
-> 2618 self.input_spec, inputs, self.name)
2619 input_list = nest.flatten(inputs)
2620 if input_list and self._dtype_policy.compute_dtype is None:
/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
164 spec.min_ndim is not None or
165 spec.max_ndim is not None):
--> 166 if x.shape.ndims is None:
167 raise ValueError('Input ' + str(input_index) + ' of layer ' +
168 layer_name + ' is incompatible with the layer: '
AttributeError: 'Flatten' object has no attribute 'shape'
当我将F
替换为input_img
时,该函数运行没有任何错误,但这不是我想要的输出。
有人可以帮我解决这个问题吗?
【问题讨论】:
【参考方案1】:Keras functional API 的设计目的是让您将模型的前一层作为输入传递给下一层。对于您定义的大多数层,您并没有真正这样做,而是使它们成为彼此不连接的独立层。要将一层的结果传递给另一层,您需要通过传入上一层来调用该层。例如,您的意思可能是这样的。
Z1 = tf.keras.layers.Conv2D(filters = 16 , kernel_size= (4,4), strides = (1,1), padding='same')(input_img)
A1 = tf.keras.layers.ReLU()(Z1)
【讨论】:
我通过了前面的层并且它起作用了。非常感谢!以上是关于AttributeError:“扁平”对象没有属性“形状”的主要内容,如果未能解决你的问题,请参考以下文章
AttributeError:“NumpyArrayIterator”对象没有属性“类”
AttributeError:'list' 对象没有属性 'size'
AttributeError:“模块”对象没有属性“WebSocketApp”
AttributeError: 'float' 对象没有属性 'split'