Tensorflow 模型保存和載入

来源:http://www.cnblogs.com/azheng333/archive/2017/06/09/6972619.html
-Advertisement-
Play Games

原文鏈接:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/ 什麼是tensorflow model 模型訓練完畢之後,你可能需要在產品上使用它。那麼tens ...


原文鏈接:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/

什麼是tensorflow model

模型訓練完畢之後,你可能需要在產品上使用它。那麼tensorflow model是什麼?tensorflow模型主要包含網路的結構的定義或者叫graph和訓練好的網路結構里的參數。因此tensorflow model包含2個文件

a)Meta graph:

使用protocol buffer來保存整個tensorflow graph.例如所有的variables, operations, collections等等。這個文件使用.meta尾碼

b) Checkpoint file:

二進位文件包含所有的weights,biases,gradients和其他variables的值。這個文件使用.ckpt尾碼,有2個文件:

mymodel.data-00000-of-00001
mymodel.index

.data文件就是保存訓練的variables我們將要使用它。

和這些文件一起,tensorflow還有一個文件叫checkpoint用來簡單保存最近一次保存checkpoint文件的記錄。

所以,總結起來就是 tensorflow models 對於版本0.11以上看起來是這樣:

-rw-rw-r-- 1 yyai yyai 88102292  6月  8 22:36 model.ckpt-50.data-00001-of-00002
-rw-rw-r-- 1 yyai yyai     1614  6月  8 22:36 model.ckpt-50.index
-rw-rw-r-- 1 yyai yyai  2208508  6月  8 22:36 model.ckpt-50.meta
-rw-rw-r-- 1 yyai yyai      255  6月  8 22:36 checkpoint

現在我們知道一個tensorflow model的樣子,可以看怎樣保存模型。

保存模型

假設你訓練一個捲積網路來做圖片分類。通常你可以觀察loss和accuracy值。當你觀察到網路已經收斂,你可以手動停止訓練或者你可以等到設定的epochs值跑完。 訓練完畢以後,你希望保存所有的variables和network graph以便將來使用。如果你希望保存graph和所有parameters的值,可以使用tensorflow,來創建一個tf.train.Saver()的實例 saver = tf.train.Saver()

記住tensorflow里的variables在session才存活,所有,你需要在session里保存model,使用剛剛創建的saver對象里的save 方法。

saver.save(sees, ‘my-test-model’)

這裡,sess就是session對象,’my-test-model’就是你給你的model起的名字,我們來看一個完整的樣子:

import tensorflow as tf
w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')
w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver.save(sess, 'my_test_model')

# This will save following files in Tensorflow v >= 0.11
# my_test_model.data-00000-of-00001
# my_test_model.index
# my_test_model.meta
# checkpoint

如果我們想要每1000個iteration保存一次model,可以使用save方法給他傳遞一個步長:

saver.save(sess, 'my_test_model',global_step=1000)

它將會在model名稱的後面加上’-1000’,例如下麵文件:

my_test_model-1000.index
my_test_model-1000.meta
my_test_model-1000.data-00000-of-00001
checkpoint

如果,我們每1000個iteration保存一次model,但是.meta文件只在第一次創建也就是第1000個iteration並且我們不需要每次都重新創建.meta文件。我們只需每次保存model,graph不會有變化。因此,當我們不需要寫meta-graph文件時可以這樣做:

saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)

如果我們只是想保存4個最近的model並且當訓練2小時之後想要保存一個model,我們可以使用maxtokeep和keepcheckpointeverynhours例如:

#saves a model every 2 hours and maximum 4 latest models are saved.
saver = tf.train.Saver(max_to_keep=4, keep_checkpoint_every_n_hours=2)

註意,如果我們沒有在tr.tran.Saver()的參數里指定任何值,它將會保存所有的variables。要是我們不想保存所有variables而只想保存其中的一些改怎麼辦呢。我們而已指定想要保存的variables/collections。當創建tf.train.Saver實例,我們傳遞一個想要保存的variables字典或者列表參數給它。例如:

import tensorflow as tf
w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')
w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')
saver = tf.train.Saver([w1,w2])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver.save(sess, 'my_test_model',global_step=1000)

Importing 一個 pre-trained model

如果你想使用別人的pre-trained model 來 fine-tuning, 有2件事你可以需要做:

a) 創建network:

你可以寫python代碼來創建network的每一個和每一層model,然後,想想你會發現,我們已經保存了network在.metafile里,我們可以使用tf.train.import()函數來重新創建network例如:saver = tf.train.importmetagraph('mytestmodel-1000.meta')

記住,importmetagraph 附加上了.meta文件里之前定義的network到當前的graph里。所以,這樣會為你創建graph/network,但是我們還是需要在當前的graph裡加載之前訓練好的paramters的值

b)載入parameters: 我們可以恢復network里的parameters,值需要調用saver里restore函數

with tf.Session() as sess:
  new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')
  new_saver.restore(sess, tf.train.latest_checkpoint('./‘))

然後,tensors的值 比如w1和w2就被載入了並且可以被訪問到:

with tf.Session() as sess:    
    saver = tf.train.import_meta_graph('my-model-1000.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    print(sess.run('w1:0'))
##Model has been restored. Above statement will print the saved value of w1.

4 恢復models來工作

下麵給出一個實際的列子,創建一個小的network 使用placeholders並且保存它,註意network被保存的時候,placeholders的值不會被保存:

import tensorflow as tf

#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}

#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())

#Create a saver object which will save all the variables
saver = tf.train.Saver()

#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1 

#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)

現在,當我們想要恢復model的時候, 我們不僅需要恢復graph和weights, 還需準備新的feeddict作為訓練數據給到network.我們可以。我們可以使用graph.gettensorbyname()方法 來獲取保存的operations和placeholder variables

#How to access saved variable/Tensor/placeholders 
w1 = graph.get_tensor_by_name("w1:0")

## How to access saved operation
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

如果我們只是想使用不通的數據來運行同樣的網路,可以簡單地通過feed_dict向network輸入新數據

import tensorflow as tf

sess=tf.Session()    
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))


# Now, let's access and create placeholders variables and
# create feed-dict to feed new data

graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run. 
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated 
#using new values of w1 and w2 and saved value of b1.   

如果你想要在graph里添加更多的operations來增加更多的layers然後再訓練它,你可以這樣做:

import tensorflow as tf

sess=tf.Session()    
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))


# Now, let's access and create placeholders variables and
# create feed-dict to feed new data

graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run. 
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

#Add more to the current graph
add_on_op = tf.multiply(op_to_restore,2)

print sess.run(add_on_op,feed_dict)
#This will print 120.

你也可以只使用之前訓練好的網路里的一部分內容。例如這裡,我們載入一個vgg pre-trained network 使用meta graph並且在最後一個層改變輸出的個數為2來使用新數據進行fine-tuning 

......
......
saver = tf.train.import_meta_graph('vgg.meta')
# Access the graph
graph = tf.get_default_graph()
## Prepare the feed_dict for feeding data for fine-tuning 

#Access the appropriate output for fine-tuning
fc7= graph.get_tensor_by_name('fc7:0')

#use this if you only want to change gradients of the last layer
fc7 = tf.stop_gradient(fc7) # It's an identity function
fc7_shape= fc7.get_shape().as_list()

new_outputs=2
weights = tf.Variable(tf.truncated_normal([fc7_shape[3], num_outputs], stddev=0.05))
biases = tf.Variable(tf.constant(0.05, shape=[num_outputs]))
output = tf.matmul(fc7, weights) + biases
pred = tf.nn.softmax(output)

# Now, you run this with fine-tuning data in sess.run()

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1 首先需要安裝gcc,把下載(http://redis.io/download)好的redis-3.0.0-rc2.tar.gz 放到linux /usr/local文件夾下 2 進行解壓 tar -zxvf redis-3.0.0-rc2.tar.gz 3 進入到redis-3.0.0目錄下,進 ...
  • 預處理的特點:1.效率高,執行速度快 2.安全性高,可以防止sql註入 $mysqli 中的函數 $stmt=$mysqli->prepare($sql); 預備一條sql語句,接下來要執行 綁定參數 給參數賦值 $stmt ->bind_param("類型對應",參數列表); $bool= $st ...
  • 1.系統信息函數 1.會話信息函數 ...
  • 目錄 一、視圖 二、觸發器 三、函數 四、存儲過程 五、事務 一、視圖 視圖是一個虛擬表(非真實存在),其本質是【根據SQL語句獲取動態的數據集,併為其命名】,用戶使用時只需使用【名稱】即可獲取結果集,並可以將其當作表來使用。 SELECT * FROM ( SELECT nid, NAME FRO ...
  • 在資料庫伺服器異常斷電重啟後,資料庫會進行實例恢復,那麼實例恢復的過程中Oracle做了什麼操作呢?參考官網在這裡做一下解釋,菜鳥水平有限,歡迎勘正。 首先說下實例恢復的定義: Instance recovery is the process of applying records in the o ...
  • 知識重點: 1.extract(day from schedule01::timestamp)=13 Extract 屬於 SQL 的 DML(即資料庫管理語言)函數,同樣,InterBase 也支持 Extract,它主要用於從一個日期或時間型的欄位內抽取年、月、日、時、分、秒數據,因此,它支持其 ...
  • 本文出處:http://www.cnblogs.com/wy123/p/6970721.html 免責聲明: 本文僅供娛樂,從足彩的勝平負觀點出發來分析如何投註來實現收益的“最穩妥”,^O^ 本文不對任何足彩勝平負實際投資組合有任何指導建議,不對任何投資有任何責任。 勝平負的介紹以及組合方案押註 閱 ...
  • 有些hive安裝文檔提到了hdfs dfs -mkdir ,也就是說hdfs也是可以用的,但在2.8.0中已經不那麼處理了,之所以還可以使用,是為了向下相容. 本文簡要介紹一下有關的命令,以便對hadoop的命令有一個大概的影響,併在想使用的時候能夠知道從哪裡可以獲得幫助。 概述 在$HADOOP_ ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...