Tensorflow之RNN,LSTM
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow之RNN,LSTM
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Tensorflow之RNN,LSTM
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ tensorflow之RNN 循環神經網絡做手寫數據集分類 """import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data#設置隨機數來比較兩種計算結果 tf.set_random_seed(1)#導入手寫數據集 mnist = input_data.read_data_sets('MNIST_data', one_hot=True)#設置參數 lr = 0.001 training_iters = 100000 batch_size = 128n_inputs = 28 # MNIST 輸入為圖片(img shape: 28*28)對應到圖片像素的一行 n_steps = 28 # time steps 對應到圖片有多少列 n_hidden_units = 128 # 隱藏層神經元個數 n_classes = 10 # MNIST分類結果為10#定義權重 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]))} #定義bias 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):#作為cell輸入的隱藏層#######################################################輸入層#將輸入shape從X三維輸入變為二維(128 batch * 28 steps, 128 hidden)X = tf.reshape(X, [-1,n_inputs])#隱藏層# X_in = (128 batch * 28 steps, 128 hidden)X_in = tf.matmul(X, weights['in']) + biases['in']# 傳給cell時需要將二維轉為三維X_in ==> (128 batch, 28 steps, 128 hidden)X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])#cell########################################################LSTM cell forget_bias=1.0表示最開始學習我們不希望忘掉任何state,#state_is_tuple=True這個為true表示記錄每個時間點的cell狀態和輸出值,以后會默認為truecell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units,forget_bias=1.0,state_is_tuple=True)#將lstm cell 分成兩部分(c_state, h_state),對應到lstm一個是主線c_state(沒有cell的遺忘),
#支線是h_state(有cell的遺忘),zero_state將每個t時間的cell初始化為0,init_state = cell.zero_state(batch_size, dtype=tf.float32)#outputs為lstm所有輸出結果包括每個時刻cell的state,和輸出值,final_state為最后的結果,
#time_major參數表示時間序列的位置是否為輸入數據的第一個維度,由于我們是在第二個維度,所以為falseoutputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)#1.將隱藏層的輸出作為最后結果,只有一個結果#results = tf.matmul(final_state[1], weights['out']) + biases['out']#2.將每一步的結果輸出到lists,在對outputs unstack后[1,0, 2]是將outputs list中每個tuple中元素對應展開tf.unstack(tf.transpose(outputs, [1, 0, 2]))results = tf.matmul(outputs[-1], weights['out']) + biases['out'] # shape = (128, 10)return resultspred = RNN(x, weights, biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) 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 = 0while 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
?
轉載于:https://www.cnblogs.com/xmeo/p/7230723.html
總結
以上是生活随笔為你收集整理的Tensorflow之RNN,LSTM的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 企业全面运营管理沙盘模拟心得_企业经营沙
- 下一篇: 今天狂想自杀,找了两个星期的工具,原来我