tensorflow實(shí)現(xiàn)從.ckpt文件中讀取任意變量
思路有些混亂,希望大家能理解我的意思。
看了faster rcnn的tensorflow代碼,關(guān)于fix_variables的作用我不是很明白,所以寫(xiě)了以下代碼,讀取了預(yù)訓(xùn)練模型vgg16得fc6和fc7的參數(shù),以及faster rcnn中heat_to_tail中的fc6和fc7,將它們做了對(duì)比,發(fā)現(xiàn)結(jié)果不一樣,說(shuō)明vgg16的fc6和fc7只是初始化了faster rcnn中heat_to_tail中的fc6和fc7,之后后者被訓(xùn)練。
具體讀取任意變量的代碼如下:
import tensorflow as tf
import numpy as np
from tensorflow.python import pywrap_tensorflow
file_name = '/home/dl/projectBo/tf-faster-rcnn/data/imagenet_weights/vgg16.ckpt' #.ckpt的路徑
name_variable_to_restore = 'vgg_16/fc7/weights' #要讀取權(quán)重的變量名
reader = pywrap_tensorflow.NewCheckpointReader(file_name)
var_to_shape_map = reader.get_variable_to_shape_map()
print('shape', var_to_shape_map[name_variable_to_restore]) #輸出這個(gè)變量的尺寸
fc7_conv = tf.get_variable("fc7", var_to_shape_map[name_variable_to_restore], trainable=False) # 定義接收權(quán)重的變量名
restorer_fc = tf.train.Saver({name_variable_to_restore: fc7_conv }) #定義恢復(fù)變量的對(duì)象
sess = tf.Session()
sess.run(tf.variables_initializer([fc7_conv], name='init')) #必須初始化
restorer_fc.restore(sess, file_name) #恢復(fù)變量
print(sess.run(fc7_conv)) #輸出結(jié)果
用以上的代碼分別讀取兩個(gè)網(wǎng)絡(luò)的fc6 和 fc7 ,對(duì)應(yīng)參數(shù)尺寸和權(quán)值都不同,但參數(shù)量相同。
再看lib/nets/vgg16.py中的:
(注意注釋?zhuān)?/p>
def fix_variables(self, sess, pretrained_model):
print('Fix VGG16 layers..')
with tf.variable_scope('Fix_VGG16') as scope:
with tf.device("/cpu:0"):
# fix the vgg16 issue from conv weights to fc weights
# fix RGB to BGR
fc6_conv = tf.get_variable("fc6_conv", [7, 7, 512, 4096], trainable=False)
fc7_conv = tf.get_variable("fc7_conv", [1, 1, 4096, 4096], trainable=False)
conv1_rgb = tf.get_variable("conv1_rgb", [3, 3, 3, 64], trainable=False) #定義接收權(quán)重的變量,不可被訓(xùn)練
restorer_fc = tf.train.Saver({self._scope + "/fc6/weights": fc6_conv,
self._scope + "/fc7/weights": fc7_conv,
self._scope + "/conv1/conv1_1/weights": conv1_rgb}) #定義恢復(fù)變量的對(duì)象
restorer_fc.restore(sess, pretrained_model) #恢復(fù)這些變量
sess.run(tf.assign(self._variables_to_fix[self._scope + '/fc6/weights:0'], tf.reshape(fc6_conv,
self._variables_to_fix[self._scope + '/fc6/weights:0'].get_shape())))
sess.run(tf.assign(self._variables_to_fix[self._scope + '/fc7/weights:0'], tf.reshape(fc7_conv,
self._variables_to_fix[self._scope + '/fc7/weights:0'].get_shape())))
sess.run(tf.assign(self._variables_to_fix[self._scope + '/conv1/conv1_1/weights:0'],
tf.reverse(conv1_rgb, [2]))) #將vgg16中的fc6、fc7中的權(quán)重reshape賦給faster-rcnn中的fc6、fc7
我的理解:faster rcnn的網(wǎng)絡(luò)繼承了分類(lèi)網(wǎng)絡(luò)的特征提取權(quán)重和分類(lèi)器的權(quán)重,讓網(wǎng)絡(luò)從一個(gè)比較好的起點(diǎn)開(kāi)始被訓(xùn)練,有利于訓(xùn)練結(jié)果的快速收斂。
補(bǔ)充知識(shí):TensorFlow:加載部分ckpt文件變量&不同命名空間中加載模型
TensorFlow中,在加載和保存模型時(shí),一般會(huì)直接使用tf.train.Saver.restore()和tf.train.Saver.save()
然而,當(dāng)需要選擇性加載模型參數(shù)時(shí),則需要利用pywrap_tensorflow讀取模型,分析模型內(nèi)的變量關(guān)系。
例子:Faster-RCNN中,模型加載vgg16.ckpt,需要利用pywrap_tensorflow讀取ckpt文件中的參數(shù)
from tensorflow.python import pywrap_tensorflow
model=VGG16()#此處構(gòu)建vgg16模型
variables = tf.global_variables()#獲取模型中所有變量
file_name='vgg16.ckpt'#vgg16網(wǎng)絡(luò)模型
reader = pywrap_tensorflow.NewCheckpointReader(file_name)
var_to_shape_map = reader.get_variable_to_shape_map()#獲取ckpt模型中的變量名
print(var_to_shape_map)
sess=tf.Session()
my_scope='my/'#外加的空間名
variables_to_restore={}#構(gòu)建字典:需要的變量和對(duì)應(yīng)的模型變量的映射
for v in variables:
if my_scope in v.name and v.name.split(':')[0].split(my_scope)[1] in var_to_shape_map:
print('Variables restored: %s' % v.name)
variables_to_restore[v.name.split(':0')[0][len(my_scope):]]=v
elif v.name.split(':')[0] in var_to_shape_map:
print('Variables restored: %s' % v.name)
variables_to_restore[v.name]=v
restorer=tf.train.Saver(variables_to_restore)#將需要加載的變量作為參數(shù)輸入
restorer.restore(sess, file_name)
實(shí)際中,F(xiàn)aster RCNN中所構(gòu)建的vgg16網(wǎng)絡(luò)的fc6和fc7權(quán)重shape如下:
<tf.Variable 'my/vgg_16/fc6/weights:0' shape=(25088, 4096) dtype=float32_ref>,
<tf.Variable 'my/vgg_16/fc7/weights:0' shape=(4096, 4096) dtype=float32_ref>,
vgg16.ckpt的fc6,fc7權(quán)重shape如下:
'vgg_16/fc6/weights': [7, 7, 512, 4096],
'vgg_16/fc7/weights': [1, 1, 4096, 4096],
因此,有如下操作:
fc6_conv = tf.get_variable("fc6_conv", [7, 7, 512, 4096], trainable=False)
fc7_conv = tf.get_variable("fc7_conv", [1, 1, 4096, 4096], trainable=False)
restorer_fc = tf.train.Saver({"vgg_16/fc6/weights": fc6_conv,
"vgg_16/fc7/weights": fc7_conv,
})
restorer_fc.restore(sess, pretrained_model)
sess.run(tf.assign(self._variables_to_fix['my/vgg_16/fc6/weights:0'], tf.reshape(fc6_conv,self._variables_to_fix['my/vgg_16/fc6/weights:0'].get_shape())))
sess.run(tf.assign(self._variables_to_fix['my/vgg_16/fc7/weights:0'], tf.reshape(fc7_conv,self._variables_to_fix['my/vgg_16/fc7/weights:0'].get_shape())))
以上這篇tensorflow實(shí)現(xiàn)從.ckpt文件中讀取任意變量就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
在jupyter notebook 添加 conda 環(huán)境的操作詳解
這篇文章主要介紹了在jupyter notebook 添加 conda 環(huán)境的操作詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
Python實(shí)現(xiàn)Kerberos用戶(hù)的增刪改查操作
這篇文章主要介紹了Python實(shí)現(xiàn)Kerberos用戶(hù)的增刪改查操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
windows系統(tǒng)Tensorflow2.x簡(jiǎn)單安裝記錄(圖文)
這篇文章主要介紹了windows系統(tǒng)Tensorflow2.x簡(jiǎn)單安裝記錄(圖文),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
在Linux命令行終端中使用python的簡(jiǎn)單方法(推薦)
下面小編就為大家?guī)?lái)一篇在Linux命令行終端中使用python的簡(jiǎn)單方法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01
Python網(wǎng)絡(luò)爬蟲(chóng)之獲取網(wǎng)絡(luò)數(shù)據(jù)
本文介紹了Python中用于獲取網(wǎng)絡(luò)數(shù)據(jù)的重要工具之一——Requests庫(kù),詳細(xì)講解了Requests庫(kù)的基本使用方法、請(qǐng)求方法、請(qǐng)求頭、請(qǐng)求參數(shù)、Cookies、Session等內(nèi)容,并結(jié)合實(shí)例代碼展示了Requests庫(kù)的應(yīng)用場(chǎng)景2023-04-04

