tensorflow 加载部分变量的实例讲解
tensorflow模型保存为saver = tf.train.Saver()函数,saver.save()保存模型,代码如下:
import tensorflow as tf v1= tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="v1") v2= tf.Variable(tf.zeros([200]), name="v2") saver = tf.train.Saver() with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) saver.save(sess,"checkpoint/model_test",global_step=1)
当我们保存模型后,我们可以通过saver.restore()来加载模型,初始化变量:
import tensorflow as tf v1= tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="v1") v2= tf.Variable(tf.zeros([200]), name="v2") saver = tf.train.Saver() with tf.Session() as sess: # init_op = tf.global_variables_initializer() # sess.run(init_op) saver.restore(sess, "checkpoint/model_test-1") # saver.save(sess,"checkpoint/model_test",global_step=1)
神经网络训练时,有时候我们需要从预训练的模型中加载部分参数,初始化当前模型,例如加入CNN有6层,我们需要从已有的模型初始化CNN前5层参数.这可以通过saver.restore()实现.
之前我们已经介绍可以通过tf.train.Saver()的保存部分变量的方法,即需要保存的变量列表,同样的,在变量初始化的时候,我们可以对需要单独初始化的变量分别定义一个tf.train.Saver()函数,这样就可以单独对该部分变量初始化,例如下面代码,saver1用于初始化变量v1,saver2用于初始化变量v2,v3:
import tensorflow as tf v1= tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="v1") v2= tf.Variable(tf.zeros([200]), name="v2") v3= tf.Variable(tf.zeros([100]), name="v3") #saver = tf.train.Saver() saver1 = tf.train.Saver([v1]) saver2 = tf.train.Saver([v2]+[v3]) with tf.Session() as sess: # init_op = tf.global_variables_initializer() # sess.run(init_op) saver1.restore(sess, "checkpoint/model_test-1") saver2.restore(sess, "checkpoint/model_test-1") # saver.save(sess,"checkpoint/model_test",global_step=1)
相关推荐
源式羽语 2020-08-09
Micusd 2020-11-19
xjtukuixing 2020-10-27
lybbb 2020-10-15
lybbb 2020-09-29
ghjk0 2020-09-24
yamaxifeng 2020-09-09
GDGYZL 2020-08-28
lybbb 2020-08-28
Icevivian 2020-08-25
comwayLi 2020-08-16
carbon0 2020-08-16
sherry颖 2020-08-01
songbinxu 2020-07-19
sherry颖 2020-07-18
Niteowl 2020-07-15
Kindle君 2020-07-15
源式羽语 2020-07-04
源式羽语 2020-06-28