通過這篇博客,你可學到怎麼在tensorflow環境下搭建LSTM網絡(這裏包括單層與多層),同時使用matplotlib模塊畫圖,通過訓練完以後,把網絡保存下來,以後再次打開網絡就不需要再次訓練網絡,直接用即可。這裏我會演示保存下來的網絡怎麼恢復以及使用保存下來的網絡進行測試,就不要訓練了。首先建立一個LSTM.py,代碼如下:
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
import matplotlib.pyplot as plt
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot=True) # MNIST_data指的是存放數據的文件夾路徑,one_hot=True 爲採用one_hot的編碼方式編碼標籤
tf.reset_default_graph()
##//////新增打印///////////
plotdata={"batchsize":[],"loss":[]}
#///////////////////////////////
# 訓練參數
learning_rate = 0.001 # 學習率
training_steps = 10000 # 總迭代次數
batch_size = 128 # 批量大小
display_step = 200
# 網絡參數
num_input = 28 # MNIST數據集圖片: 28*28
timesteps = 28 # timesteps
num_hidden = 128 # 隱藏層神經元數
num_classes = 10 # MNIST 數據集類別數 (0-9 digits)
# 定義輸入
X = tf.placeholder("float", [None, timesteps, num_input],name="input_x")
Y = tf.placeholder("float", [None, num_classes],name="input_y")
# 定義權重和偏置
# weights矩陣[128, 10]
weights = {
'out': tf.Variable(tf.random_normal([num_hidden, num_classes]))
}
biases = {
'out': tf.Variable(tf.random_normal([num_classes]))
}
# 定義LSTM網絡
def LSTM(x, weights, biases):
# Prepare data shape to match `rnn` function requirements
# 輸入數據x的shape: (batch_size, timesteps, n_input)
# 需要的shape: 按 timesteps 切片,得到 timesteps 個 (batch_size, n_input)
# 對x進行切分
# tf.unstack(value,num=None,axis=0,name='unstack')
# value:要進行分割的tensor
# axis:整數,打算進行切分的維度
# num:整數,axis(打算切分)維度的長度
x = tf.unstack(x, timesteps, 1)
# 定義一個lstm cell,即上面圖示LSTM中的A
# n_hidden表示神經元的個數,forget_bias就是LSTM們的忘記係數,如果等於1,就是不會忘記任何信息。如果等於0,就都忘記。
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
# #/////////////添加多層///////////
# lstm_cell_1 = tf.contrib.rnn.BasicLSTMCell(num_units=512)
# lstm_cell_2 = tf.contrib.rnn.BasicLSTMCell(num_units=256)
# lstm_cell_3 = tf.contrib.rnn.BasicLSTMCell(num_units=128)
# lstm_cell=tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell_1,lstm_cell_2,lstm_cell_3])
#////////////////////////////////////
# 得到 lstm cell 輸出
# 輸出output和states
# outputs是一個長度爲T的列表,通過outputs[-1]取出最後的輸出
# state是最後的狀態
outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
# 線性激活
# 矩陣乘法
return tf.matmul(outputs[-1], weights['out']) + biases['out']
logits = LSTM(X, weights, biases)
prediction = tf.nn.softmax(logits)
##////////,這裏值是進行了模型的保存,這裏保存的目的是爲了進行加載並對輸入的數據進行測試,並且不需要重建整個網絡。
tf.add_to_collection('prediction',prediction)
#//////////////////////////
# 定義損失函數和優化器
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(
logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# 模型評估(with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 初始化全局變量
init = tf.global_variables_initializer()
#////新增程序//////保存數據首先創建一個對象
saver=tf.train.Saver()
#///////////////////
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
for step in range(1, training_steps+1):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Reshape data to get 28 seq of 28 elements
batch_x = batch_x.reshape((batch_size, timesteps, num_input))
# Run optimization op (backprop)
sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
if step % display_step == 0 or step == 1:
# Calculate batch loss and accuracy
loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
model_path = "./model/my_model"
save_path = saver.save(sess, model_path)
plotdata["batchsize"].append(step)
plotdata["loss"].append(loss)
#////////新增畫圖///////////
plt.plot(plotdata["batchsize"],plotdata["loss"],'b--')
plt.xlabel('minibatch number')
plt.ylabel('loss')
plt.title('Training loss')
plt.show()
#//////////////////////////
print("Optimization Finished!")
# Calculate accuracy for 128 mnist test images
test_len = 128
test_data = mnist.test.images[:test_len].reshape((-1, timesteps, num_input))
test_label = mnist.test.labels[:test_len]
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={X: test_data, Y: test_label}))
1.上述代碼需要注意的地方,如果想要多層網絡把這個註釋去掉,
# #/////////////添加多層///////////
# lstm_cell_1 = tf.contrib.rnn.BasicLSTMCell(num_units=512)
# lstm_cell_2 = tf.contrib.rnn.BasicLSTMCell(num_units=256)
# lstm_cell_3 = tf.contrib.rnn.BasicLSTMCell(num_units=128)
# lstm_cell=tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell_1,lstm_cell_2,lstm_cell_3])
#////////////////////////////////////
把lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
註釋掉即可。
2.打印在代碼中定義了存儲變量:
##//////新增打印///////////
plotdata={"batchsize":[],"loss":[]}
#///////////////////////////////
3.想要保存模型首先創建一個對象
#////新增程序//////保存數據首先創建一個對象
saver=tf.train.Saver()
#///////////////////
然後通過:
model_path = "./model/my_model"
save_path = saver.save(sess, model_path)
這兩行代碼把模型保存到當前程序所在目錄model文件夾下,名字爲my_model.
爲了在驗證階段使用模塊,程序代碼中增加了:
##////////,這裏值是進行了模型的保存,這裏保存的目的是爲了進行加載並對輸入的數據進行測試,並且不需要重建整個網絡。
tf.add_to_collection('prediction',prediction)
#//////////////////////////
現在把模型保存好了,開始用訓練完保存好的模型進行測試,建立一個LSTM_test.py,代碼如下:
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import pylab
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
n_input = 28
n_steps = 28
n_classes = 10
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('./model/my_model.meta')
new_saver.restore(sess, './model/my_model')
graph = tf.get_default_graph()
predict = tf.get_collection('prediction')[0]
input_x = graph.get_operation_by_name("input_x").outputs[0]
# im = Image.open('./MNIST_data/3.jpg')
#
# pylab.imshow(im)
# plt.show()
# im = im.convert('L')
# tv = list(im.getdata())
# tva = [(255-x)*1.0/255.0 for x in tv]
# im=np.array(im)
# im1=im.reshape((1, n_steps, n_input))
#
# print(im.shape)
#
# res = sess.run(predict, feed_dict={input_x: im1 })
# print("predict class ",str(sess.run(tf.argmax(res, 1))))
x = mnist.test.images[1].reshape((1, n_steps, n_input))
y = mnist.test.labels[1].reshape(-1, n_classes) # 轉爲one-hot形式
x1=x.reshape(-1,28)
pylab.imshow(x1)
plt.show()
res = sess.run(predict, feed_dict={input_x: x })
print("Actual class: ", str(sess.run(tf.argmax(y, 1))), \
", predict class ",str(sess.run(tf.argmax(res, 1))), \
", predict ", str(sess.run(tf.equal(tf.argmax(y, 1), tf.argmax(res, 1))))
)
下面這兩行代碼就是從保存好的模型中恢復參數:
new_saver = tf.train.import_meta_graph('./model/my_model.meta')
new_saver.restore(sess, './model/my_model')
通過下面這兩行進行計算與輸入的提取
predict = tf.get_collection('prediction')[0]
input_x = graph.get_operation_by_name("input_x").outputs[0]
下面代碼進行圖片數據處理,這裏,也可以看看輸入圖片是什麼樣子的
x = mnist.test.images[1].reshape((1, n_steps, n_input))
y = mnist.test.labels[1].reshape(-1, n_classes) # 轉爲one-hot形式
x1=x.reshape(-1,28)
pylab.imshow(x1)
plt.show()
下面這段代碼就是預測與給定比較
res = sess.run(predict, feed_dict={input_x: x })
print("Actual class: ", str(sess.run(tf.argmax(y, 1))), \
", predict class ",str(sess.run(tf.argmax(res, 1))), \
", predict ", str(sess.run(tf.equal(tf.argmax(y, 1), tf.argmax(res, 1))))
)
結果如下:
這樣結果就是預測與給定標註是符合的。