【tensorflow2.x】自编码器mnist

本文介绍了使用TensorFlow构建的自动编码器模型,包括编码器和解码器的设计,以及如何对MNIST数据集进行预处理和训练。通过编码前后的特征可视化,展示了模型在数据压缩和重构上的效果。
部署运行你感兴趣的模型镜像
import tensorflow as tf
import matplotlib.pyplot as plt

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.expand_dims(x_train / 255.0, -1)

class Encoder(tf.keras.Model):
    def __init__(self):
        super(Encoder, self).__init__()
        self.conv = tf.keras.Sequential([
            tf.keras.layers.Conv2D(filters=32, kernel_size=(7, 7), activation='relu', strides=2),
            tf.keras.layers.BatchNormalization(),
            tf.keras.layers.Conv2D(filters=64, kernel_size=(5, 5), activation='relu', strides=1),
            tf.keras.layers.BatchNormalization(),
            tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation='relu', strides=1),
            tf.keras.layers.BatchNormalization(),
        ])
        self.fc = tf.keras.Sequential([
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(128, activation='relu'),
            tf.keras.layers.Dense(128, activation='relu'),
            tf.keras.layers.Dense(2, activation='tanh')
        ])

    def call(self, inputs):
        x = self.conv(inputs)
        y = self.fc(x)
        return y

class Decoder(tf.keras.Model):
    def __init__(self):
        super(Decoder, self).__init__()
        self.fc = tf.keras.Sequential([
            tf.keras.layers.Dense(128, activation='relu'),
            tf.keras.layers.Dense(128, activation='relu'),
            tf.keras.layers.Dense(5 * 5 * 128, activation='relu'),
        ])
        self.d_conv = tf.keras.Sequential([
            tf.keras.layers.Conv2DTranspose(filters=64, kernel_size=(3, 3), activation='relu', strides=1),
            tf.keras.layers.BatchNormalization(),
            tf.keras.layers.Conv2DTranspose(filters=32, kernel_size=(5, 5), activation='relu', strides=1),
            tf.keras.layers.BatchNormalization(),
            tf.keras.layers.Conv2DTranspose(filters=1, kernel_size=(8, 8), activation='sigmoid', strides=2),
            tf.keras.layers.BatchNormalization(),
        ])

    def call(self, inputs):
        x = self.fc(inputs)
        x = tf.reshape(x, [-1, 5, 5, 128])
        y = self.d_conv(x)
        return y

if __name__ == '__main__':

    encoder = Encoder()
    decoder = Decoder()

    out = encoder.predict(x_train)
    plt.scatter(out.T[0], out.T[1], c=y_train, s=1)
    plt.show()

    model = tf.keras.Sequential([
        encoder, decoder
    ])

    model.compile(optimizer='adam', loss='MSE')

    model.fit(x_train, x_train, batch_size=1024, epochs=100)

    out = encoder.predict(x_train)
    plt.scatter(out.T[0], out.T[1], c=y_train, s=1)
    plt.show()

encode before training

请添加图片描述

encode after training

请添加图片描述

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

### 使用自编码器进行MNIST数据集的图像重建 #### 加载并预处理数据集 为了使用自编码器MNIST数据集执行图像重建,首先要加载和预处理该数据集。通常情况下,会利用TensorFlow或PyTorch这样的库来简化这一过程。 ```python import tensorflow as tf from tensorflow.keras import layers, models # 加载MNIST数据集 (x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data() # 归一化像素值至0-1范围,并调整形状适应模型输入需求 x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape((len(x_train), 28, 28, 1)) x_test = x_test.reshape((len(x_test), 28, 28, 1)) ``` #### 构建自编码器架构 接下来定义一个简单的卷积自编码器结构,其中包含用于压缩输入图像到低维度表示形式的编码部分以及负责从这种紧凑表征还原原始图像外观的解码组件[^4]。 ##### 编码器设计 编码器接收二维灰度图作为输入并通过一系列下采样操作逐步减少空间分辨率的同时增加通道数以捕捉更复杂的模式特征: ```python input_img = tf.keras.Input(shape=(28, 28, 1)) encoded = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) encoded = layers.MaxPooling2D((2, 2), padding='same')(encoded) encoded = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(encoded) encoded = layers.MaxPooling2D((2, 2), padding='same')(encoded) encoder_output = layers.Conv2D(8, (3, 3), strides=(2,2), activation='relu', padding='same')(encoded) ``` ##### 解码器设计 相反地,解码器的任务是从上述获得的小尺寸高密度描述反向推导回接近初始状态的大尺度稀疏分布: ```python decoded = layers.Conv2DTranspose(8, (3, 3), strides=2, activation='relu', padding='same')(encoder_output) decoded = layers.UpSampling2D((2, 2))(decoded) decoded = layers.Conv2DTranspose(16, (3, 3), activation='relu', padding='same')(decoded) decoded = layers.UpSampling2D((2, 2))(decoded) decoder_output = layers.Conv2D(1, (3, 3), activation='sigmoid', padding='same')(decoded) ``` 整个自编码框架由这两大部分串联而成形成端到端可微分的学习系统[^1]。 #### 训练自编码器 完成模型搭建之后就可以编译并启动训练流程了,在此期间损失函数衡量的是预测输出与实际目标之间的差异程度,而优化算法则致力于最小化这个差距从而提升整体性能表现: ```python autoencoder = models.Model(input_img, decoder_output) autoencoder.compile(optimizer='adam', loss='binary_crossentropy') history = autoencoder.fit( x_train, x_train, epochs=50, batch_size=256, shuffle=True, validation_data=(x_test, x_test), ) ``` #### 展示重建效果 一旦训练结束便可以通过可视化手段直观感受来自编码再解码环节前后变化情况,以此评估所建立系统的有效性及稳定性[^2]: ```python import matplotlib.pyplot as plt def plot_reconstruction(original_images, reconstructed_images): n = 10 # 显示的数量 plt.figure(figsize=(20, 4)) for i in range(n): ax = plt.subplot(2, n, i + 1) plt.imshow(original_images[i].reshape(28, 28), cmap="gray") ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(2, n, i + 1 + n) plt.imshow(reconstructed_images[i].reshape(28, 28), cmap="gray") ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() reconstructions = autoencoder.predict(x_test[:10]) plot_reconstruction(x_test[:10], reconstructions) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值