tensorflow模型保存为saver = tf.train.Saver()函数,saver.save()保存模型,代码如下:
1
2
3
4
5
6
7
8
9
|
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()来加载模型,初始化变量:
1
2
3
4
5
6
7
8
9
10
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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) |
以上这篇tensorflow 加载部分变量的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u011961856/article/details/76850335