当前位置:   article > 正文

自编码器详细说明_自编码器要输入可以是张量吗

自编码器要输入可以是张量吗

自编码器(Autoencoder)是一种无监督学习算法,可以用于降维、特征提取、数据去噪等任务。自编码器包含编码器和解码器两部分,编码器将输入数据压缩成潜在表示,解码器将潜在表示还原成原始数据。通过调整自编码器的参数,使得解码器还原出的数据与原始数据的误差最小,从而学习到数据的低维表示。在实际应用中,自编码器可以用于图像压缩、图像去噪、图像生成等任务。

下面是一个自编码器的 Python 代码示例,用于对 MNIST 数据集中的手写数字进行压缩和解压缩:

  1. import numpy as np
  2. import tensorflow as tf
  3. import matplotlib.pyplot as plt
  4. # 加载 MNIST 数据集
  5. from tensorflow.examples.tutorials.mnist import input_data
  6. mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
  7. # 定义自编码器的输入和输出维度
  8. input_dim = 784 # 28x28 像素
  9. output_dim = input_dim
  10. # 定义自编码器的网络结构
  11. def autoencoder(x):
  12. # 定义编码器的网络结构
  13. hidden_layer = tf.layers.dense(x, 256, activation=tf.nn.relu)
  14. encoding_layer = tf.layers.dense(hidden_layer, 64, activation=tf.nn.relu)
  15. # 定义解码器的网络结构
  16. hidden_layer2 = tf.layers.dense(encoding_layer, 256, activation=tf.nn.relu)
  17. decoding_layer = tf.layers.dense(hidden_layer2, output_dim, activation=tf.nn.sigmoid)
  18. return decoding_layer
  19. # 定义输入张量和输出张量的占位符
  20. inputs = tf.placeholder(tf.float32, shape=[None, input_dim])
  21. outputs = tf.placeholder(tf.float32, shape=[None, output_dim])
  22. # 定义自编码器的损失函数和优化器
  23. encoded = autoencoder(inputs)
  24. loss = tf.reduce_mean(tf.square(outputs - encoded))
  25. optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
  26. # 开始训练自编码器
  27. num_epochs = 20
  28. batch_size = 256
  29. num_batches = mnist.train.num_examples // batch_size
  30. with tf.Session() as sess:
  31. sess.run(tf.global_variables_initializer())
  32. for epoch in range(num_epochs):
  33. for batch in range(num_batches):
  34. batch_inputs, _ = mnist.train.next_batch(batch_size)
  35. sess.run(optimizer, feed_dict={inputs: batch_inputs, outputs: batch_inputs})
  36. # 每个 epoch 完成后输出一次损失值
  37. training_loss = sess.run(loss, feed_dict={inputs: mnist.train.images, outputs: mnist.train.images})
  38. print("Epoch: {}/{}... Training loss: {}".format(epoch+1, num_epochs, training_loss))
  39. # 在测试集上测试自编码器
  40. test_images = mnist.test.images[:10]
  41. reconstructed = sess.run(encoded, feed_dict={inputs: test_images})
  42. # 显示原始图像和重构图像
  43. n = 10 # 显示的数字数量
  44. plt.figure(figsize=(20, 4))
  45. for i in range(n):
  46. # 显示原始图像
  47. ax = plt.subplot(2, n, i + 1)
  48. plt.imshow(test_images[i].reshape(28, 28))
  49. plt.gray()
  50. ax.get_xaxis().set_visible(False)
  51. ax.get_yaxis().set_visible(False)
  52. # 显示重构图像
  53. ax = plt.subplot(2, n, i + 1 + n)
  54. plt.imshow(reconstructed[i].reshape(28, 28))
  55. plt.gray()
  56. ax.get_xaxis().set_visible(False)
  57. ax.get_yaxis().set_visible(False)
  58. plt.show()

这段代码定义了一个基于 TensorFlow 的自编码器,并使用 MNIST 数据集进行训练和测试。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号