TensorFlow——Checkpoint為模型添加檢查點(diǎn)的實(shí)例
1.檢查點(diǎn)
保存模型并不限于在訓(xùn)練模型后,在訓(xùn)練模型之中也需要保存,因?yàn)門(mén)ensorFlow訓(xùn)練模型時(shí)難免會(huì)出現(xiàn)中斷的情況,我們自然希望能夠?qū)⒂?xùn)練得到的參數(shù)保存下來(lái),否則下次又要重新訓(xùn)練。
這種在訓(xùn)練中保存模型,習(xí)慣上稱之為保存檢查點(diǎn)。
2.添加保存點(diǎn)
通過(guò)添加檢查點(diǎn),可以生成載入檢查點(diǎn)文件,并能夠指定生成檢查文件的個(gè)數(shù),例如使用saver的另一個(gè)參數(shù)——max_to_keep=1,表明最多只保存一個(gè)檢查點(diǎn)文件,在保存時(shí)使用如下的代碼傳入迭代次數(shù)。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
train_x = np.linspace(-5, 3, 50)
train_y = train_x * 5 + 10 + np.random.random(50) * 10 - 5
plt.plot(train_x, train_y, 'r.')
plt.grid(True)
plt.show()
tf.reset_default_graph()
X = tf.placeholder(dtype=tf.float32)
Y = tf.placeholder(dtype=tf.float32)
w = tf.Variable(tf.random.truncated_normal([1]), name='Weight')
b = tf.Variable(tf.random.truncated_normal([1]), name='bias')
z = tf.multiply(X, w) + b
cost = tf.reduce_mean(tf.square(Y - z))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
training_epochs = 20
display_step = 2
saver = tf.train.Saver(max_to_keep=15)
savedir = "model/"
if __name__ == '__main__':
with tf.Session() as sess:
sess.run(init)
loss_list = []
for epoch in range(training_epochs):
for (x, y) in zip(train_x, train_y):
sess.run(optimizer, feed_dict={X: x, Y: y})
if epoch % display_step == 0:
loss = sess.run(cost, feed_dict={X: x, Y: y})
loss_list.append(loss)
print('Iter: ', epoch, ' Loss: ', loss)
w_, b_ = sess.run([w, b], feed_dict={X: x, Y: y})
saver.save(sess, savedir + "linear.cpkt", global_step=epoch)
print(" Finished ")
print("W: ", w_, " b: ", b_, " loss: ", loss)
plt.plot(train_x, train_x * w_ + b_, 'g-', train_x, train_y, 'r.')
plt.grid(True)
plt.show()
load_epoch = 10
with tf.Session() as sess2:
sess2.run(tf.global_variables_initializer())
saver.restore(sess2, savedir + "linear.cpkt-" + str(load_epoch))
print(sess2.run([w, b], feed_dict={X: train_x, Y: train_y}))
在上述的代碼中,我們使用saver.save(sess, savedir + "linear.cpkt", global_step=epoch)將訓(xùn)練的參數(shù)傳入檢查點(diǎn)進(jìn)行保存,saver = tf.train.Saver(max_to_keep=1)表示只保存一個(gè)文件,這樣在訓(xùn)練過(guò)程中得到的新的模型就會(huì)覆蓋以前的模型。
cpkt = tf.train.get_checkpoint_state(savedir) if cpkt and cpkt.model_checkpoint_path: saver.restore(sess2, cpkt.model_checkpoint_path) kpt = tf.train.latest_checkpoint(savedir) saver.restore(sess2, kpt)
上述的兩種方法也可以對(duì)checkpoint文件進(jìn)行加載,tf.train.latest_checkpoint(savedir)為加載最后的檢查點(diǎn)文件。這種方式,我們可以通過(guò)保存指定訓(xùn)練次數(shù)的檢查點(diǎn),比如保存5的倍數(shù)次保存一下檢查點(diǎn)。
3.簡(jiǎn)便保存檢查點(diǎn)
我們還可以用更加簡(jiǎn)單的方法進(jìn)行檢查點(diǎn)的保存,tf.train.MonitoredTrainingSession()函數(shù),該函數(shù)可以直接實(shí)現(xiàn)保存載入檢查點(diǎn)模型的文件,與前面的方法不同的是,它是按照訓(xùn)練時(shí)間來(lái)保存檢查點(diǎn)的,可以通過(guò)指定save_checkpoint_secs參數(shù)的具體秒數(shù),設(shè)置多久保存一次檢查點(diǎn)。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
train_x = np.linspace(-5, 3, 50)
train_y = train_x * 5 + 10 + np.random.random(50) * 10 - 5
# plt.plot(train_x, train_y, 'r.')
# plt.grid(True)
# plt.show()
tf.reset_default_graph()
X = tf.placeholder(dtype=tf.float32)
Y = tf.placeholder(dtype=tf.float32)
w = tf.Variable(tf.random.truncated_normal([1]), name='Weight')
b = tf.Variable(tf.random.truncated_normal([1]), name='bias')
z = tf.multiply(X, w) + b
cost = tf.reduce_mean(tf.square(Y - z))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
training_epochs = 30
display_step = 2
global_step = tf.train.get_or_create_global_step()
step = tf.assign_add(global_step, 1)
saver = tf.train.Saver()
savedir = "check-point/"
if __name__ == '__main__':
with tf.train.MonitoredTrainingSession(checkpoint_dir=savedir + 'linear.cpkt', save_checkpoint_secs=5) as sess:
sess.run(init)
loss_list = []
for epoch in range(training_epochs):
sess.run(global_step)
for (x, y) in zip(train_x, train_y):
sess.run(optimizer, feed_dict={X: x, Y: y})
if epoch % display_step == 0:
loss = sess.run(cost, feed_dict={X: x, Y: y})
loss_list.append(loss)
print('Iter: ', epoch, ' Loss: ', loss)
w_, b_ = sess.run([w, b], feed_dict={X: x, Y: y})
sess.run(step)
print(" Finished ")
print("W: ", w_, " b: ", b_, " loss: ", loss)
plt.plot(train_x, train_x * w_ + b_, 'g-', train_x, train_y, 'r.')
plt.grid(True)
plt.show()
load_epoch = 10
with tf.Session() as sess2:
sess2.run(tf.global_variables_initializer())
# saver.restore(sess2, savedir + 'linear.cpkt-' + str(load_epoch))
# cpkt = tf.train.get_checkpoint_state(savedir)
# if cpkt and cpkt.model_checkpoint_path:
# saver.restore(sess2, cpkt.model_checkpoint_path)
#
kpt = tf.train.latest_checkpoint(savedir + 'linear.cpkt')
saver.restore(sess2, kpt)
print(sess2.run([w, b], feed_dict={X: train_x, Y: train_y}))
上述的代碼中,我們?cè)O(shè)置了沒(méi)訓(xùn)練了5秒中之后,就保存一次檢查點(diǎn),它默認(rèn)的保存時(shí)間間隔是10分鐘,這種按照時(shí)間的保存模式更適合使用大型數(shù)據(jù)集訓(xùn)練復(fù)雜模型的情況,注意在使用上述的方法時(shí),要定義global_step變量,在訓(xùn)練完一個(gè)批次或者一個(gè)樣本之后,要將其進(jìn)行加1的操作,否則將會(huì)報(bào)錯(cuò)。

以上這篇TensorFlow——Checkpoint為模型添加檢查點(diǎn)的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python socket實(shí)現(xiàn)的文件下載器功能示例
這篇文章主要介紹了Python socket實(shí)現(xiàn)的文件下載器功能,結(jié)合實(shí)例形式分析了Python使用socket模塊實(shí)現(xiàn)的文件下載器客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
淺談selenium如何應(yīng)對(duì)網(wǎng)頁(yè)內(nèi)容需要鼠標(biāo)滾動(dòng)加載的問(wèn)題
這篇文章主要介紹了淺談selenium如何應(yīng)對(duì)網(wǎng)頁(yè)內(nèi)容需要鼠標(biāo)滾動(dòng)加載的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例
今天小編就為大家分享一篇python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
Python調(diào)用olmOCR大模型實(shí)現(xiàn)提取復(fù)雜PDF文件內(nèi)容
olmocr是由Allen人工智能研究所(AI2)開(kāi)發(fā)的一個(gè)開(kāi)源工具包,旨在高效地將PDF和其他文檔轉(zhuǎn)換為結(jié)構(gòu)化的純文本,同時(shí)保持自然閱讀順序,下面我們來(lái)看看如何使用olmOCR大模型實(shí)現(xiàn)提取復(fù)雜PDF文件內(nèi)容吧2025-03-03
解決python xlrd無(wú)法讀取excel文件的問(wèn)題
今天小編就為大家分享一篇解決python xlrd無(wú)法讀取excel文件的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
Appium+python自動(dòng)化之連接模擬器并啟動(dòng)淘寶APP(超詳解)
這篇文章主要介紹了Appium+python自動(dòng)化之 連接模擬器并啟動(dòng)淘寶APP(超詳解)本文以淘寶app為例,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2019-06-06

