【发布时间】:2019-03-12 12:02:58
【问题描述】:
我的目标是通过首先训练权重的子集顺序训练网络 然后训练 所有 权重。考虑给定的两种架构 here 首先从“网络 1”开始,它由一个输入标量 z_1、2 个分别具有权重 (w_11, w_21) 和偏差 (b_1, b_2) 的节点组成。 “网络 2”通过添加一个输入节点 (z_2) 扩展了“网络 1”,因此也为每个节点添加了一个标量权重 (w_12, w_22)。在“Network 2”中,(w_11, w_21) 和 (b_1, b_2) 由“Network 1”的训练结果初始化,而 (w_12, w_22) 以其他方式初始化。
我知道如何保存和恢复权重子集(参见here 和here)。但是,链接中描述的方法在使用像tf.layers.dense(...) 这样的全连接层时不起作用,它仅在恢复由tf.Variable(...) 实例化的变量子集时才起作用。我可能需要为此编写一个自定义层,但我不确定。 如何实现我的目标?
为了给出一些上下文,下面的脚本保存了“Network 1”
import tensorflow as tf
import numpy as np
def generator(Z,reuse=False):
with tf.variable_scope("restore"):
h1 = tf.layers.dense(Z,2,activation=tf.nn.leaky_relu, name='h1')
return h1
Z = tf.placeholder(tf.float32,[None,1])
G_sample = generator(Z)
Z_batch = np.random.uniform(-1., 1., size=[1, 1])
saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope="restore")
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
saver.save(sess, 'test')
print('restore/h1/bias:0 :', sess.run(tf.get_default_graph().get_tensor_by_name("restore/h1/bias:0")))
print('restore/h1/kernel:0 :', sess.run(tf.get_default_graph().get_tensor_by_name("restore/h1/kernel:0")))
这给出了输出
restore/h1/bias:0 : [0. 0.]
restore/h1/kernel:0 : [[-0.7695515 1.2254907]]
下面的脚本从上面的脚本中恢复图形,并用两个权重扩展它。 注意:当 z_dim = 1 时,代码运行良好(它只是恢复与之前相同的图形),但当 z_dim = 2 时,它显然会失败,因为它不知道要在层中恢复什么权重“ h1"。
import tensorflow as tf
import numpy as np
def generator(Z,reuse=False):
with tf.variable_scope("restore"):
h1 = tf.layers.dense(Z,2,activation=tf.nn.leaky_relu, name='h1')
return h1
Z = tf.placeholder(tf.float32,[None,2])
G_sample = generator(Z)
z_dim = 2
Z_batch = np.random.uniform(-1., 1., size=[1, z_dim])
reader = tf.train.NewCheckpointReader('../test/modeltest')
restore_dict = dict()
for v in tf.trainable_variables():
tensor_name = v.name.split(':')[0]
if reader.has_tensor(tensor_name):
print('has tensor ', tensor_name)
restore_dict[tensor_name] = v
print('restore_dict:', restore_dict)
init_op = tf.global_variables_initializer()
saver = tf.train.Saver(restore_dict)
with tf.Session() as sess:
sess.run(init_op)
saver.restore(sess, 'test')
print('restore/h1/bias:0 :',sess.run(tf.get_default_graph().get_tensor_by_name("restore/h1/bias:0")))
print('restore/h1/kernel:0 :',sess.run(tf.get_default_graph().get_tensor_by_name("restore/h1/kernel:0")))
非常感谢您的意见。谢谢。
【问题讨论】:
-
欢迎来到 SO。考虑到您的目标,您是否尝试过仅将所需的变量传递给优化器?
-
感谢您的意见。在这个阶段,我不需要考虑优化,因为我只是对将全连接层权重的子集从“网络 1”转移到“网络 2”感兴趣。
标签: python tensorflow