我有一个预定义的代码,可以创建Tensorflow图.变量包含在变量范围中,每个变量都有一个预定义的初始化程序.有没有办法改变变量的初始化器?
示例:第一个图定义
with tf.variable_scope('conv1')
w = tf.get_variable('weights')
Run Code Online (Sandbox Code Playgroud)
稍后我想修改变量并将初始化程序更改为Xavier:
with tf.variable_scope('conv1')
tf.get_variable_scope().reuse_variable()
w = tf.get_variable('weights',initializer=tf.contrib.layers.xavier_initializer(uniform=False))
Run Code Online (Sandbox Code Playgroud)
但是,当我重用变量时,初始化程序不会更改.稍后当我这样做时,initialize_all_variables()
我得到默认值而不是Xavier如何更改变量的初始值设定项?谢谢
问题是在设置重用时无法更改初始化(初始化是在第一个块期间设置的)。
因此,只需在第一个变量作用域调用期间使用 xavier 初始化来定义它即可。因此,第一个调用将是,然后所有变量的初始化都是正确的:
with tf.variable_scope(name) as scope:
kernel = tf.get_variable("W",
shape=kernel_shape, initializer=tf.contrib.layers.xavier_initializer_conv2d())
# you could also just define your network layer 'now' using this kernel
# ....
# Which would need give you a model (rather just weights)
Run Code Online (Sandbox Code Playgroud)
如果您需要重新使用该组权重,第二次调用可以为您获取它的副本。
with tf.variable_scope(name, reuse=True) as scope:
kernel = tf.get_variable("W")
# you can now reuse the xavier initialized variable
# ....
Run Code Online (Sandbox Code Playgroud)