我正在查看文档中的示例: https://www.tensorflow.org/tutorials/generative/autoencoder
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, losses
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Model
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(), # flattens input WITHOUT affecting batch size
layers.Dense(latent_dim, activation='relu'),
])
self.decoder = tf.keras.Sequential([
layers.Dense(tf.math.reduce_prod(shape).numpy(),
activation='sigmoid'),
layers.Reshape(shape)
])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
# (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) # (60000, 28, 28)
print(x_test.shape) # (10000, 28, 28)
shape = x_test.shape[1:]
latent_dim = 64
autoencoder = Autoencoder(latent_dim, shape)
autoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError())
# autoencoder.build(input_shape=x_train.shape) # nope
# autoencoder.build(input_shape=(None, 28, 28)) # nope
# autoencoder.summary()
我想构建模型来获得摘要。 input_shape 应该是什么?输入尺寸为 28x28 的图像。
我希望这能起作用:
autoencoder.build(input_shape=(None, 28, 28))
非常感谢!
谢谢您的建议。
重新审视这个例子:
autoencoder.build(input_shape=x_train.shape)
autoencoder.summary()
产量:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
sequential (Sequential) (60000, 64) 50240
sequential_1 (Sequential) (60000, 28, 28) 50960
=================================================================
Total params: 101,200
以下:
autoencoder.build(input_shape=(None, 28, 28))
autoencoder.summary()
产量:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
sequential_2 (Sequential) (None, 64) 50240
sequential_3 (Sequential) (None, 28, 28) 50960
=================================================================
Total params: 101,200
Trainable params: 101,200
Non-trainable params: 0
_________________________________________________________________
在这两种情况下,第一层的参数数量都是 28 x 28 x 64 + 64 = 50240,正如预期的那样。
感谢您的提示!