一、概述
成都創(chuàng)新互聯(lián)專注于四子王企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),商城網(wǎng)站建設(shè)。四子王網(wǎng)站建設(shè)公司,為四子王等地區(qū)提供建站服務(wù)。全流程按需定制,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)AutoEncoder大致是一個(gè)將數(shù)據(jù)的高維特征進(jìn)行壓縮降維編碼,再經(jīng)過相反的解碼過程的一種學(xué)習(xí)方法。學(xué)習(xí)過程中通過解碼得到的最終結(jié)果與原數(shù)據(jù)進(jìn)行比較,通過修正權(quán)重偏置參數(shù)降低損失函數(shù),不斷提高對(duì)原數(shù)據(jù)的復(fù)原能力。學(xué)習(xí)完成后,前半段的編碼過程得到結(jié)果即可代表原數(shù)據(jù)的低維“特征值”。通過學(xué)習(xí)得到的自編碼器模型可以實(shí)現(xiàn)將高維數(shù)據(jù)壓縮至所期望的維度,原理與PCA相似。
二、模型實(shí)現(xiàn)
1. AutoEncoder
首先在MNIST數(shù)據(jù)集上,實(shí)現(xiàn)特征壓縮和特征解壓并可視化比較解壓后的數(shù)據(jù)與原數(shù)據(jù)的對(duì)照。
先看代碼:
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # 導(dǎo)入MNIST數(shù)據(jù) 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]) # 用字典的方式存儲(chǔ)各隱藏層的參數(shù) n_hidden_1 = 256 # 第一編碼層神經(jīng)元個(gè)數(shù) n_hidden_2 = 128 # 第二編碼層神經(jīng)元個(gè)數(shù) # 權(quán)重和偏置的變化在編碼層和解碼層順序是相逆的 # 權(quán)重參數(shù)矩陣維度是每層的 輸入*輸出,偏置參數(shù)維度取決于輸出層的單元數(shù) weights = { 'encoder_h2': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'encoder_h3': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'decoder_h2': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])), 'decoder_h3': 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])), } # 每一層結(jié)構(gòu)都是 xW + b # 構(gòu)建編碼器 def encoder(x): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h2']), biases['encoder_b1'])) layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h3']), biases['encoder_b2'])) return layer_2 # 構(gòu)建解碼器 def decoder(x): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h2']), biases['decoder_b1'])) layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h3']), biases['decoder_b2'])) return layer_2 # 構(gòu)建模型 encoder_op = encoder(X) decoder_op = decoder(encoder_op) # 預(yù)測(cè) y_pred = decoder_op y_true = X # 定義代價(jià)函數(shù)和優(yōu)化器 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) # 首先計(jì)算總批數(shù),保證每次循環(huán)訓(xùn)練集中的每個(gè)樣本都參與訓(xùn)練,不同于批量訓(xùn)練 total_batch = int(mnist.train.num_examples/batch_size) #總批數(shù) 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()