天天看點

用LSTM做手寫數字識别

參考網址:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-08-RNN2/ ,感謝!

一張圖檔是28*28,我們把28行作為28個時刻的輸入。

注意輸入的次元,初始狀态的次元,LSTM中隐藏層的次元,最後輸出的次元。

一個LSTM單元的輸入是向量,是以tf.contrib.rnn.BasicLSTMCell有參數n_hidden_units,也就是隐藏單元個數。

初始狀态的個數跟batch_size和隐藏單元個數有關,這裡初始狀态的shape=(256, 128)。

如果使用tf.nn.dynamic_rnn(cell, inputs), 我們要确定 inputs 的格式. tf.nn.dynamic_rnn 中的 time_major 參數會針對不同 inputs 格式有不同的值.

如果 inputs 為 (batches, steps, inputs) ==> time_major=False;

如果 inputs 為 (steps, batches, inputs) ==> time_major=True;

在dynamic_rnn的源碼中是這樣解釋的:

輸入inputs:

The RNN inputs.

If

time_major == False

(default), this must be a

Tensor

of shape:

[batch_size, max_time, ...]

, or a nested tuple of such

elements.

If

time_major == True

, this must be a

Tensor

of shape:

[max_time, batch_size, ...]

, or a nested tuple of such

elements.

輸出outputs:

The RNN output

Tensor

.

If time_major == False (default), this will be a

Tensor

shaped:

[batch_size, max_time, cell.output_size]

.

If time_major == True, this will be a

Tensor

shaped:

[max_time, batch_size, cell.output_size]

.

計算最後的結果可以用隐狀态h_state(即final_state[1])來計算,也可以用最後一個時刻的output輸出來計算,結果是一樣的。

完整的代碼如下(複制代碼到編譯器上即可運作):

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
This code is a modified version of the code from this link:
https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py
His code is a very good one for RNN beginners. Feel free to check it out.
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# set random seed for comparing the two result calculations
tf.set_random_seed(1)

# this is data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# hyperparameters
lr = 0.001
training_iters = 100000
# batch_size = 128
batch_size = 256

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)

# tf Graph input
x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_classes])

# Define weights
weights = {   # 對權重進行随機初始化
    # (28, 128)
    'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),
    # (128, 10)
    'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))
}
biases = {   # 對偏差進行随機初始化
    # (128, )
    'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),
    # (10, )
    'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))
}

def RNN(X, weights, biases):
    # transpose the inputs shape from
    # X ==> (256 batch * 28 steps, 28 inputs)
    X = tf.reshape(X, [-1, n_inputs])

    # into hidden
    # X_in = (256 batch * 28 steps, 128 hidden)
    X_in = tf.matmul(X, weights['in']) + biases['in']   # 這裡的次元是(256*28,128),輸入先經過一個線性變化
    # X_in ==> (256 batch, 28 steps, 128 hidden)
    X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])   # 這裡的次元是(256,28,128)

    # cell
    cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units)  # 一個lstm單元的輸入是向量,是以有這麼多隐藏單元n_hidden_units
    # lstm cell is divided into two parts (c_state, h_state)
    init_state = cell.zero_state(batch_size, dtype=tf.float32)   # 初始狀态的次元跟batch_size和隐藏單元個數有關,這裡shape=(256, 128)

    outputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)

    # hidden layer for output as the final results
    # results = tf.matmul(final_state[1], weights['out']) + biases['out']    # 可以這樣用隐狀态final_state[1]求results,也可以用下面的方法即最後時刻的輸出outputs求results

    # # or
    # unpack to list [(batch, outputs)..] * steps
    # 這裡的outputs是[batch_size, max_time, cell.output_size]的形式,現在要取最後一個時間的outputs,是以要調換一下max_time和batch_size,這樣就可以直接用outputs[-1]來得到最後一個的輸出
    outputs = tf.unstack(tf.transpose(outputs, [1,0,2]))  # tf.unstack預設是按行分解。
    results = tf.matmul(outputs[-1], weights['out']) + biases['out']    # shape = (128, 10)  # outputs[-1]是指最後一個時間的輸出,outputs[-1]再經過一個線性變化得到結果

    return results

pred = RNN(x, weights, biases)  # 此時x還沒有數值,後面用feed_dict輸入
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))  # 此時y還沒有數值,後面用feed_dict輸入
train_op = tf.train.AdamOptimizer(lr).minimize(cost)

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

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    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])  # 把[batch_size,784]變形為[batch_size,28,28],這樣才符合x的次元
        sess.run(train_op, feed_dict={x: batch_xs,y: batch_ys,})
        if step % 20 == 0:
            batch_xs, batch_ys = mnist.test.next_batch(batch_size)   
            # 取batch_size大小的測試集,因為初始狀态跟batch_size有關,是以這裡取batch_size大小的測試集資料,否則會報錯。也可以把batch_size作為一個參數來傳遞
            batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
            print("time:",step," accuracy:",sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,}))
        step += 1
           

測試集準确率如下:

time: 0  accuracy: 0.23828125
time: 20  accuracy: 0.6796875
time: 40  accuracy: 0.74609375
time: 60  accuracy: 0.84375
time: 80  accuracy: 0.81640625
time: 100  accuracy: 0.875
time: 120  accuracy: 0.8828125
time: 140  accuracy: 0.91796875
time: 160  accuracy: 0.94140625
time: 180  accuracy: 0.89453125
time: 200  accuracy: 0.90625
time: 220  accuracy: 0.89453125
time: 240  accuracy: 0.96484375
time: 260  accuracy: 0.93359375
time: 280  accuracy: 0.953125
time: 300  accuracy: 0.953125
time: 320  accuracy: 0.94921875
time: 340  accuracy: 0.91796875
time: 360  accuracy: 0.93359375
time: 380  accuracy: 0.9453125
           

繼續閱讀