Tensorflow 变量范围:如果变量存在则重用

编程入门 行业动态 更新时间:2024-10-26 04:24:05
本文介绍了Tensorflow 变量范围:如果变量存在则重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 05:25:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Tensorflow

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!