### 下载Fashion MNIST数据集

Fashion MNIST由德国柏林的欧洲电子商务公司Zalando设计和维护。Fashion MNIST由60000个图像的训练集和10000个图像的测试集组成。每个例子是一个28×28的灰度图像，与来自10个类的标签相关联。

Fashion MNIST包含服装的图像（如图所示），被设计为MNIST数据集的替代数据集，MNIST数据集包含手写数字。我们选择Fashion MNIST仅仅是因为MNIST在许多教程中已经被过度使用。

```import tensorflow as tf
from tensorflow.keras.datasets import fashion_mnist
# 我们不需要y_train和y_test
(x_train, _), (x_test, _) = fashion_mnist.load_data()
print('Max value in the x_train is', x_train[0].max())
print('Min value in the x_train is', x_train[0].min())```

```import matplotlib.pyplot as plt
fig, axs = plt.subplots(5, 10)
plt.gray()
a = 0
for i in range(5):
for j in range(10):
axs[i, j].imshow(tf.squeeze(x_test[a]))
axs[i, j].xaxis.set_visible(False)
axs[i, j].yaxis.set_visible(False)
a = a + 1```

### 处理Fashion MNIST数据

```x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.```

```x_train = x_train[…, tf.newaxis]
x_test = x_test[…, tf.newaxis]```

```print(x_train.shape)
print(x_test.shape)```

### 给图像添加噪声

```noise_factor = 0.4
x_train_noisy = x_train + noise_factor * tf.random.normal(shape=x_train.shape)
x_test_noisy = x_test + noise_factor * tf.random.normal(shape=x_test.shape)```

```x_train_noisy = tf.clip_by_value(x_train_noisy, clip_value_min=0., clip_value_max=1.)
x_test_noisy = tf.clip_by_value(x_test_noisy, clip_value_min=0., clip_value_max=1.)```

```n = 5
plt.figure(figsize=(20, 8))
plt.gray()
for i in range(n):
ax = plt.subplot(2, n, i + 1)
plt.title("original", size=20)
plt.imshow(tf.squeeze(x_test[i]))
plt.gray()
bx = plt.subplot(2, n, n+ i + 1)
plt.title("original + noise", size=20)
plt.imshow(tf.squeeze(x_test_noisy[i]))
plt.show()```

### 建立我们的模型

```from tensorflow.keras.layers import Conv2DTranspose, Conv2D, Input
class NoiseReducer(tf.keras.Model):
def __init__(self):
super(NoiseReducer, self).__init__()
self.encoder = tf.keras.Sequential([
Input(shape=(28, 28, 1)),

self.decoder = tf.keras.Sequential([
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded```

`autoencoder = NoiseReducer()`

### 配置我们的模型

`autoencoder.compile(optimizer='adam', loss='mse')`

```autoencoder.fit(x_train_noisy,
x_train,
epochs=10,
shuffle=True,
validation_data=(x_test_noisy, x_test))```

### 用我们训练过的自编码器降低图像噪声

```encoded_imgs=autoencoder.encoder(x_test_noisy).numpy()
decoded_imgs=autoencoder.decoder(encoded_imgs)```

```n = 10
plt.figure(figsize=(20, 7))
plt.gray()
for i in range(n):
# 显示原始+噪声
bx = plt.subplot(3, n, i + 1)
plt.title("original + noise")
plt.imshow(tf.squeeze(x_test_noisy[i]))
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# 显示重建
cx = plt.subplot(3, n, i + n + 1)
plt.title("reconstructed")
plt.imshow(tf.squeeze(decoded_imgs[i]))
bx.get_xaxis().set_visible(False)
bx.get_yaxis().set_visible(False)
# 显示原始
ax = plt.subplot(3, n, i + 2*n + 1)
plt.title("original")
plt.imshow(tf.squeeze(x_test[i]))
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()```

### 结尾

#### 参考

[1] Intro to Autoencoders, TensorFlow, available on https://www.tensorflow.org/tu…