一、TensorFlow的模型保存和加載,使我們在訓練和使用時的一種常用方式。我們把訓練好的模型通過二次加載訓練,或者獨立加載模型訓練。這基本上都是比較常用的方式。
二、模型的保存與加載類型有2種
1)需要重新建立圖譜,來實現模型的加載
2)獨家加載模型
模型的保存與訓練加載: tf.train.Saver(<var_list>,<max_to_keep>) var_list: 指定要保存和還原的變量,作為一個dict或者list傳遞 max_to_keep: 指示要保留的最大檢查點文件個數。 保存模型的文件:checkpoint文件/檢查點文件 method: save(<session>, <path>) restore(<session>, <path>) 模型的獨立加載: 1、tf.train.import_meta_graph(<meta_graph_or_file>) 讀取訓練時的數據流圖 meta_graph_or_file: *.meta的文件 2、saver.restore(<session>, tf.train.latest_checkpoint(<path>)) 加載最后一次檢測點 path: 含有checkpoint的上一級目錄 3、graph = tf.get_default_graph() 默認圖譜 graph.get_tensor_by_name(<name>) 獲取對應數據傳入占位符 name: tensor的那么名稱,如果沒有生命name,則為(placeholder:0), 數字0依次往后推 graph.get_collection(<name>) 獲取收集集合 return tensor列表 補充: 如果不知道怎么去獲取tensor的相關圖譜,可以通過 graph.get_operations() 查看所有的操作符,最好斷點查看
三、模型的保存與訓練加載
import os import tensorflow as tf def model_save(): # 1、准備特征值和目標值 with tf.variable_scope("data"): # 占位符,用於數據傳入 x = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x") # 矩陣相乘必須是二維(為了模擬效果而設定固定值來訓練) y_true = tf.matmul(x, [[0.7]]) + 0.8 # 2、建立回歸模型,隨機給權重值和偏置的值,讓他去計算損失,然后在當前狀態下優化 with tf.variable_scope("model"): # 模型 y = wx + b, w的個數根據特征數據而定,b隨機 # 其中Variable的參數trainable可以指定變量是否跟着梯度下降一起優化(默認True) w = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0), name="w", trainable=True) b = tf.Variable(0.0, name="b") # 預測值 y_predict = tf.matmul(x, w) + b # 3、建立損失函數,均方誤差 with tf.variable_scope("loss"): loss = tf.reduce_mean(tf.square(y_true - y_predict)) # 4、梯度下降優化損失 with tf.variable_scope("optimizer"): # 學習率的控制非常重要,如果過大會出現梯度消失/梯度爆炸導致NaN train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) # 收集需要用於預測的模型 tf.add_to_collection("y_predict", y_predict) # 定義保存模型 saver = tf.train.Saver() # 通過繪畫運行程序 with tf.Session() as sess: # 存在變量時需要初始化 sess.run(tf.global_variables_initializer()) # 加載上次訓練的模型結果 if os.path.exists("model/model/checkpoint"): saver.restore(sess, "model/model/model") # 循環訓練 for i in range(100): # 讀取數據(這里自己生成數據) x_train = sess.run(tf.random_normal([100, 1], mean=1.75, stddev=0.5, name="x")) sess.run(train_op, feed_dict={x: x_train}) # 保存模型 if (i + 1) % 10 == 0: print("第%d次訓練保存,權重:%f, 偏值:%f" % (((i + 1) / 10), w.eval(), b.eval())) saver.save(sess, "model/model/model")
四、模型的獨立加載
def model_load(): with tf.Session() as sess: # 1、加載模型 saver = tf.train.import_meta_graph("model/model/model.meta") saver.restore(sess, tf.train.latest_checkpoint("model/model")) graph = tf.get_default_graph() # 2、獲取占位符 x = graph.get_tensor_by_name("data/x:0") # 3、獲取權重和偏置 y_predict = graph.get_collection("y_predict")[0] # 4、讀取測試數據 x_test = sess.run(tf.random_normal([10, 1], mean=1.75, stddev=0.5, name="x")) # 5、預測 for i in range(len(x_test)): predict = sess.run(y_predict, feed_dict={x: [x_test[i]]}) print("第%d個數據,原值:%f, 預測值:%f" % ((i + 1), x_test[i], predict))