TensorFlow模型儲存/載入的兩種方法,tensorflow模型

來源:互聯網
上載者:User

TensorFlow模型儲存/載入的兩種方法,tensorflow模型

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)

載入

with tf.Session() as sess: new_saver = tf.train.import_meta_graph('my-save-dir/my-model-10000.meta') new_saver.restore(sess, 'my-save-dir/my-model-10000') # tf.get_collection() 返回一個list. 但是這裡只要第一個參數即可 y = tf.get_collection('pred_network')[0] graph = tf.get_default_graph() # 因為y中有placeholder,所以sess.run(y)的時候還需要用實際待預測的樣本以及相應的參數來填充這些placeholder,而這些需要通過graph的get_operation_by_name方法來擷取。 input_x = graph.get_operation_by_name('input_x').outputs[0] keep_prob = graph.get_operation_by_name('keep_prob').outputs[0] # 使用y進行預測  sess.run(y, feed_dict={input_x:...., keep_prob:1.0})

這裡有兩點需要注意的:

一、saver.restore()時填的檔案名稱,因為在saver.save的時候,每個checkpoint會儲存三個檔案,如
my-model-10000.meta, my-model-10000.index, my-model-10000.data-00000-of-00001
在import_meta_graph時填的就是meta檔案名稱,我們知道權值都儲存在my-model-10000.data-00000-of-00001這個檔案中,但是如果在restore方法中填這個檔案名稱,就會報錯,應該填的是首碼,這個首碼可以使用tf.train.latest_checkpoint(checkpoint_dir)這個方法擷取。

二、模型的y中有用到placeholder,在sess.run()的時候肯定要feed對應的資料,因此還要根據具體placeholder的名字,從graph中使用get_operation_by_name方法擷取。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.