import tensorflow as tf import matplotlib.pyplot as plt import numpy as np
查看tensorflow版本
导入mnist数据集
1
| (x_train,_),(x_test,_) = tf.keras.datasets.mnist.load_data()
|
查看数据维度
1
| x_train.shape,x_test.shape
|
对数据进行reshape 28*28->784
1 2
| x_train = x_train.reshape(x_train.shape[0], -1) x_test = x_test.reshape(x_test.shape[0], -1)
|
数据归一化
1 2
| x_train = tf.cast(x_train,tf.float32)/255 x_test = tf.cast(x_test,tf.float32)/255
|
噪声的添加
1 2 3
| factor = 0.5 #增加噪声多少 x_train_noise = x_train + factor*np.random.normal(loc=0.0,scale=1.0,size=x_train.shape) x_test_noise = x_test + factor*np.random.normal(loc=0.0,scale=1.0,size=x_test.shape)
|
数据范围规定
1 2
| x_train_noise = np.clip(x_train_noise,0.,1.)#加噪后数值可能会不在0~1之间将范围规定到之中,大于1变成1小于0变成00 x_test_noise = np.clip(x_test_noise,0.,1.)
|
查看加噪后的图片
1 2 3 4 5
| n=10 plt.figure(figsize=(10,2)) for i in range(1,n): ax = plt.subplot(1,n,i) plt.imshow(x_train_noise[i].reshape(28,28))
|

构建模型
1 2 3 4 5 6 7 8 9 10 11 12 13
| input_size = 784 hidden_size = 32 output_size = 784
input = tf.keras.layers.Input(shape=(input_size,))
# Encoder en = tf.keras.layers.Dense(hidden_size, activation='relu')(input)
# Decoder de = tf.keras.layers.Dense(output_size, activation='sigmoid')(en)
model = tf.keras.Model(inputs=input, outputs=de)
|
查看模型数据流动
1
| tf.keras.utils.plot_model(model,show_shapes=True)#可视化
|

模型配置
1 2 3
| model.compile(optimizer=tf.keras.optimizers.Adam(0.001), loss='mse' )
|
模型训练
1 2 3 4 5 6
| model.fit(x_train_noise, x_train, epochs=50, batch_size=256, shuffle=True, validation_data=(x_test_noise,x_test) )
|
模型测试
编码
1
| encode = tf.keras.Model(inputs=input,outputs=en)
|
model.layers[-1].name
解码
1 2 3
| input_de = tf.keras.layers.Input(shape=(hidden_size,)) output = model.layers[-1](input_de) decode = tf.keras.Model(inputs=input_de, outputs=output)
|
输出
1 2 3 4 5 6 7 8 9 10
| encode_test = encode(x_test_noise)#TensorShape([10000, 32]) de_test = decode.predict(encode_test)#(10000, 784) n = 10 x_test = x_test.numpy() plt.figure(figsize=(20,4)) for i in range(1,n): ax = plt.subplot(2,n,i) plt.imshow(x_test_noise[i].reshape(28,28)) ax = plt.subplot(2,n,i+n) plt.imshow(de_test[i].reshape(28,28))
|
