import tensorflow as tf import matplotlib.pyplot as plt

查看Tensorflow版本

1
tf.__version__

加载数据集

1
(x_train,_),(x_test,_) = tf.keras.datasets.mnist.load_data()

扁平化

1
2
x_train = x_train.reshape(x_train.shape[0],-1)#-1 表示自动计算
x_test = x_test.reshape(x_test.shape[0],-1)
1
2
3
x_train.shape,x_test.shape
((60000, 28, 28), (10000, 28, 28))
((60000, 784), (10000, 784))

归一化

1
2
x_train = tf.cast(x_train,tf.float32)/255
x_test = tf.cast(x_test,tf.float32)/255

设置输入、输出、压缩大小

1
2
3
input_size = 784
hidden_size = 32
output_size = 784

模型结构

1
2
3
4
5
6
7
8
9
input = tf.keras.layers.Input(shape=(input_size,))

#encode
en = tf.keras.layers.Dense(hidden_size,activation='relu')(input)

#decode
de = tf.keras.layers.Dense(output_size,activation='sigmoid')(en)

model = tf.keras.Model(inputs=input,outputs=de)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
model.summary()
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 784)] 0
_________________________________________________________________
dense (Dense) (None, 32) 25120
_________________________________________________________________
dense_1 (Dense) (None, 784) 25872
=================================================================
Total params: 50,992
Trainable params: 50,992
Non-trainable params: 0
_________________________________________________________________

绘制模型

1
tf.keras.utils.plot_model(model,show_shapes=True)#可视化

模型配置

1
2
3
model.compile(optimizer='adam',
loss='mse'
)

模型训练

1
2
3
4
5
6
model.fit(x_train,x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test,x_test)
)

模型使用

编码

1
encode = tf.keras.Model(inputs=input,outputs=en)

解码

1
2
3
4
input_de = tf.keras.layers.Input(shape=(hidden_size,))
output_de = model.layers[-1](input_de)

decode = tf.keras.Model(inputs=input_de,outputs=output_de)
1
2
3
4
encode_test = encode(x_test)
encode_test.shape #TensorShape([10000, 32])
de_test = decode.predict(encode_test)
de_test.shape #(10000, 784)

打印原图片与预测图片

设置打印图片张数

1
n = 10

转换数据

1
x_test = x_test.numpy()

打印

1
2
3
4
5
6
plt.figure(figsize=(20,4))
for i in range(1,n):
ax = plt.subplot(2,n,i)
plt.imshow(x_test[i].reshape(28,28))
ax = plt.subplot(2,n,i+n)
plt.imshow(de_test[i].reshape(28,28))