天天看點

Tensorflow學習:循環(遞歸/記憶)神經網絡RNN(手寫數字識别:MNIST資料集分類)

Tensorflow學習:循環(遞歸/記憶)神經網絡RNN(手寫數字識别:MNIST資料集分類)

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 載入資料集
mnist = input_data.read_data_sets("MNST_data", one_hot=True)

# 輸入圖檔是28*28像素
n_inputs = 28  # 輸入一行,一行有28個資料(輸入層有28個神經元)
max_time = 28  # 一共28行
lstm_size = 100  # 隐層的單元
n_classes = 10  # 輸出10個分類
batch_size = 50  # 每個批次50個樣本
n_batch = mnist.train.num_examples // batch_size  # 計算一共有多少個批次

# 這裡的None表示第一個次元可以是任意的長度
x = tf.placeholder(tf.float32, [None, 784])
# 正确的标簽
y = tf.placeholder(tf.float32, [None, 10])

# 初始化權值[100,10]
weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1))
# 初始化偏置值[10]
biases = tf.Variable(tf.constant(0.1, shape=[n_classes]))


# 定義RNN網絡
def RNN(X, weights, biases):
    # inputs=[batch_size,max_time,n_inputs] = [50,28,28]
    inputs = tf.reshape(X, [-1, max_time, n_inputs])
    # 定義LSTM基本的CELL
    #lstm_cell = tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(lstm_size)
    lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(lstm_size)
    # final_state[0]:cell state,final_state[1]:hidden state
    outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, inputs, dtype=tf.float32)
    results = tf.nn.softmax(tf.matmul(final_state[1], weights) + biases)
    return results


# 計算RNN的傳回結果
prediction = RNN(x, weights, biases)

# 交叉熵代價函數
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
# 使用AdamOptimizer進行優化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 結果存放在一個布爾類型的清單中
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))  # argmax:傳回一位張量中最大值所在的位置,既标簽
# 求準确度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 初始化變量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    # 疊代6個周期
    for step in range(6):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
        print("Iter" + str(step) + ",Testing Accuracy=" + str(acc))

           

運作結果:

Tensorflow學習:循環(遞歸/記憶)神經網絡RNN(手寫數字識别:MNIST資料集分類)

繼續閱讀