RNN LSTM 循环神经网络 (分类例子)
學習資料:
- 相關代碼
- 為 TF 2017 打造的新版可視化教學代碼
- 機器學習-簡介系列?什么是RNN
- 機器學習-簡介系列?什么是LSTM RNN
- 本代碼基于網上這一份代碼?code
設置 RNN 的參數
這次我們會使用 RNN 來進行分類的訓練 (Classification). 會繼續使用到手寫數字 MNIST 數據集. 讓 RNN 從每張圖片的第一行像素讀到最后一行, 然后再進行分類判斷. 接下來我們導入 MNIST 數據并確定 RNN 的各種參數(hyper-parameters):
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data tf.set_random_seed(1) # set random seed# 導入數據 mnist = input_data.read_data_sets('MNIST_data', one_hot=True)# hyperparameters lr = 0.001 # learning rate training_iters = 100000 # train step 上限 batch_size = 128 n_inputs = 28 # MNIST data input (img shape: 28*28) n_steps = 28 # time steps n_hidden_units = 128 # neurons in hidden layer n_classes = 10 # MNIST classes (0-9 digits)接著定義?x,?y?的?placeholder?和?weights,?biases?的初始狀況.
# x y placeholder x = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None, n_classes])# 對 weights biases 初始值的定義 weights = {# shape (28, 128)'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),# shape (128, 10)'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes])) } biases = {# shape (128, )'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),# shape (10, )'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ])) }定義 RNN 的主體結構
接著開始定義 RNN 主體結構, 這個 RNN 總共有 3 個組成部分 (?input_layer,?cell,?output_layer). 首先我們先定義?input_layer:
def RNN(X, weights, biases):# 原始的 X 是 3 維數據, 我們需要把它變成 2 維數據才能使用 weights 的矩陣乘法# X ==> (128 batches * 28 steps, 28 inputs)X = tf.reshape(X, [-1, n_inputs])# X_in = W*X + bX_in = tf.matmul(X, weights['in']) + biases['in']# X_in ==> (128 batches, 28 steps, 128 hidden) 換回3維X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])接著是?cell?中的計算, 有兩種途徑:
因 Tensorflow 版本升級原因,?state_is_tuple=True?將在之后的版本中變為默認. 對于?lstm?來說,?state可被分為(c_state, h_state).
# 使用 basic LSTM Cell.lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) # 初始化全零 state如果使用tf.nn.dynamic_rnn(cell, inputs), 我們要確定?inputs?的格式.?tf.nn.dynamic_rnn?中的?time_major?參數會針對不同?inputs?格式有不同的值.
最后是?output_layer?和?return?的值. 因為這個例子的特殊性, 有兩種方法可以求得?results.
方式一:?直接調用final_state?中的?h_state?(final_state[1]) 來進行運算:
results = tf.matmul(final_state[1], weights['out']) + biases['out']方式二:?調用最后一個?outputs?(在這個例子中,和上面的final_state[1]是一樣的):
# 把 outputs 變成 列表 [(batch, outputs)..] * stepsoutputs = tf.unstack(tf.transpose(outputs, [1,0,2]))results = tf.matmul(outputs[-1], weights['out']) + biases['out'] #選取最后一個 output在?def RNN()?的最后輸出?result
return results定義好了 RNN 主體結構后, 我們就可以來計算?cost?和?train_op:
pred = RNN(x, weights, biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) train_op = tf.train.AdamOptimizer(lr).minimize(cost)訓練 RNN
訓練時, 不斷輸出?accuracy, 觀看結果:
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))# init= tf.initialize_all_variables() # tf 馬上就要廢棄這種寫法 # 替換成下面的寫法: init = tf.global_variables_initializer()with tf.Session() as sess:sess.run(init)step = 0while step * batch_size < training_iters:batch_xs, batch_ys = mnist.train.next_batch(batch_size)batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])sess.run([train_op], feed_dict={x: batch_xs,y: batch_ys,})if step % 20 == 0:print(sess.run(accuracy, feed_dict={x: batch_xs,y: batch_ys,}))step += 1最終?accuracy?的結果如下:
0.1875 0.65625 0.726562 0.757812 0.820312 0.796875 0.859375 0.921875 0.921875 0.898438 0.828125 0.890625 0.9375 0.921875 0.9375 0.929688 0.953125 ....原文地址: https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-08-RNN2/
總結
以上是生活随笔為你收集整理的RNN LSTM 循环神经网络 (分类例子)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从Tensorflow代码中理解LSTM
- 下一篇: tensorflow笔记:多层LSTM代