首页 > 解决方案 > 在 Keras 中的密集层之后重塑层

问题描述

我试图理解为什么密集层和重塑层之间存在不匹配的维度。这段代码不应该是正确的吗?Dense Layer输出的维数会是image_resize^2 * 128,为什么reshape有冲突?

input_shape = (28,28,1)
inputs = Input(shape=input_shape)
image_size = 28
image_resize = image_size // 4
x = Dense(image_resize * image_resize * 128)(inputs)
x = Reshape((image_resize, image_resize, 128))(x)

这是显示的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/venv/lib/python3.7/site-packages/keras/engine/base_layer.py", line 474, in __call__
    output_shape = self.compute_output_shape(input_shape)
  File "/Users/venv/lib/python3.7/site-packages/keras/layers/core.py", line 398, in compute_output_shape
    input_shape[1:], self.target_shape)
  File "/Users/venv/lib/python3.7/site-packages/keras/layers/core.py", line 386, in _fix_unknown_dimension
    raise ValueError(msg)
ValueError: total size of new array must be unchanged

标签: keras

解决方案


Dense图层作用于输入数据的最后一个维度,如果要将图像输入给Dense图层,则应首先将其展平:

x = Flatten()(x)
x = Dense(image_resize * image_resize * 128)(x)
x = Reshape((image_resize, image_resize, 128))(x)

然后Reshape意志起作用。


推荐阅读