我有一个预定义的代码可以创建一个 Tensorflow 图。变量包含在变量作用域中,每个变量都有一个预定义的初始值设定项。 有什么办法可以改变变量的初始值设定项吗?
例子: 第一张图定义
with tf.variable_scope('conv1')
w = tf.get_variable('weights')
稍后我想修改变量并将初始值设定项更改为 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))
然而,当我重用一个变量时,初始化器并没有改变。
稍后当我执行 initialize_all_variables()
时,我得到默认值而不是 Xavier
如何更改变量的初始值设定项?
谢谢
最佳答案
问题是在设置重用时无法更改初始化(初始化是在第一个 block 中设置的)。
因此,只需在第一次变量范围调用期间使用 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)
如果您需要重新使用这组权重,第二次调用可以获得它的副本。
with tf.variable_scope(name, reuse=True) as scope:
kernel = tf.get_variable("W")
# you can now reuse the xavier initialized variable
# ....
关于python - 在 Tensorflow 中更改变量的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37992326/