1. 程式人生 > >tensorflow 選擇性fine-tune(微調)

tensorflow 選擇性fine-tune(微調)

'''
多種選擇fine-tune部分權重的方法

Multiple selection load weights for fine-tune

注:slim的fine-tune 適用slim模組conv bn(儘量一致對應模組)

第一種沒有試驗過:個人理解:可以不用管 不需要fine-tune的權重 直接tf.global_variables_initializer即可 (slim模組就是這樣實驗的)

'''
import tensorflow as tf
from tensorflow.contrib import slim

model_path=r'**/model.ckpt'

# 1
sess=tf.Session()
var = tf.global_variables() # all weights' name dict
var_to_restore = [val  for val in var if 'conv1' in val.name or 'conv2'in val.name] # select which to fine-tune
saver = tf.train.Saver(var_to_restore)
saver.restore(sess, model_path)# fine-tune those weights (names must be same)
var_to_init = [val  for val in var if 'conv1' not in val.name or 'conv2'not in val.name] # need to init
tf.variables_initializer(var_to_init)
# when save model ,need to create a new saver

# 2

sess=tf.Session()
exclude = ['conv1', 'conv2'] # need write the actual name
variables_to_restore = slim.get_variables_to_restore(exclude=exclude)
saver = tf.train.Saver(variables_to_restore)
saver.restore(sess, model_path)
# when save model ,need to create a new saver

# 3
exclude = ['weight1','weight2']
variables_to_restore = slim.get_variables_to_restore(exclude=exclude)
init_fn = slim.assign_from_checkpoint_fn(model_path, variables_to_restore)

init_fn(sess)
具體實現程式碼: https://blog.csdn.net/leilei18a/article/details/80189917

'''
個人見解: 如果是要fine-tune前面連續的層權重,可以先建立網路,然後在需要fine-tune層
最後位置新增init_fn = slim.assign_from_checkpoint_fn(model_path, slim.get_model_variables('model_name')) # model_name: eg resnet_v2_152
然後,在tf.global_variables_initializer 執行後,新增init_fn(sess),即: 只fine-tune
前面某些層權重。【當然也可以在最後弄,選擇載入即可其他的自動會init】
別人點醒我:init_fn在網路哪個位置,此位置之前會自動從get_model_variables中提取相同名字的
權重。(儘量名字一致)
'''