autoencoder自编码器原理以及在mnist数据集上的实现

在这里插入图片描述
Autoencoder是常见的一种非监督学习的神经网络。它实际由一组相对应的神经网络组成(可以是普通的全连接层,或者是卷积层,亦或者是LSTMRNN等等,取决于项目目的),其目的是将输入数据降维成一个低维度的潜在编码,再通过解码器将数据还原出来。因此autoencoder总是包含了两个部分,编码部分以及解码部分。编码部分负责将输入降维编码,解码部分负责让输出层通过潜在编码还原出输入层。我们的训练目标就是使得输出层与输入层之间的差距最小化。

我们会发现,有一定的风险使得训练出的AE模型是一个恒等函数,这是一个需要尽量避免的问题。

Autoencoder CNN 卷积自编码器

下面我们就用一个简单的基于mnist数据集的实现,来更好地理解autoencoder的原理。
首先是import相关的模块,定义一个用于对比显示输入图像与输出图像的可视化函数。

# Le dataset MNIST
from tensorflow.keras.datasets import mnist
import tensorflow as tf
from tensorflow.keras.layers import Input,Dense, Conv2D, Conv2DTranspose, MaxPooling2D, Flatten, UpSampling2D, Reshape
from tensorflow.keras.models import Model,Sequential
import numpy as np
import matplotlib.pyplot as plt

def MNIST_AE_disp(img_in, img_out, img_idx):

    num_img = len(img_idx)
    plt.figure(figsize=(18, 4))

    for i, image_idx in enumerate(img_idx):
        # 显示输入图像
        ax = plt.subplot(2, num_img, i + 1)
        plt.imshow(img_in[image_idx].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        # 显示输出图像
        ax = plt.subplot(2, num_img, num_img + i + 1)
        plt.imshow(img_out[image_idx].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    plt.show()

加载数据并对mnist图像数据进行预处理,包括正则化以及将图片扩充成28,28,1的三维。

(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 正则化 [0, 255] à [0, 1]
x_train=x_train.astype('float32')/float(x_train.
  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,稀疏编码器是一种无监督学习算法,它可以通过学习特征的稀疏表示来压缩数据,并且在去噪任务中也有很好的应用。以下是一个简单的Python代码实现: 首先,我们需要导入必要的库,包括NumPy、Matplotlib、TensorFlow和Keras。 ```python import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.datasets import mnist from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model from tensorflow.keras import regularizers ``` 然后,我们加载MNIST数据集,并将其标准化到0到1之间的范围内。 ```python (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), np.prod(x_train.shape[1:]))) x_test = np.reshape(x_test, (len(x_test), np.prod(x_test.shape[1:]))) ``` 接下来,我们定义稀疏编码器的架构。这里我们使用一个具有两个隐藏层的全连接神经网络,其中第一个隐藏层的大小为500,第二个隐藏层的大小为250。我们还将使用L1正则化来促进稀疏表示。 ```python input_img = Input(shape=(784,)) encoded = Dense(500, activation='relu', activity_regularizer=regularizers.l1(10e-5))(input_img) encoded = Dense(250, activation='relu', activity_regularizer=regularizers.l1(10e-5))(encoded) decoded = Dense(500, activation='relu')(encoded) decoded = Dense(784, activation='sigmoid')(decoded) ``` 然后,我们定义模型并编译它。我们使用Adam优化器和均方误差损失函数。我们还定义训练模型时使用的批量大小和训练轮数。 ```python autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adam', loss='mse') batch_size = 128 epochs = 50 ``` 接下来,我们训练模型并使用测试数据集进行评估。 ```python history = autoencoder.fit(x_train, x_train, epochs=epochs, batch_size=batch_size, shuffle=True, validation_data=(x_test, x_test)) encoded_imgs = autoencoder.predict(x_test) ``` 最后,我们将原始图像和重建图像可视化,以便比较它们之间的差异。 ```python n = 10 plt.figure(figsize=(20, 4)) for i in range(n): # original image 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) # reconstructed image ax = plt.subplot(2, n, i + 1 + n) plt.imshow(encoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() ``` 这个模型的训练结果取决于许多因素,例如批量大小、训练轮数和网络架构。您可以尝试不同的参数组合以获得更好的结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值