一、概述
AutoEncoder大致是一個將數據的高維特征進行壓縮降維編碼,再經過相反的解碼過程的一種學習方法。學習過程中通過解碼得到的最終結果與原數據進行比較,通過修正權重偏置參數降低損失函數,不斷提高對原數據的復原能力。學習完成后,前半段的編碼過程得到結果即可代表原數據的低維“特征值”。通過學習得到的自編碼器模型可以實現將高維數據壓縮至所期望的維度,原理與PCA相似。

二、模型實現
1. AutoEncoder
首先在MNIST數據集上,實現特征壓縮和特征解壓并可視化比較解壓后的數據與原數據的對照。
先看代碼:
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # 導入MNIST數據 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=False) learning_rate = 0.01 training_epochs = 10 batch_size = 256 display_step = 1 examples_to_show = 10 n_input = 784 # tf Graph input (only pictures) X = tf.placeholder("float", [None, n_input]) # 用字典的方式存儲各隱藏層的參數 n_hidden_1 = 256 # 第一編碼層神經元個數 n_hidden_2 = 128 # 第二編碼層神經元個數 # 權重和偏置的變化在編碼層和解碼層順序是相逆的 # 權重參數矩陣維度是每層的 輸入*輸出,偏置參數維度取決于輸出層的單元數 weights = { 'encoder_h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'encoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'decoder_h1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])), 'decoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_input])), } biases = { 'encoder_b1': tf.Variable(tf.random_normal([n_hidden_1])), 'encoder_b2': tf.Variable(tf.random_normal([n_hidden_2])), 'decoder_b1': tf.Variable(tf.random_normal([n_hidden_1])), 'decoder_b2': tf.Variable(tf.random_normal([n_input])), } # 每一層結構都是 xW + b # 構建編碼器 def encoder(x): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1'])) layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2'])) return layer_2 # 構建解碼器 def decoder(x): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']), biases['decoder_b1'])) layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']), biases['decoder_b2'])) return layer_2 # 構建模型 encoder_op = encoder(X) decoder_op = decoder(encoder_op) # 預測 y_pred = decoder_op y_true = X # 定義代價函數和優化器 cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2)) #最小二乘法 optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) with 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) #總批數 for epoch in range(training_epochs): 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}) if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c)) print("Optimization Finished!") encode_decode = sess.run( y_pred, feed_dict={X: mnist.test.images[:examples_to_show]}) 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()
|
新聞熱點
疑難解答