【科学计算与数学建模】自编码器

一、自编码器


任务描述

本关任务:搭建一个简单的自编码器模型。

相关知识

为了完成本关任务,你需要掌握:1.基本的自编码概念,2.搭建简单的自编码器模型。

自编码器

自编码器简介

自编码器是一类尝试使用反向传播算法重新创建输入数据作为输出的神经网络。自编码器包含两部分:编码器和解码器。编码器读取输入并把它压缩成紧凑表示,解码器则读取紧凑表示并用其重建输入。如下图所示:

,

搭建简单的自编码器模型

可以通过keras很快的创建如下的编码器和解码器并编译,代码如下:

 
  1. from keras.layers import Input, Dense
  2. from keras.models import Model
  3. # 编码器维度
  4. encoding_dim = 32
  5. input_img = Input(shape=(784,))
  6. # "encoded" 是把输入编码表示
  7. encoded = Dense(encoding_dim, activation='relu')(input_img)
  8. # "decoded" 是输入的有损重构
  9. decoded = Dense(784, activation='sigmoid')(encoded)
  10. # 搭建自编码模型
  11. autoencoder = Model(input_img, decoded)
  12. autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
  13. # 打印模型结构
  14. autoencoder.summary()

运行结果:

 
  1. _________________________________________________________________
  2. Layer (type) Output Shape Param #
  3. =================================================================
  4. input_1 (InputLayer) (None, 784) 0
  5. _________________________________________________________________
  6. dense_1 (Dense) (None, 32) 25120
  7. _________________________________________________________________
  8. dense_2 (Dense) (None, 784) 25872
  9. =================================================================
  10. Total params: 50,992
  11. Trainable params: 50,992
  12. Non-trainable params: 0
  13. _________________________________________________________________
导入数据集

可通过以下代码导入mnist数据集,代码如下:

 
  1. from keras.datasets import mnist
  2. import numpy as np
  3. # 加载数据集
  4. (x_train, _), (x_test, _) = mnist.load_data()
  5. # 对图片数据进行归一化
  6. x_train = x_train.astype('float32') / 255.
  7. x_test = x_test.astype('float32') / 255.
  8. # 转换数据形状
  9. x_train=x_train.reshape((len(x_train),np.prod(x_train.shape[1:]))
  10. x_test =x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
  11. print(x_train.shape)
  12. print(x_test.shape)

运行结果:

 
  1. (60000,784)
  2. (10000,784)
拟合模型

通过以上数据拟合模型autoencoder,提示:epochs =50,batch_size=256,shuffle=True 。 代码如下:

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

代码执行结果:

 
  1. Train on 60000 samples, validate on 10000 samples
  2. Epoch 1/50
  3. 60000/60000 [==============================] - 5s 83us/step - loss: 0.3567 - val_loss: 0.2714
  4. Epoch 2/50
  5. 60000/60000 [==============================] - 4s 61us/step - loss: 0.2645 - val_loss: 0.2545
  6. Epoch 3/50
  7. 60000/60000 [==============================] - 4s 61us/step - loss: 0.2450 - val_loss: 0.2333
  8. Epoch 4/50
  9. 60000/60000 [==============================] - 4s 62us/step - loss: 0.2248 - val_loss: 0.2139
  10. Epoch 5/50
  11. 60000/60000 [==============================] - 4s 61us/step - loss: 0.2078 - val_loss: 0.1997
  12. 60000/60000 [==============================] - 4s 73us/step - loss: 0.1055 - val_loss: 0.1037
  13. Epoch 50/50
  14. 60000/60000 [==============================] - 4s 75us/step - loss: 0.1052 - val_loss: 0.1033
查看重构的输出与原来的输出对比

我们可以通过以下方式来查看,代码如下:

 
  1. # 从测试集选取一些数据来编码和解码
  2. encoded_imgs = encoder.predict(x_test)
  3. decoded_imgs = decoder.predict(encoded_imgs)
  4. import matplotlib.pyplot as plt
  5. n = 10 # 打印的图片数量
  6. plt.figure(figsize=(20, 4))
  7. for i in range(n):
  8. # 显示原来图像
  9. ax = plt.subplot(2, n, i + 1)
  10. plt.imshow(x_test[i].reshape(28, 28))
  11. plt.gray()
  12. ax.get_xaxis().set_visible(False)
  13. ax.get_yaxis().set_visible(False)
  14. # 显示重构后的图像
  15. ax = plt.subplot(2, n, i + 1 + n)
  16. plt.imshow(decoded_imgs[i].reshape(28, 28))
  17. plt.gray()
  18. ax.get_xaxis().set_visible(False)
  19. ax.get_yaxis().set_visible(False)
  20. plt.show()

代码执行结果:

,

编程要求

根据左侧内容提示,补充右侧代码部分内容。

  • 补充训练自编码器模型代码。
  • 补充编码器模型参数。

因评测时间限时,实战代码只训练五轮的结果进行评测对比。

测试说明

平台会对你编写的代码进行测试:

测试输入:略; 预期输出: 通关成功!


开始你的任务吧,祝你成功!

代码部分

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from Keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

# 设置随机种子
np.random.seed(1447)


def draw(X_test, decoded_imgs):
    # 打印图片的数量
    n = 10
    # 画布大小
    plt.figure(figsize=(20, 4))
    for i in range(n):
        ax = plt.subplot(2, n, i+1)
        plt.imshow(X_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        # 显示重构之后的图像
        ax = plt.subplot(2, n, i+1+n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    
    # 保存图片文件
    plt.savefig("src/step1/stu_img/result.png")
    plt.show()


def autoencoder1():
    # 编码器维度
    encoding_dim = 32
    input_img = Input(shape=(784,))
    # "encoded" 是把输入编码表示
    encoded = Dense(encoding_dim, activation='relu')(input_img)
    # "decoded" 是输入的有损重构
    decoded = Dense(784, activation='sigmoid')(encoded)

    # 自编码模型
    autoencoder = Model(input_img, decoded)
    autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

    # 加载数据
    (X_train, _), (X_test, _) = mnist.load_data()
    # 数据归一化
    X_train = X_train.astype('float32') / 255
    X_test = X_test.astype('float32') / 255
    # 形状转换
    X_train = X_train.reshape((len(X_train), np.prod(X_train.shape[1:])))
    X_test = X_test.reshape((len(X_test), np.prod(X_test.shape[1:])))
    print(X_train.shape)
    print(X_test.shape)

    # 训练模型参数,补充下面代码
    # 训练5轮,batch_size设置为5,shuffle为True。
    # validation_data放入测试集数据,verbose设置为2则不输出进度条。
    # ********** Begin *********#


    # autoencoder.fit( )

    autoencoder.fit(X_train, X_train,
                epochs=5,
                batch_size=256,
                shuffle=True,
                validation_data=(X_test, X_test),
                verbose=2
                )
    # ********** End **********#

    # 获取编码器和解码器

    # ********** Begin *********#
    # "encoded" 是把输入编码表示,补充下面代码
    # encoder = Model(inputs=, outputs=)
    # encoded_input = Input(shape=(encoding_dim,))
    encoder = Model(inputs=input_img, outputs=encoded)
    encoded_input = Input(shape=(encoding_dim,))
    # ********** End **********#
    # "decoded" 是输入的有损重构
    decoder_layer = autoencoder.layers[-1]
    decoder = Model(inputs=encoded_input, outputs=decoder_layer(encoded_input))

    # 预测
    encoded_imgs = encoder.predict(X_test)
    decoded_imgs = decoder.predict(encoded_imgs)
    # 显示
    draw(X_test, decoded_imgs)

二、卷积自编码器


任务描述

本关任务:编写一个卷积自编码器。

相关知识

为了完成本关任务,你需要掌握:1.卷积自编码器的基础知识,2.使用keras实现卷积自编码器。

卷积自编码器
搭建卷积自编码器

当输入是图像时,使用卷积神经网络基本上总是有意义的。在现实中,用于处理图像的自动编码器几乎都是卷积自动编码器——又简单又快。 卷积自编码器的编码器部分由卷积层和MaxPooling层构成,MaxPooling负责空域下采样。而解码器由卷积层和上采样层构成。

我们可以通过以下方式来创建如下的卷积编码器和解码器并编译,代码如下:

 
  1. from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
  2. from keras.models import Model
  3. from keras import backend as K
  4. input_img = Input(shape=(28, 28, 1)) #输入图像形状
  5. #编码器
  6. x=Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
  7. #卷积层
  8. x = MaxPooling2D((2, 2), padding='same')(x)#空域下采样
  9. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  10. x = MaxPooling2D((2, 2), padding='same')(x)
  11. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  12. encoded = MaxPooling2D((2, 2), padding='same')(x)
  13. #解码
  14. x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
  15. x = UpSampling2D((2, 2))(x)#上采样层
  16. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  17. x = UpSampling2D((2, 2))(x)
  18. x = Conv2D(16, (3, 3), activation='relu')(x)
  19. x = UpSampling2D((2, 2))(x)
  20. decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
  21. # 定义模型
  22. autoencoder = Model(input_img, decoded)
  23. # 编译模型
  24. autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')#编译
  25. # 打印模型结构
  26. autoencoder.summary()

运行结果:

 
  1. _________________________________________________________________
  2. Layer (type) Output Shape Param #
  3. =================================================================
  4. input_1 (InputLayer) (None, 28, 28, 1) 0
  5. _________________________________________________________________
  6. conv2d_1 (Conv2D) (None, 28, 28, 16) 160
  7. _________________________________________________________________
  8. max_pooling2d_1 (MaxPooling2 (None, 14, 14, 16) 0
  9. _________________________________________________________________
  10. conv2d_2 (Conv2D) (None, 14, 14, 8) 1160
  11. _________________________________________________________________
  12. max_pooling2d_2 (MaxPooling2 (None, 7, 7, 8) 0
  13. _________________________________________________________________
  14. conv2d_3 (Conv2D) (None, 7, 7, 8) 584
  15. _________________________________________________________________
  16. max_pooling2d_3 (MaxPooling2 (None, 4, 4, 8) 0
  17. _________________________________________________________________
  18. conv2d_4 (Conv2D) (None, 4, 4, 8) 584
  19. _________________________________________________________________
  20. up_sampling2d_1 (UpSampling2 (None, 8, 8, 8) 0
  21. _________________________________________________________________
  22. conv2d_5 (Conv2D) (None, 8, 8, 8) 584
  23. _________________________________________________________________
  24. up_sampling2d_2 (UpSampling2 (None, 16, 16, 8) 0
  25. _________________________________________________________________
  26. conv2d_6 (Conv2D) (None, 14, 14, 16) 1168
  27. _________________________________________________________________
  28. up_sampling2d_3 (UpSampling2 (None, 28, 28, 16) 0
  29. _________________________________________________________________
  30. conv2d_7 (Conv2D) (None, 28, 28, 1) 145
  31. =================================================================
  32. Total params: 4,385
  33. Trainable params: 4,385
  34. Non-trainable params: 0
  35. _________________________________________________________________
  36. Process finished with exit code 0
加载数据并拟合模型

请参考上个关卡加载数据并完成模型拟合。 提示1:

x_train 用 reshape重构时参数设置为 x_train = np.reshape(x_train, (len(x_train), 28, 28, 1)) ,x_test 同上类似。

提示2:

autoencoder 中的 batch_size 设置为 128,其他不变。

代码如下:

 
  1. from keras.datasets import mnist
  2. import numpy as np
  3. # 加载数据
  4. (x_train, _), (x_test, _) = mnist.load_data()
  5. # 归一化
  6. x_train = x_train.astype('float32') / 255.
  7. x_test = x_test.astype('float32') / 255.
  8. # 转换形状
  9. x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
  10. x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
  11. # 训练模型
  12. autoencoder.fit(x_train, x_train,
  13. epochs=50,
  14. batch_size=128,
  15. shuffle=True,
  16. validation_data=(x_test, x_test),)

运行结果:

 
  1. Train on 60000 samples, validate on 10000 samples
  2. Epoch 1/50
  3. 60000/60000 [==============================] - 42s 699us/step - loss: 0.2094 - val_loss: 0.1738
  4. Epoch 2/50
  5. 60000/60000 [==============================] - 35s 586us/step - loss: 0.1511 - val_loss: 0.1389
  6. Epoch 3/50
  7. 60000/60000 [==============================] - 36s 603us/step - loss: 0.1371 - val_loss: 0.1302
  8. Epoch 4/50
  9. 60000/60000 [==============================] - 36s 604us/step - loss: 0.1301 - val_loss: 0.1256
  10. Epoch 5/50
  11. 60000/60000 [==============================] - 37s 609us/step - loss: 0.1256 - val_loss: 0.1236
  12. Epoch 49/50
  13. 60000/60000 [==============================] - 38s 633us/step - loss: 0.0981 - val_loss: 0.0951
  14. Epoch 50/50
  15. 60000/60000 [==============================] - 39s 644us/step - loss: 0.0979 - val_loss: 0.0953
  16. <keras.callbacks.History at 0x7fbec2d90128>
查看重构的输出与原来的输出对比

查看 10 张重构后的图像与原图像的对比。 代码如下:

 
  1. # 预测
  2. decoded_imgs = autoencoder.predict(x_test)
  3. n = 10
  4. plt.figure(figsize=(20, 4))
  5. for i in range(n):
  6. # 显示原图像
  7. ax = plt.subplot(2, n, i+1)
  8. plt.imshow(x_test[i].reshape(28, 28))
  9. plt.gray()
  10. ax.get_xaxis().set_visible(False)
  11. ax.get_yaxis().set_visible(False)
  12. # 显示重构后的图像
  13. ax = plt.subplot(2, n, i + n+1)
  14. plt.imshow(decoded_imgs[i].reshape(28, 28))
  15. plt.gray()
  16. ax.get_xaxis().set_visible(False)
  17. ax.get_yaxis().set_visible(False)
  18. plt.show()

运行结果:

,

编程要求

根据左侧内容提示,补充右侧代码部分内容。

  • 补充编码器模型的卷积层和最大池化层参数。
  • 补充解码器模型的上采样层和卷积层参数。

因评测时间限时,实战代码只训练五轮的结果进行评测对比。

测试说明

平台会对你编写的代码进行测试:

测试输入:略; 预期输出: 通关成功!


开始你的任务吧,祝你成功!

代码部分

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from Keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

# 设置随机种子
np.random.seed(1447)


def draw(X_test, decoded_imgs):
    
    n = 10
    plt.figure(figsize=(20, 4))
    for i in range(n):
        ax = plt.subplot(2, n, i+1)
        plt.imshow(X_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        # 显示重构之后的图像
        ax = plt.subplot(2, n, i+1+n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    plt.savefig("src/step2/stu_img/result.png")
    plt.show()


def autoencoder2():
    # 卷积编码器
    input_img = Input(shape=(28, 28, 1))  # 输入图像形状
    ###编码器
    # 卷积层
    x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
    # 最大池化
    x = MaxPooling2D((2, 2), padding='same')(x)

    x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
    x = MaxPooling2D((2, 2), padding='same')(x)

    # 定义一个卷积,卷积核大小为8,形状为(3,3),激活函数为relu,padding为same
    # encoded是最大池化,池化形状为(2,2),padding为same
    # ********** Begin *********#
    # x = 
    # encoded = 
    x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
    encoded = MaxPooling2D((2, 2), padding='same')(x)
    # ********** End *********#

    ###解码器
    x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
    # 上采样层
    x = UpSampling2D((2, 2))(x)
    x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
    x = UpSampling2D((2, 2))(x)
    x = Conv2D(16, (3, 3), activation='relu')(x)

    # 定义一个上采样层,形状为(2,2)
    # decoded是卷积层,卷积核大小为1,形状为(3,3),激活函数为sigmoid,padding为same
    # ********** Begin *********#
    # x = 
    # decoded = 
    x = UpSampling2D((2, 2))(x)
    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

    # ********** Begin *********#


    autoencoder = Model(input_img, decoded)
    autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

    # 数据处理
    (X_train, _), (X_test, _) = mnist.load_data()
    # 数据归一化
    X_train = X_train.astype('float32') / 255
    X_test = X_test.astype('float32') / 255
    # 数据形状转换
    X_train = np.reshape(X_train, (len(X_train), 28, 28, 1))
    X_test = np.reshape(X_test, (len(X_test), 28, 28, 1))
    print(X_train.shape)
    print(X_test.shape)

    # 训练模型
    autoencoder.fit(X_train, X_train, epochs=5, batch_size=128,
                    shuffle=True, validation_data=(X_test, X_test))
    # 预测
    decoded_imgs = autoencoder.predict(X_test)
    # 显示
    draw(X_test, decoded_imgs)

三、自编码器的应用


任务描述

本关任务:对数据集加入噪点,构建自编码器。

相关知识

为了完成本关任务,你需要掌握:1.自编码器在数据加入噪点后进行还原,2.编写代码进行实现。

自编码器的应用
介绍

我们把训练样本用噪声污染,然后使用解码器解码出干净的照片,以获得去噪自动编码器。

把原图片加入高斯噪声

我们可以通过以下方式来加入噪声并查看加噪后的图片,代码如下:

 
  1. from keras.datasets import mnist
  2. import numpy as np
  3. # 加载数据
  4. (x_train, _), (x_test, _) = mnist.load_data()
  5. # 归一化
  6. x_train = x_train.astype('float32') / 255.
  7. x_test = x_test.astype('float32') / 255.
  8. # 形状转换
  9. x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
  10. x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
  11. noise_factor = 0.5
  12. # 噪点
  13. x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
  14. x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
  15. x_train_noisy = np.clip(x_train_noisy, 0., 1.)
  16. x_test_noisy = np.clip(x_test_noisy, 0., 1.)
  17. n = 10
  18. plt.figure(figsize=(20, 2))
  19. # 显示
  20. for i in range(n):
  21. ax = plt.subplot(1, n, i+1)
  22. plt.imshow(x_test_noisy[i].reshape(28, 28))
  23. plt.gray()
  24. ax.get_xaxis().set_visible(False)
  25. ax.get_yaxis().set_visible(False)
  26. plt.show()

代码执行结果:

,

构建自编码器

参考上一关卡按如下步骤使用Keras函数模型搭建自编码器并拟合。

1)设置input_img参数。 2)搭建编码器,添加Conv2D层,输入是input_img,输出维度 32,卷积核大小3×3,激活函数’‘relu’padding设置为‘same’,返回给x。 3)添加Maxpooling2D层,大小是(2,2)padding设置为‘same’。 4)添加Conv2D层,输出维度 32,卷积核大小3×3,激活函数’‘relu’padding设置为‘same’。 5)添加Maxpooling2D层,大小是(2,2)padding设置为‘same’,返回给encoded。 6)设置解码器,添加Conv2D层,输入是encoded,输出维度 32,卷积核大小3×3,激活函数’‘relu’padding设置为‘same’,返回给x。 7)添加上采样层,大小是(2,2)。 8)添加Conv2D层,输出维度 32,卷积核大小3×3,激活函数’‘relu’padding设置为‘same’。 9)添加上采样层,大小是(2,2)。 10)添加Conv2D层,输入是encoded,输出维度 1,卷积核大小3×3,激活函数’‘sigmoid’padding设置为‘same’,返回给decoded。 11)设置自编码器,输入是input_img,decoded。 12)编译自编码器,参数不变。 13)拟合数据,参数与上个关卡一样。

 
  1. # 输入尺寸
  2. input_img = Input(shape=(28, 28, 1))
  3. # 卷积层
  4. x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
  5. # 池化层
  6. x = MaxPooling2D((2, 2), padding='same')(x)
  7. x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
  8. encoded = MaxPooling2D((2, 2), padding='same')(x)
  9. # 卷积层
  10. x = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
  11. # 上采样层
  12. x = UpSampling2D((2, 2))(x)
  13. x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
  14. x = UpSampling2D((2, 2))(x)
  15. decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
  16. # 定义模型
  17. autoencoder = Model(input_img, decoded)
  18. # 模型编译
  19. autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
  20. # 训练模型
  21. autoencoder.fit(x_train_noisy, x_train,
  22. epochs=100,
  23. batch_size=128,
  24. shuffle=True,
  25. validation_data=(x_test_noisy, x_test),)

代码执行结果:

 
  1. Train on 60000 samples, validate on 10000 samples
  2. Epoch 1/50
  3. 60000/60000 [==============================] - 66s 1ms/step - loss: 0.1182 - val_loss: 0.1111
  4. Epoch 2/50
  5. 60000/60000 [==============================] - 63s 1ms/step - loss: 0.1114 - val_loss: 0.1081
  6. Epoch 3/50
  7. 60000/60000 [==============================] - 71s 1ms/step - loss: 0.1077 - val_loss: 0.1035
  8. Epoch 4/50
  9. 60000/60000 [==============================] - 71s 1ms/step - loss: 0.1055 - val_loss: 0.1034
  10. Epoch 5/50
  11. 60000/60000 [==============================] - 60s 1ms/step - loss: 0.1040 - val_loss: 0.1036
  12. Epoch 49/50
  13. 60000/60000 [==============================] - 68s 1ms/step - loss: 0.0954 - val_loss: 0.0950
  14. Epoch 50/50
  15. 60000/60000 [==============================] - 67s 1ms/step - loss: 0.0953 - val_loss: 0.0946
  16. <keras.callbacks.History at 0x7f685ce82390>
查看重构的输出与原来的输出对比

查看10张重构后的图像与原图像的对比。

代码如下:

 
  1. # 预测
  2. decoded_imgs = autoencoder.predict(x_test)
  3. n = 10
  4. plt.figure(figsize=(20, 4))
  5. # 显示10张重构后的图像与原图像的对比
  6. for i in range(n):
  7. ax = plt.subplot(2, n, i + 1)
  8. plt.imshow(x_test_noisy[i].reshape(28, 28))
  9. plt.gray()
  10. ax.get_xaxis().set_visible(False)
  11. ax.get_yaxis().set_visible(False)
  12. ax = plt.subplot(2, n, i + n + 1)
  13. plt.imshow(decoded_imgs[i].reshape(28, 28))
  14. plt.gray()
  15. ax.get_xaxis().set_visible(False)
  16. ax.get_yaxis().set_visible(False)
  17. plt.show()

执行代码结果:

,

编程要求

根据左侧内容提示,补充右侧代码部分内容。

  • 补充对测试集数据的噪点和截取操作。
  • 补充自编码器模型的编译参数。

因评测时间限时,实战代码只训练十轮的结果进行评测对比。

测试说明

平台会对你编写的代码进行测试:

测试输入:略; 预期输出: 通关成功!


开始你的任务吧,祝你成功!

代码部分

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from Keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

# 设置随机种子
np.random.seed(1447)


def draw(X_test, decoded_imgs):
    n = 10
    plt.figure(figsize=(20, 4))
    for i in range(n):
        ax = plt.subplot(2, n, i+1)
        plt.imshow(X_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        # 显示重构之后的图像
        ax = plt.subplot(2, n, i+1+n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    # 保存图片文件
    plt.savefig("src/step3/stu_img/result.png")
    plt.show()


def autoencoder3():
    # 数据处理
    (X_train, _), (X_test, _) = mnist.load_data()
    # 数据归一化
    X_train = X_train.astype('float32') / 255
    X_test = X_test.astype('float32') / 255
    # 数据形状转换
    X_train = np.reshape(X_train, (len(X_train), 28, 28, 1))
    X_test = np.reshape(X_test, (len(X_test), 28, 28, 1))

    # 加入数据噪点
    # ********** Begin *********#

    noise_factor = 0.5  # 噪点因子
    X_train_noisy = X_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=X_train.shape)
    
    # 给测试集加入噪点
    #X_test_noisy = 
    X_test_noisy = X_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=X_test.shape) 
    X_train_noisy = np.clip(X_train_noisy, 0., 1.)

    # 对测试集进行截取
    # X_test_noisy = 
    X_test_noisy = np.clip(X_test_noisy, 0., 1.)
    # ********** End *********#


    # 输入图片形状
    input_img = Input(shape=(28, 28, 1))
    ### 编码器
    x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
    x = MaxPooling2D((2, 2), padding='same')(x)
    x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
    encoded = MaxPooling2D((2, 2), padding='same')(x)

    ### 解码器
    x = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
    x = UpSampling2D((2, 2))(x)
    x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
    x = UpSampling2D((2, 2))(x)
    decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

    # 定义模型
    autoencoder = Model(input_img, decoded)

    # 编译模型,优化器为adadelta,损失函数为binary_crossentropy
    # ********** Begin *********#
    # autoencoder.compile()
    autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
    
    # ********** End *********#

    # 训练模型
    autoencoder.fit(X_train_noisy, X_train, epochs=10, batch_size=128,
                    shuffle=True, validation_data=(X_test_noisy, X_test))

    # 预测
    decoded_imgs = autoencoder.predict(X_test)
    # 显示
    draw(X_test_noisy, decoded_imgs)

  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值