ValueError:新数组的总大小必须保持不变(从keras重塑)

时间:2019-08-08 10:57:53

标签: python numpy tensorflow keras python-3.6

对于此玩具模型:

from keras.layers import Input, Dense, Reshape
from keras.models import Model

# this is the size of our encoded representations
compression = 10  

input_img = Input(shape=(28,28, ), name= "28x28")
encoded = Dense(int(np.floor(28*28/compression)), activation='relu', 
                name= "encoder_" + str(compression))(input_img)
decoded = Dense(units = 28*28, activation='sigmoid',
                name = "28.28_decoder")(encoded)
reshape = Reshape(target_shape = (28,28), name = "28x28_reshape")(decoded)
autoencoder = Model(input_img, reshape)

我得到了错误:

ValueError                                Traceback (most recent call last)
<ipython-input-27-04b835543369> in <module>
     12 decoded = Dense(units = 28*28, activation='sigmoid',
     13                 name = "28.28_decoder")(encoded)
---> 14 reshape = Reshape(target_shape = (28,28), name = "28x28_reshape")(decoded)
     15 autoencoder = Model(input_img, reshape)
     16 

~/.local/lib/python3.6/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    472             if all([s is not None
    473                     for s in to_list(input_shape)]):
--> 474                 output_shape = self.compute_output_shape(input_shape)
    475             else:
    476                 if isinstance(input_shape, list):

~/.local/lib/python3.6/site-packages/keras/layers/core.py in compute_output_shape(self, input_shape)
    396             # input shape known? then we can compute the output shape
    397             return (input_shape[0],) + self._fix_unknown_dimension(
--> 398                 input_shape[1:], self.target_shape)
    399 
    400     def call(self, inputs):

~/.local/lib/python3.6/site-packages/keras/layers/core.py in _fix_unknown_dimension(self, input_shape, output_shape)
    384             output_shape[unknown] = original // known
    385         elif original != known:
--> 386             raise ValueError(msg)
    387 
    388         return tuple(output_shape)

ValueError: total size of new array must be unchanged

我一直试图找出原因,但我不明白。从help page来看,它非常简单,因为上一层足以执行整形。

2 个答案:

答案 0 :(得分:0)

您的解码密集层具有28 * 28个单位,这将使其输出变暗为(,28,784),而不会重塑为28 * 28。

答案 1 :(得分:0)

根据您要执行的操作,应该事先将数组展平。这应该起作用:

flatten = Flatten()(input_img)
encoded = Dense(int(np.floor(28*28/compression)), activation='relu',  name= "encoder_" + str(compression))(flatten)
decoded = Dense(units = 28*28, activation='sigmoid', name = "28.28_decoder" (encoded)
reshape = Reshape(target_shape = (28,28), name = "28x28_reshape")(decoded)
autoencoder = Model(input_img, reshape)

我认为最初的重塑无效,因为您正在通过密集层传递3D张量,并且初始尺寸被弄乱了。因此,您可以将其恢复为初始形状。