Autoencoder ValueError:尺寸必须相等,但分别为 32 和 28

时间:2021-02-10 19:00:27

标签: python tensorflow machine-learning keras deep-learning

我正在尝试使用编码器和解码器创建非常简单的自动编码器,但不断收到以下错误。我使用的数据类似于 mnist,所以我用这个简单的代码重新创建了错误。但我无法解码错误。 所以它就像错误弹出是因为损失层在 y_pred 和 y_true 之间得到了错误的输入。

代码是:-

import warnings
warnings.filterwarnings("ignore")
from tensorflow.keras.models import Model
from tensorflow.keras import layers, losses
from tensorflow.keras.datasets import fashion_mnist
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf

(x_train, _), (x_test, _) = fashion_mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.

print (x_train.shape)
print (x_test.shape)
x_inp = tf.keras.Input(shape = (28,28))
# x = layers.Reshape((28,28,1))(x_inp)
# x = layers.Conv2D(5,(2,2), input_shape = (28,28,1))(x)
x = layers.Flatten()(x_inp)
encoded = layers.Dense(64, activation = "relu")(x)
decoded = layers.Dense(784, activation = "sigmoid")(encoded)
out = layers.Reshape((28,28))(decoded)
autoencoder = Model(x_inp, decoded)
autoencoder.compile(loss=losses.MeanSquaredError(), optimizer='adam')
encoder = Model(x_inp, encoded)
encoded_input = layers.Input(shape=(64,))
decoder_layer = autoencoder.layers[-1]
decoder = Model(encoded_input, decoder_layer(encoded_input))
print(autoencoder.summary())
autoencoder.fit(x_train, x_train, epochs = 5,shuffle = True, validation_data=(x_test, x_test))

关于如何解决这个问题的任何想法:

Epoch 1/5
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-65-820526943444> in <module>()
     23 decoder = Model(encoded_input, decoder_layer(encoded_input))
     24 print(autoencoder.summary())
---> 25 autoencoder.fit(x_train, x_train, epochs = 5,shuffle = True, validation_data=(x_test, x_test))

9 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    975           except Exception as e:  # pylint:disable=broad-except
    976             if hasattr(e, "ag_error_metadata"):
--> 977               raise e.ag_error_metadata.to_exception(e)
    978             else:
    979               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:756 train_step
        y, y_pred, sample_weight, regularization_losses=self.losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:203 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:152 __call__
        losses = call_fn(y_true, y_pred)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:256 call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1198 mean_squared_error
        return K.mean(math_ops.squared_difference(y_pred, y_true), axis=-1)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py:10251 squared_difference
        "SquaredDifference", x=x, y=y, name=name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:750 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py:592 _create_op_internal
        compute_device)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:3536 _create_op_internal
        op_def=op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:2016 __init__
        control_input_ops, op_def)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py:1856 _create_c_op
        raise ValueError(str(e))

    ValueError: Dimensions must be equal, but are 32 and 28 for '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT](model_41/dense_59/Sigmoid, IteratorGetNext:1)' with input shapes: [32,784], [32,28,28].

1 个答案:

答案 0 :(得分:0)

更改这一行:

autoencoder = Model(x_inp, out)