autoencoder.fit因ValueError无法工作
我不太明白我的问题出在哪里。这个代码应该能正常运行,因为它是tensorflow文档中的标准自编码器。
这是我遇到的错误:
line 64, in call
decoded = self.decoder(encoded)
ValueError: Exception encountered when calling Autoencoder.call().
Invalid dtype: <property object at 0x7fb471cc1c60>
Arguments received by Autoencoder.call():
• x=tf.Tensor(shape=(32, 28, 28), dtype=float32)
这是我的代码:
(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)
class Autoencoder(Model):
def __init__(self, latent_dim, shape):
super(Autoencoder, self).__init__()
self.latent_dim = latent_dim
self.shape = shape
self.encoder = tf.keras.Sequential([
layers.Flatten(),
layers.Dense(latent_dim, activation='relu'),
])
self.decoder = tf.keras.Sequential([
layers.Dense(tf.math.reduce_prod(shape), activation='sigmoid'),
layers.Reshape(shape)
])
def call(self, x):
encoded = self.encoder(x)
print(encoded)
decoded = self.decoder(encoded)
print(decoded)
return decoded
shape = x_test.shape[1:]
latent_dim = 64
autoencoder = Autoencoder(latent_dim, shape)
autoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError())
autoencoder.fit(x_train, x_train,
epochs=10,
shuffle=True,
validation_data=(x_test, x_test))
我尝试过更换数据库,也试过不同的形状。
1 个回答
0
我在尝试用 Keras 3 运行这个例子时遇到了同样的错误。这个“无效的数据类型”错误是因为解码器中的 Dense 层需要一个正整数,但 reduce_prod
返回的是一个标量张量。你需要用比如说 numpy()
来提取这个标量值:
layers.Dense(tf.math.reduce_prod(shape).numpy(), activation='sigmoid')
修复了这个错误后,我又遇到了一个关于批量大小的问题(例子中的模型不支持批量维度),我通过在编码器中添加一个初始的 Input
层来解决这个问题。下面是我转换为 Keras 3 的自编码器模型:
class Autoencoder(keras.Model):
def __init__(self, latent_dim, shape):
super().__init__()
self.latent_dim = latent_dim
self.shape = shape
self.encoder = keras.Sequential([
keras.Input(shape),
keras.layers.Flatten(),
keras.layers.Dense(latent_dim, activation='relu'),
])
self.decoder = keras.Sequential([
keras.layers.Dense(keras.ops.prod(shape).numpy(), activation='sigmoid'),
keras.layers.Reshape(shape)
])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
shape = x_test.shape[1:]
latent_dim = 64
autoencoder = Autoencoder(latent_dim, shape)