import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #載入數據集 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) #輸入的圖片是28*28 n_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,weight,biases): inputs=tf.reshape(X,[-1,max_time,n_inputs]) #定義LSTM基本CELL lstm_cell=tf.contrib.rnn.BasicLSTMCell(lstm_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進行優化 trian_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #結果存放在一個布爾型列表中 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax返回一維張量中最大的值所在的位置 #求准確率 accuarcy=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(trian_step, feed_dict={x:batch_xs,y:batch_ys}) acc=sess.run(accuarcy, feed_dict={x:mnist.test.images,y:mnist.test.labels}) print ("Iter "+str(epoch)+", Testing Accuarcy= " + str(acc))
運行結果:
目錄:
- tensorflow簡介、目錄
- tensorflow中的圖(02-1)
- tensorflow變量的使用(02-2)
- tensorflow中的Fetch、Feed(02-3)
- tensorflow版helloworld---擬合線性函數的k和b(02-4)
- tensorflow非線性回歸(03-1)
- MNIST手寫數字分類simple版(03-2)
- 二次代價函數、交叉熵(cross-entropy)、對數似然代價函數(log-likelihood cost)(04-1)
- 多層網絡通過防止過擬合,增加模型的准確率(04-2)
- 修改優化器進一步提升准確率(04-3)
- 手寫數字識別-卷積神經網絡cnn(06-2)
- 循環神經網絡rnn與長短時記憶神經網絡簡述(07-2)
- 循環神經網絡lstm代碼實現(07-3)
- tensorflow模型保存和使用08
- 下載inception v3 google訓練好的模型並解壓08-3
- 使用inception v3做各種圖像分類識別08-4
- word2vec模型訓練簡單案例
- word2vec+textcnn文本分類簡述及代碼