tensorflow之inception_v3模型的部分載入及權重的部分恢復(23)---《深度學習》
阿新 • • 發佈:2018-12-31
大家都知道,在載入模型及對應的權重進行訓練的時候,我們可以整個使用所提供的模型,但是有時候呢?所提供的模型不能很好的滿足我們的要求,有時候我們只需要模型的前幾層然後進行對應的權重賦值,這時候,我們應該怎麼辦呢?tensorflow為我們提供了兩種方法(探索了好久才找到解決辦法,不過感覺蠻有用的,分享給大家啦!):
1)在載入模型的時候,使用final_endpoint引數,指定模型階段點:
import tensorflow.contrib.slim.nets as nets
#from tensorflow.contrib.slim.nets.inception import inception_v3, inception_v3_arg_scope
import numpy as np
import os
height = 299
width = 299
channels = 3
num_classes=1001
X = tf.placeholder(tf.float32, shape=[None, height, width, channels])
y = tf.placeholder(tf.float32,shape=[None,182])
with slim.arg_scope(nets.inception.inception_v3_arg_scope()):
logits, end_points = nets.inception .inception_v3_base(X,final_endpoint = "Mixed_7a")
variables_to_restore=slim.get_variables_to_restore()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver=tf.train.Saver(variables_to_restore)
saver.restore(sess,os.path.join("E:\\","inception_v3.ckpt"))
print("Done" )
2)在恢復模型的時候,部分層不使用ckpt檔案中提供的引數:
#-*-coding=utf-8-*-
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
#from tensorflow.contrib.slim.nets.inception import inception_v3, inception_v3_arg_scope
import numpy as np
import os
height = 299
width = 299
channels = 3
num_classes=1001
X = tf.placeholder(tf.float32, shape=[None, height, width, channels])
y = tf.placeholder(tf.float32,shape=[None,182])
with slim.arg_scope(nets.inception.inception_v3_arg_scope()):
logits, end_points = nets.inception.inception_v3(X, num_classes=num_classes,is_training=False)
with tf.Session() as sess:
exclude=['Mixed_7c','Mixed_7b','AuxLogits','AuxLogits','Logits','Predictions']
variables_to_restore=slim.get_variables_to_restore(exclude=exclude)
sess.run(tf.global_variables_initializer())
saver=tf.train.Saver(variables_to_restore)
saver.restore(sess,os.path.join("E:\\","inception_v3.ckpt"))
print("Done")