我不明白我的问题是什么。它应该可以工作,只是因为它是张量流文档中的标准自动编码器。 这是错误
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))
我尝试更改数据库,也尝试了不同的形状
在尝试使用 Keras 3 获取这个示例时,我遇到了相同的错误。无效的 dtype 错误是因为解码器中的 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)