TensorFlow 模型保存/載入
我們在上線使用一個算法模型的時候,首先必須將已經訓練好的模型保存下來。tensorflow保存模型的方式與sklearn不太一樣,sklearn很直接,一個sklearn.externals.joblib的dump與load方法就可以保存與載入使用。而tensorflow由于有graph, operation 這些概念,保存與載入模型稍顯麻煩。
一、基本方法
網上搜索tensorflow模型保存,搜到的大多是基本的方法。即
保存
定義變量 使用saver.save()方法保存載入
定義變量 使用saver.restore()方法載入如 保存 代碼如下
import tensorflow as tf import numpy as np W = tf.Variable([[1,1,1],[2,2,2]],dtype = tf.float32,name='w') b = tf.Variable([[0,1,2]],dtype = tf.float32,name='b') init = tf.initialize_all_variables() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init) save_path = saver.save(sess,"save/model.ckpt")
載入代碼如下
import tensorflow as tf import numpy as np W = tf.Variable(tf.truncated_normal(shape=(2,3)),dtype = tf.float32,name='w') b = tf.Variable(tf.truncated_normal(shape=(1,3)),dtype = tf.float32,name='b') saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess,"save/model.ckpt")
這種方法不方便的在于,在使用模型的時候,必須把模型的結構重新定義一遍,然后載入對應名字的變量的值。但是很多時候我們都更希望能夠讀取一個文件然后就直接使用模型,而不是還要把模型重新定義一遍。所以就需要使用另一種方法。
二、不需重新定義網絡結構的方法
tf.train.import_meta_graphimport_meta_graph( meta_graph_or_file, clear_devices=False, import_scope=None, **kwargs)
這個方法可以從文件中將保存的graph的所有節點加載到當前的default graph中,并返回一個saver。也就是說,我們在保存的時候,除了將變量的值保存下來,其實還有將對應graph中的各種節點保存下來,所以模型的結構也同樣被保存下來了。
比如我們想要保存計算最后預測結果的y,則應該在訓練階段將它添加到collection中。具體代碼如下
保存
### 定義模型input_x = tf.placeholder(tf.float32, shape=(None, in_dim), name='input_x')input_y = tf.placeholder(tf.float32, shape=(None, out_dim), name='input_y')w1 = tf.Variable(tf.truncated_normal([in_dim, h1_dim], stddev=0.1), name='w1')b1 = tf.Variable(tf.zeros([h1_dim]), name='b1')w2 = tf.Variable(tf.zeros([h1_dim, out_dim]), name='w2')b2 = tf.Variable(tf.zeros([out_dim]), name='b2')keep_prob = tf.placeholder(tf.float32, name='keep_prob')hidden1 = tf.nn.relu(tf.matmul(self.input_x, w1) + b1)hidden1_drop = tf.nn.dropout(hidden1, self.keep_prob)### 定義預測目標y = tf.nn.softmax(tf.matmul(hidden1_drop, w2) + b2)# 創建saversaver = tf.train.Saver(...variables...)# 假如需要保存y,以便在預測時使用tf.add_to_collection('pred_network', y)sess = tf.Session()for step in xrange(1000000): sess.run(train_op) if step % 1000 == 0: # 保存checkpoint, 同時也默認導出一個meta_graph # graph名為'my-model-{global_step}.meta'. saver.save(sess, 'my-model', global_step=step)
新聞熱點
疑難解答