TensorFlow人工智能入門教程之十一 最強網絡DLSTM 雙向長短時間記憶網絡(阿里小AI實現)

         失眠 。。。。上一章 講了 最強網絡之一 RSNN 深度殘差網絡 這一章節 咱們來說講  還有一個很強的網絡模型,就是雙向LSTM 也就是前一陣阿里吹牛逼的小AI的 實現的一個重要網絡部分,固然實際上 比這還要複雜 層數 以及 多個網絡配合,其實就好像 alphaGo 同樣,其實多個網絡配合 多層 複用 效果是最好的,這就像 咱們有大腦第一中樞系統 ,可是咱們脊髓 是第二中樞系統同樣,脊髓能夠控制咱們身體的某些肌肉 關節運動,與大腦相互配合調節,經過神經傳輸 相互傳遞信息,互相配合調節,大腦爲主 脊髓爲輔。python

     最近在學鋼琴,那真難。有些東西境界到的人 懂的人天然會懂。因此我博客分享一下個人理解,這都是本身自學摸索研究的東西,主要一是 但願能夠給本身 作個整理,無聊寫寫東西,其實這些東西 對我來講都是不重要的東西,可是可讓你們 學習瞭解下人工智能,人工智能 就這麼點麼,這是基礎,前面全部章節所有是基礎 ,基礎知識,你所有掌握了這些,你還只是一個門外漢,最主要的是要可以熟練的使用 ,不管是用來作什麼,爲所欲爲,因地制宜,可以知道怎麼運用,這纔是最重要的。因此我把這些對我來講還算很簡單的知識吧,這裏以及後面,至於方向,我將的東西也許有些是本身的理解,可是絕對不會影響你們的使用,本人去年一年創業 就是使用tensorflow ,而後把它在spark上整合實現了,從新改寫了bp反饋層 ff前向層 同時改寫了部分代碼、實現了0.6時候的tensorflow的與spark 並行 訓練,因此對人工智能方面 也許沒有很好的數學基礎,可是對代碼 對理解方面 仍是算能夠的吧。創業項目基本就是人工智能的運用 以及 使用。git

       雙向LSTM 阿里的小AI 就是使用它,我估計是使用了雙向LSTM 以後接着一個RNN層 並 加強學習。 可是小AI 裏面最重要的仍是這個雙向LSTM,結合RNN 結合 其餘的幾種網絡 還有加強學習 .  網絡

        LSTM 是爲了解決 RNN的一些問題,對隱藏層進行改進,讓前面上下文信息 可以有更遠的印象,也就是記憶,架構

       LSTM網絡本質仍是RNN網絡,基於LSTM的RNN架構上的變化有最早的BRNN(雙向)dom

 LSTM引入了Cell 與其說LSTM是一種RNN結構,倒不如說LSTM是RNN的一個魔改組件,把上面看到的網絡中的小圓圈換成LSTM的block,就是所謂的LSTM了。那它的block長什麼樣子呢? oop

      

  1. Cell,就是咱們的小本子,有個叫作state的參數東西來記事兒的學習

  2. Input Gate,Output Gate,在參數輸入輸出的時候起點做用,算一算東西測試

  3. Forget Gate:遺忘門 就像人體的遺忘曲線同樣,正是由於遺忘的調節才能知道 那些更重要,由於原始的LSTM在這個位置就是一個值1,是鏈接到下一時間的那個參數,之前的事情記太牢了,最近的就不住就很差了,因此要選擇性遺忘一些東西。經過遺忘進行調節,這樣知道那些更重要。那些值得記憶。ui

            上上一章咱們講了RNN/LSTM 的使用,因此 那些操做 不理解的能夠到上上一章去看。人工智能

 這裏講一下雙向LSTM 

     LSTM網絡本質仍是RNN網絡,基於LSTM的RNN架構上的變化有最早的BRNN(雙向)

   在大多數 應用裏面 NLP 自動問答 基於時間有關的 上下文有關的,通常都是雙向LSTM+LSTM/RNN橫向擴展 來實現的 ,效果很是好。好像國內不少吹逼的 都是這樣的機構實現的,雖然叫的名字不一樣可是 實際上是一個東西。

雙向LSTM 顧名思義採用了 可以雙向的LSTM cell單元。是的每次可以訪問 下文 也能訪問下文

     下面看看BIRNN的結構

    

而 LSTM 咱們上面講了 其實就是RNN 把其中的組件部位換了 加上了cell 也就是記憶單元。 因此雙向LSTM

就是把上面雙向RNN 裏面h 那些園的單元所有換成LSTM單元 就是雙向LSTM. 阿里的小AI 就是使用它,我估計是使用了雙向LSTM 以後接着一個RNN層 吧。 可是小AI 裏面最重要的仍是這個雙向LSTM,結合RNN 結合 其餘的幾種網絡 還有加強學習 . 

   雙向LSTM 在tensorflow中 與 上上篇文章 不一樣的地方就是

  咱們直接使用rnn.rnn 來構建RNN 而後傳入的LSTMcell(單元) ,這裏雙向是

   

rnn.bidirectional_rnn

其餘基本與上上章基本相同 ,替換一下 稍微修改下便可,不理解的能夠跳回去 看看 上上章 LSTM/RNN的內容

下面貼出 示例代碼 

import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

import tensorflow as tf
from tensorflow.python.ops.constant_op import constant
from tensorflow.models.rnn import rnn, rnn_cell
import numpy as np

# Parameters
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Network Parameters
n_input = 28 # MNIST data input (img shape: 28*28)
n_steps = 28 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 10 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
# Tensorflow LSTM cell requires 2x n_hidden length (state & cell)
istate_fw = tf.placeholder("float", [None, 2*n_hidden])
istate_bw = tf.placeholder("float", [None, 2*n_hidden])
y = tf.placeholder("float", [None, n_classes])

# Define weights
weights = {
    # Hidden layer weights => 2*n_hidden because of foward + backward cells
    'hidden': tf.Variable(tf.random_normal([n_input, 2*n_hidden])),
    'out': tf.Variable(tf.random_normal([2*n_hidden, n_classes]))
}
biases = {
    'hidden': tf.Variable(tf.random_normal([2*n_hidden])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

def BiRNN(_X, _istate_fw, _istate_bw, _weights, _biases, _batch_size, _seq_len):

    # BiRNN requires to supply sequence_length as [batch_size, int64]
    # Note: Tensorflow 0.6.0 requires BiRNN sequence_length parameter to be set
    # For a better implementation with latest version of tensorflow, check below
    _seq_len = tf.fill([_batch_size], constant(_seq_len, dtype=tf.int64))

    # input shape: (batch_size, n_steps, n_input)
    _X = tf.transpose(_X, [1, 0, 2])  # permute n_steps and batch_size
    # Reshape to prepare input to hidden activation
    _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)
    # Linear activation
    _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']

    # Define lstm cells with tensorflow
    # Forward direction cell
    lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
    # Backward direction cell
    lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
    # Split data because rnn cell needs a list of inputs for the RNN inner loop
    _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)

    # Get lstm cell output
    outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, _X,
                                            initial_state_fw=_istate_fw,
                                            initial_state_bw=_istate_bw,
                                            sequence_length=_seq_len)

    # Linear activation
    # Get inner loop last output
    return tf.matmul(outputs[-1], _weights['out']) + _biases['out']

pred = BiRNN(x, istate_fw, istate_bw, weights, biases, batch_size, n_steps)


# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        # Reshape data to get 28 seq of 28 elements
        batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))
        # Fit training using batch data
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys,
                                       istate_fw: np.zeros((batch_size, 2*n_hidden)),
                                       istate_bw: np.zeros((batch_size, 2*n_hidden))})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,
                                                istate_fw: np.zeros((batch_size, 2*n_hidden)),
                                                istate_bw: np.zeros((batch_size, 2*n_hidden))})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,
                                             istate_fw: np.zeros((batch_size, 2*n_hidden)),
                                             istate_bw: np.zeros((batch_size, 2*n_hidden))})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + \
                  ", Training Accuracy= " + "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    # Calculate accuracy for 128 mnist test images
    test_len = 128
    test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
    test_label = mnist.test.labels[:test_len]
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label,
                                                             istate_fw: np.zeros((test_len, 2*n_hidden)),
                                                             istate_bw: np.zeros((test_len, 2*n_hidden))})

下面貼出運行測試截圖。

 

相關文章
相關標籤/搜索