?本文使用 RNN 來進行分類的訓(xùn)練 (Classification). 會繼續(xù)使用到手寫數(shù)字 MNIST 數(shù)據(jù)集. 讓 RNN 從每張圖片的第一行像素讀到最后一行, 然后再進行分類判斷.
設(shè)置RNN參數(shù)
導(dǎo)入 MNIST 數(shù)據(jù)并確定 RNN 的各種參數(shù)(hyper-parameters):
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(1) # set random seed
# 導(dǎo)入數(shù)據(jù)
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主體結(jié)構(gòu)
定義 RNN 主體結(jié)構(gòu), 這個 RNN 總共有 3 個組成部分 ( input_layer, cell, output_layer). 首先先定義 input_layer:
def RNN(X, weights, biases):
# 原始的 X 是 3 維數(shù)據(jù), 需要把它變成 2 維數(shù)據(jù)才能使用 weights 的矩陣乘法
# X ==> (128 batches * 28 steps, 28 inputs)
X = tf.reshape(X, [-1, n_inputs])
# X_in = W*X + b
X_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 中的計算, 有兩種途徑:
- 使用
tf.nn.rnn(cell, inputs)(不推薦原因). 但是如果使用這種方法, 可以參考這個代碼; - 使用
tf.nn.dynamic_rnn(cell, inputs)(推薦). 這里將使用這種方式.
因 Tensorflow 版本升級原因, state_is_tuple=True 將在之后的版本中變?yōu)槟J(rèn). 對于 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 參數(shù)會針對不同 inputs 格式有不同的值.
- 如果
inputs為 (batches, steps, inputs) ==>time_major=False; - 如果
inputs為 (steps, batches, inputs) ==>time_major=True;
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=init_state, time_major=False)
最后是 output_layer 和 return 的值. 因為這個例子的特殊性, 有兩種方法可以求得 results.
方式一:
直接調(diào)用final_state 中的 h_state (final_state[1]) 來進行運算:
results = tf.matmul(final_state[1], weights['out']) + biases['out']
方式二:
調(diào)用最后一個 outputs (在這個例子中,和上面的final_state[1]是一樣的):
# 把 outputs 變成 列表 [(batch, outputs)..] * steps
outputs = tf.unstack(tf.transpose(outputs, [1,0,2]))
results = tf.matmul(outputs[-1], weights['out']) + biases['out'] #選取最后一個 output
在 def RNN() 的最后輸出 result
return results
定義好了 RNN 主體結(jié)構(gòu)后, 計算 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)
訓(xùn)練RNN
訓(xùn)練時, 不斷輸出 accuracy, 觀看結(jié)果:
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 = 0
while 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 的結(jié)果如下:
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
....