代碼:
import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
運行結果:
Extracting MNIST_data/train-images-idx3-ubyte.gzExtracting MNIST_data/train-labels-idx1-ubyte.gzExtracting MNIST_data/t10k-images-idx3-ubyte.gzExtracting MNIST_data/t10k-labels-idx1-ubyte.gz
代碼:
# 輸入圖片是28*28n_inputs = 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])#初始化權值weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1))#初始化偏置值biases = tf.Variable(tf.constant(0.1, shape=[n_classes]))#定義RNN網路def RNN(X,weights,biases): # inputs=[batch_size, max_time, n_inputs] inputs = tf.reshape(X,[-1,max_time,n_inputs]) #定義LSTM基本CELL lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_size) # final_state[state, batch_size, cell.state_size] # final_state[0]是cell state # final_state[1]是hidden_state 最後輸出的訊號 # 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]`. 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(logits=prediction,labels=y))#使用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))#把correct_prediction變為float32類型#初始化init = tf.global_variables_initializer()with tf.Session() as sess: sess.run(init) for epoch 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(epoch) + ", Testing Accuracy= " + str(acc))
運行結果:
Iter 0, Testing Accuracy= 0.7258Iter 1, Testing Accuracy= 0.7861Iter 2, Testing Accuracy= 0.8223Iter 3, Testing Accuracy= 0.8923Iter 4, Testing Accuracy= 0.9145Iter 5, Testing Accuracy= 0.9193