Tensorflow variable scope: reuse if variable exists

后端 未结 4 396
醉酒成梦
醉酒成梦 2020-12-02 15:17

I want a piece of code that creates a variable within a scope if it doesn\'t exist, and access the variable if it already exists. I need it to be the same c

4条回答
  •  旧巷少年郎
    2020-12-02 15:59

    New AUTO_REUSE option does the trick.

    From the tf.variable_scope API docs: if reuse=tf.AUTO_REUSE, we create variables if they do not exist, and return them otherwise.

    Basic example of sharing a variable AUTO_REUSE:

    def foo():
      with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
        v = tf.get_variable("v", [1])
      return v
    
    v1 = foo()  # Creates v.
    v2 = foo()  # Gets the same, existing v.
    assert v1 == v2
    

提交回复
热议问题