Tensorflow 变量范围:如果变量存在则重用 [英] Tensorflow variable scope: reuse if variable exists

查看:23
本文介绍了Tensorflow 变量范围:如果变量存在则重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一段代码,如果变量不存在,它会在一个范围内创建一个变量,如果它已经存在,则访问该变量.我需要它是 相同 代码,因为它将被多次调用.

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 code since it will be called multiple times.

但是,Tensorflow 需要我指定是要创建还是重用变量,如下所示:

However, Tensorflow needs me to specify whether I want to create or reuse the variable, like this:

with tf.variable_scope("foo"): #create the first time
    v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True): #reuse the second time
    v = tf.get_variable("v", [1])

我怎样才能让它确定是自动创建还是重用它?即,我希望上述两个代码块 相同 并运行程序.

How can I get it to figure out whether to create or reuse it automatically? I.e., I want the above two blocks of code to be the same and have the program run.

推荐答案

get_variable() 中引发 ValueError 在创建新变量且未声明形状时,或者在变量创建期间违反重用时.因此,你可以试试这个:

A ValueError is raised in get_variable() when creating a new variable and shape is not declared, or when violating reuse during variable creation. Therefore, you can try this:

def get_scope_variable(scope_name, var, shape=None):
    with tf.variable_scope(scope_name) as scope:
        try:
            v = tf.get_variable(var, shape)
        except ValueError:
            scope.reuse_variables()
            v = tf.get_variable(var)
    return v

v1 = get_scope_variable('foo', 'v', [1])
v2 = get_scope_variable('foo', 'v')
assert v1 == v2

请注意以下内容也有效:

Note that the following also works:

v1 = get_scope_variable('foo', 'v', [1])
v2 = get_scope_variable('foo', 'v', [1])
assert v1 == v2

<小时>

更新.新的 API 现在支持自动重用:


UPDATE. The new API supports auto-reusing now:

def get_scope_variable(scope, var, shape=None):
    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
        v = tf.get_variable(var, shape)
    return v

这篇关于Tensorflow 变量范围:如果变量存在则重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆