简体   繁体   English

在Tensorflow中更改变量的初始化程序

[英]Change initializer of Variable in Tensorflow

I have a predefined code that creates a Tensorflow graph. 我有一个预定义的代码来创建Tensorflow图。 The variables are contained in variable scopes and each has a predefined initializer. 变量包含在变量作用域中,每个变量都有一个预定义的初始化程序。 Is there any way to change the initializer of the variables? 有什么办法可以更改变量的初始化程序吗?

example: The first graph defines 示例:第一个图定义

with tf.variable_scope('conv1')
    w = tf.get_variable('weights')

Later on I would like to modify variable and change the initializer to Xavier: 稍后,我想修改变量并将初始值设定项更改为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))

However, when I reuse a variable, the initializer doesn't change. 但是,当我重用变量时,初始化程序不会改变。 later on when I do initialize_all_variables() I get the default values and not Xavier How can I change the initializer of a variable? 稍后,当我执行initialize_all_variables() ,将获得默认值,而不是Xavier。如何更改变量的初始化器? Thanks 谢谢

The problem is that initialization can't be changed on setting up reuse (the initialization is set during the first block). 问题是初始化不能在设置重用时更改(初始化是在第一个块中设置的)。

So, just define it with xavier intialization during the first variable scope call. 因此,只需在第一个变量作用域调用期间使用xavier初始化对其进行定义。 So the first call would be, then initialization of all variables with be correct: 因此,第一个调用将是,然后正确初始化所有变量:

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)

If you need to re-use the set of weights, the second call can get you a copy of it. 如果您需要重用这组权重,则第二次致电可以为您提供一份副本。

with tf.variable_scope(name, reuse=True) as scope:
    kernel = tf.get_variable("W")
    # you can now reuse the xavier initialized variable
    # ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM