Tensorflow 实现自编码

来源:互联网 发布:如何使用r软件 编辑:程序博客网 时间:2024/06/04 22:38

概述

AutoEncoder大致是一个将数据的高维特征进行压缩降维编码,再经过相反的解码过程的一种学习方法。学习过程中通过解码得到的最终结果与原数据进行比较,通过修正权重偏置参数降低损失函数,不断提高对原数据的复原能力。学习完成后,前半段的编码过程得到结果即可代表原数据的低维“特征值”。通过学习得到的自编码器模型可以实现将高维数据压缩至所期望的维度,原理与PCA相似。

  • 自编码器是利用神经网络提取出图像中的高阶特征,同时可以利用高阶特征重构自己
  • 如果向原图中添加噪声,则可以通过高阶特征的提取,对原始图像进行去噪
  • tensorflow实战第四章内容

其模型类似于下图:
Autocorder.png

自编码器的实现

TensorFlow的自编码网络实现(MNIST无监督学习) (自动编解码) 左边网络编码 右边网络解码, 然后让编码 前的数据 和 解码 后的数据 保持一致 。 (编码前的当 label ,解码后的当 target) 自编码网络

  • 自编码网络的作用 自编码网络的作用就是将输入样本压缩到隐藏层,然后解压,在输出端重建样本,最终输出层神经元数量等于输入层神经元的数量。
  • 这里主要有两个过程,压缩和解压。
  • 压缩原理 压缩依靠的是输入数据(图像、文字、声音)本身存在不同成都的冗余信息,自动编码网络学习去掉这些冗余信息,把有用的特征输入到隐藏层中。
  • 多个隐藏层的主要作用 多个隐藏层的主要作用是,如果输入的数据是图像,第一层会学习如何识别边,第二层会学习如何组合边,从而构成轮廓、角等,更高层学习如何去组合更有意义的特征。
  • 下面我们还以MINST数据集为例,讲解一下自编码器的运用
第一步 加载数据 先导入必要的库 from __future__ import division, print_function, absolute_importimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt# Import MNIST datafrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data", one_hot=False) 第二部 构建模型 设置训练的参数包括学习率训练的轮数全部数据训练完一遍成为一轮)、每次训练的而数据多少每隔多少轮显示一次训练结果# Parameterslearning_rate = 0.01training_epochs = 5batch_size = 256display_step = 1examples_to_show = 10 初始化权重与定义网络结构我们设计这个自动编码网络还有两个隐藏层第一个隐藏层神经元为256个第二个隐藏层神经元为128个定义网络参数如下# Network Parametersn_input = 784  # MNIST data input (img shape: 28*28)# tf Graph input (only pictures)X = tf.placeholder("float", [None, n_input])# hidden layer settingsn_hidden_1 = 256 # 1st layer num featuresn_hidden_2 = 128 # 2nd layer num features 初始化每一层的权重和偏置如下# Building the encoderdef encoder(x):    # Encoder Hidden layer with sigmoid activation #1    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']),                                   biases['encoder_b1']))    # Decoder Hidden layer with sigmoid activation #2    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']),                                   biases['encoder_b2']))    return layer_2# Building the decoderdef decoder(x):    # Encoder Hidden layer with sigmoid activation #1    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']),                                   biases['decoder_b1']))    # Decoder Hidden layer with sigmoid activation #2    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']),                                   biases['decoder_b2']))    return layer_2 构建模型# Construct modelencoder_op = encoder(X)decoder_op = decoder(encoder_op) 构建损失函数和优化器这里的损失函数用最小二乘法对原始数据集和输出的数据集进行平方差并取均值运算优化器采用RMSPropOptimizer# Predictiony_pred = decoder_op# Targets (Labels) are the input data.y_true = X# Define loss and optimizer, minimize the squared errorcost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) 第三部 训练数据及评估模型 在回话中启动图开始训练和评估 # Launch the graphwith tf.Session() as sess:    # tf.initialize_all_variables() no long valid from    # 2017-03-02 if using tensorflow >= 0.12    if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:        init = tf.initialize_all_variables()    else:        init = tf.global_variables_initializer()    sess.run(init)    total_batch = int(mnist.train.num_examples/batch_size)    # Training cycle    for epoch in range(training_epochs):        # Loop over all batches        for i in range(total_batch):            batch_xs, batch_ys = mnist.train.next_batch(batch_size)  # max(x) = 1, min(x) = 0            # Run optimization op (backprop) and cost op (to get loss value)            _, c = sess.run([optimizer, cost], feed_dict={X: batch_xs})        # Display logs per epoch step        if epoch % display_step == 0:            print("Epoch:", '%04d' % (epoch+1),                  "cost=", "{:.9f}".format(c))    print("Optimization Finished!")    # # Applying encode and decode over test set    encode_decode = sess.run(        y_pred, feed_dict={X: mnist.test.images[:examples_to_show]})    # Compare original images with their reconstructions    f, a = plt.subplots(2, 10, figsize=(10, 2))    for i in range(examples_to_show):        a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))        a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))    plt.show()    # encoder_result = sess.run(encoder_op, feed_dict={X: mnist.test.images})    # plt.scatter(encoder_result[:, 0], encoder_result[:, 1], c=mnist.test.labels)    # plt.colorbar()    # plt.show()

代码解读: 首先,导入将要使用到的各种库和数据集,定义各个参数如学习率、训练迭代次数等,清晰明了便于后期修改。由于自编码器的神经网络结构非常有规律性,都是xW + b的结构,故将每一层的权重W和偏置b的变量tf.Variable统一置于一个字典中,通过字典的key值更加清晰明了的描述。模型构建思路上,将编码器部分和解码器部分分开构建,每一层的激活函数使用Sigmoid函数,编码器通常与编码器使用同样的激活函数。通常编码器部分和解码器部分是一个互逆的过程,例如我们设计将784维降至256维再降至128维的编码器,解码器对应的就是从128维解码至256维再解码至784维。定义代价函数,代价函数表示为解码器的输出与原始输入的最小二乘法表达,优化器采用AdamOptimizer训练阶段每次循环将所有的训练数据都参与训练。经过训练,最终将训练结果与原数据可视化进行对照,如下图,还原度较高。如果增大训练循环次数或者增加自编码器的层数,可以得到更好的还原效果。

运行结果:Autocorder result.png

原创粉丝点击