tensorflow從ckpt和從.pb文件讀取變量的值方式
最近在學習tensorflow自帶的量化工具的相關知識,其中遇到的一個問題是從tensorflow保存好的ckpt文件或者是保存后的.pb文件(這里的pb是把權重和模型保存在一起的pb文件)讀取權重,查看量化后的權重是否變成整形。
因此將自己解決這個問題記錄下來,為了下一次遇到時,可以有所參考,也希望給有需要的同學一個可能的參考。
(1) 從保存的ckpt讀取變量的值(以讀取保存的第一個權重為例)
from tensorflow.python import pywrap_tensorflow
import tensorflow as tf
with tf.Graph().as_default():
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state('./model_ckpt') #保存ckpt文件的文件夾
if ckpt and ckpt.model_checkpoint_path:
reader = pywrap_tensorflow.NewCheckpointReader('./model_ckpt/model.ckpt-999') #自己保存的ckpt文件名
all_variables = reader.get_variable_to_shape_map()
w1 = reader.get_tensor("Variable_1")
print(w1.shape)
print(w1)
else: print('No checkpoint file found')
(2) 從保存的.pb文件讀取變量的值(以讀取保存的第一個權重為例)
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
import numpy as np
sess = tf.Session()
with gfile.FastGFile('Yourpb.pb', 'rb') as f: #自己保存的pb文件
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
print(sess.run('Variable_1:0'))
補充知識:如何從已存在的檢查點文件(cpkt文件)種解析出里面變量——無需重新創(chuàng)建原始計算圖
import tensorflow as tf
import os
CheckpointReader
tf.train.NewCheckpointReader是一個創(chuàng)建檢查點讀取器(CheckpointReader)對象的完美手段。 CheckpointReader中有幾個非常有用的方法:
get_variable_to_shape_map() - 提供具有變量名稱和形狀的字典
debug_string() - 提供由檢查點文件中所有變量組成的字符串
has_tensor(var_name) - 允許檢查變量是否存在于檢查點中
get_tensor(var_name) - 返回變量名稱的張量
為了便于說明,我將定義一個函數(shù)來檢查路徑的有效性,并為您加載檢查點讀取器。
In [3]:
def load_reader(path):
assert os.path.exists(path), "Provided incorrect path to the file. {} doesn't exist".format(path)
return tf.train.NewCheckpointReader(path)
In [34]:
your_path = 'logs/squeezeDet1024x1024/train/model.ckpt-0'
reader = load_reader(your_path)
reader.debug_string()
用于返回包含以下內容的一個字符串:
variable name(變量名)
data type(數(shù)據(jù)類型)
tensor shape(張量類型)
它返回字符串的各元素間均用空格符' '分隔,你可以使用debug_string來創(chuàng)建一個變量名列表,如下所示:
In [53]:
all_var_descriptions = reader.debug_string().split() var_names, var_shapes = all_var[::3], all_var[2::3] print(var_names[:4]) print(var_shapes[:4])
輸出:
['iou', 'fire9/squeeze1x1/kernels', 'fire9/squeeze1x1/biases', 'fire9/expand3x3/kernels/Momentum']
['[10,36864]', '[1,1,512,64]', '[64]', '[3,3,64,256]']
但是,對于完成同樣的任務,更好的方法是使用reader.get_variable_to_shape_map()
reader.get_variable_to_shape_map()
用于返回包含所有變量及其形狀名稱的字典,變量作為字典的Key,形狀作為Value。
In [66]:
saved_shapes = reader.get_variable_to_shape_map()
print('fire9/squeeze1x1/kernels:', saved_shapes['fire9/squeeze1x1/kernels'])
fire9/squeeze1x1/kernels: [1, 1, 512, 64]
reader.has_tensor(var_name)
返回bool值
這是一種方便的方法,允許您檢查ckeckpoint中是否存在相關的變量。
In [51]:
names_that_exit = {var_name: reader.has_tensor(var_name) for var_name in var_names[:10]}
for key in names_that_exit:
print(key.decode()+':', names_that_exit[key])
fire8/squeeze1x1/kernels/Momentum: True fire9/expand3x3/kernels: True iou: True fire9/expand3x3/biases: True fire9/expand1x1/kernels: True fire9/expand3x3/kernels/Momentum: True fire9/expand1x1/biases/Momentum: True fire9/squeeze1x1/biases: True fire9/expand1x1/kernels/Momentum: True fire9/squeeze1x1/kernels: True reader.get_tensor(tensor_name)
返回包含檢查點的張量值的NumPy數(shù)組
正常使用方法是先恢復一個張量,然后用恢復的張量初始化你自己的變量:
In [60]:
def recover_var(reader, var_name):
recovered_var = 'var to be recovered'
try:
recovered_var = reader.get_tensor(var_name)
except:
assert reader.has_tensor(var_name),\
"{} variable doesn't exist in the check point. Please check the variable name".format(var_name)
return recovered_var
In [67]:
checkpoint_var = recover_var(reader, 'conv1/kernels')
print ("Recovered variable has the following shape: \n", checkpoint_var.shape)
new_var = tf.Variable(initial_value=checkpoint_var, name="new_conv1")
print ("New variable will be initialized with recovered values and the following shape: \n", new_var.get_shape())
Recovered variable has the following shape: (3, 3, 3, 64) New variable will be initialized with recovered values and the following shape: (3, 3, 3, 64)
以上這篇tensorflow從ckpt和從.pb文件讀取變量的值方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python合并已經(jīng)存在的sheet數(shù)據(jù)到新sheet的方法
今天小編就為大家分享一篇python合并已經(jīng)存在的sheet數(shù)據(jù)到新sheet的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python中random.shuffle()函數(shù)用法代碼案例
random.shuffle方法,對元素進行重新排序,打亂原有的順序,返回一個隨機序列,該方法的作用類似洗牌,本文重點給大家介紹Python中random.shuffle()函數(shù)用法代碼案例,感興趣的朋友跟隨小編一起看看吧2022-11-11
Python編程實現(xiàn)二分法和牛頓迭代法求平方根代碼
這篇文章主要介紹了Python編程實現(xiàn)二分法和牛頓迭代法求平方根代碼,具有一定參考價值,需要的朋友可以了解下。2017-12-12
opencv+python實現(xiàn)鼠標點擊圖像,輸出該點的RGB和HSV值
這篇文章主要介紹了opencv+python實現(xiàn)鼠標點擊圖像,輸出該點的RGB和HSV值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密
這篇文章主要介紹了如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03
一個月入門Python爬蟲學習,輕松爬取大規(guī)模數(shù)據(jù)
利用爬蟲我們可以獲取大量的價值數(shù)據(jù),從而獲得感性認識中不能得到的信息,這篇文章給大家?guī)砹艘粋€月入門Python學習,爬蟲輕松爬取大規(guī)模數(shù)據(jù),感興趣的朋友一起看看吧2018-01-01

