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
|
对数据最后一个维度进行扩展
1 2
| x_train = np.expand_dims(x_train, -1) x_test = np.expand_dims(x_test, -1)
|
x_train.shape,x_test.shape
1
| ((60000, 28, 28, 1), (10000, 28, 28, 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 14 15 16 17
| input = tf.keras.layers.Input(shape=(28, 28, 1))
# Encoder x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input) x = tf.keras.layers.MaxPool2D((2, 2), padding='same')(x) # 14*14*16
x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x) x = tf.keras.layers.MaxPool2D((2, 2), padding='same')(x) # 7*7*32
# Decoder x = tf.keras.layers.Conv2DTranspose(16, (3, 3), strides=2, activation='relu', padding='same')(x) # 14*14*16 output = tf.keras.layers.Conv2DTranspose(1, (3, 3), strides=2, activation='sigmoid', padding='same')(x) # 28*28*1
model = tf.keras.Model(inputs=input, outputs=output)
|
查看模型数据流动
1
| tf.keras.utils.plot_model(model,show_shapes=True)#可视化
|

模型配置
1
| model.compile(optimizer='adam', loss='mse')
|
模型训练
1 2 3 4
| model.fit(x_train_noisy, x_train, epochs=50, batch_size=256, validation_data=(x_test_noisy, x_test))
|
模型测试
1 2 3 4 5 6 7 8 9 10
| pre_test = model.predict(x_test_noisy) plt.figure(figsize=(20, 4)) for i in range(1, n): # 展示原始图像 ax = plt.subplot(2, n, i) plt.imshow(x_test_noisy[i].reshape(28, 28)) # 展示自编码器重构后的图像 ax = plt.subplot(2, n, i + n) plt.imshow(pre_test[i].reshape(28, 28)) plt.show()
|
