赞
踩
自编码器(Autoencoder)是一种无监督学习算法,可以用于降维、特征提取、数据去噪等任务。自编码器包含编码器和解码器两部分,编码器将输入数据压缩成潜在表示,解码器将潜在表示还原成原始数据。通过调整自编码器的参数,使得解码器还原出的数据与原始数据的误差最小,从而学习到数据的低维表示。在实际应用中,自编码器可以用于图像压缩、图像去噪、图像生成等任务。
下面是一个自编码器的 Python 代码示例,用于对 MNIST 数据集中的手写数字进行压缩和解压缩:
- import numpy as np
- import tensorflow as tf
- import matplotlib.pyplot as plt
-
- # 加载 MNIST 数据集
- from tensorflow.examples.tutorials.mnist import input_data
- mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
-
- # 定义自编码器的输入和输出维度
- input_dim = 784 # 28x28 像素
- output_dim = input_dim
-
- # 定义自编码器的网络结构
- def autoencoder(x):
- # 定义编码器的网络结构
- hidden_layer = tf.layers.dense(x, 256, activation=tf.nn.relu)
- encoding_layer = tf.layers.dense(hidden_layer, 64, activation=tf.nn.relu)
-
- # 定义解码器的网络结构
- hidden_layer2 = tf.layers.dense(encoding_layer, 256, activation=tf.nn.relu)
- decoding_layer = tf.layers.dense(hidden_layer2, output_dim, activation=tf.nn.sigmoid)
- return decoding_layer
-
- # 定义输入张量和输出张量的占位符
- inputs = tf.placeholder(tf.float32, shape=[None, input_dim])
- outputs = tf.placeholder(tf.float32, shape=[None, output_dim])
-
- # 定义自编码器的损失函数和优化器
- encoded = autoencoder(inputs)
- loss = tf.reduce_mean(tf.square(outputs - encoded))
- optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
-
- # 开始训练自编码器
- num_epochs = 20
- batch_size = 256
- num_batches = mnist.train.num_examples // batch_size
-
- with tf.Session() as sess:
- sess.run(tf.global_variables_initializer())
- for epoch in range(num_epochs):
- for batch in range(num_batches):
- batch_inputs, _ = mnist.train.next_batch(batch_size)
- sess.run(optimizer, feed_dict={inputs: batch_inputs, outputs: batch_inputs})
-
- # 每个 epoch 完成后输出一次损失值
- training_loss = sess.run(loss, feed_dict={inputs: mnist.train.images, outputs: mnist.train.images})
- print("Epoch: {}/{}... Training loss: {}".format(epoch+1, num_epochs, training_loss))
-
- # 在测试集上测试自编码器
- test_images = mnist.test.images[:10]
- reconstructed = sess.run(encoded, feed_dict={inputs: test_images})
-
- # 显示原始图像和重构图像
- n = 10 # 显示的数字数量
- plt.figure(figsize=(20, 4))
- for i in range(n):
- # 显示原始图像
- ax = plt.subplot(2, n, i + 1)
- plt.imshow(test_images[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(reconstructed[i].reshape(28, 28))
- plt.gray()
- ax.get_xaxis().set_visible(False)
- ax.get_yaxis().set_visible(False)
- plt.show()
这段代码定义了一个基于 TensorFlow 的自编码器,并使用 MNIST 数据集进行训练和测试。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。