【问题标题】:How to reuse / reopen already closed variable_scope with name_scope in Tensorflow?如何在Tensorflow中重用/重新打开已经关闭的带有name_scope的variable_scope?
【发布时间】:2018-04-02 23:15:38
【问题描述】:

我尝试使用 variable_scope 管理张量。问题是每次运行代码 sn-p 时,它都会创建一个带有索引的新张量

例如:

import tensorflow as tf
parameters = {}
with tf.variable_scope("layer1"):
    parameters["b1"] = tf.add(1,1)
with tf.variable_scope("layer1"):
    parameters["b2"] = tf.add(1,1)
print(parameters["b1"])
print(parameters["b2"])

你多次运行代码,它会创建

Tensor("layer1_1/Add:0", shape=(), dtype=int32)
Tensor("layer1_2/Add:0", shape=(), dtype=int32)

Tensor("layer1_3/Add:0", shape=(), dtype=int32)
Tensor("layer1_4/Add:0", shape=(), dtype=int32)

....

我怎样才能防止这种情况发生?

解决方案:

所以不关闭-重新打开范围将解决部分问题:

with tf.variable_scope("layer1"):
    parameters["b1"] = tf.add(1,1)
    parameters["b2"] = tf.add(1,1)

如果你想在两者之间做一些其他的事情,并且你必须关闭范围,那么你可以像这样捕获它:

with tf.variable_scope("layer1") as s: # remembering scope in s
    [ create some tensors... ]
[ scope closed ]
with tf.variable_scope( s.original_name_scope ): # reopen same name scope again
    [ declare new variables within same name scope ]

这将在两个 variable_scope 之间共享 name_scope

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    因此,根据您的评论,您的问题是您希望命名方案为 layer1/Add_1,然后是 layer1/Add_2 等。

    如果这是您的目标,那么您的代码的问题是您单独使用 with 构造。 “with”的想法是它会自动打开和关闭您使用它的对象。所以with tf.variable_scope( 'layer1' ) 创建了一个名为layer1 的变量范围,然后在您退出with 时将其关闭。然后你重新打开另一个同名的,当它尝试创建它时,它会遇到“同名”问题并开始索引后缀。

    所以不关闭-重新打开范围将解决部分问题:

    with tf.variable_scope("layer1"):
        parameters["b1"] = tf.add(1,1)
        parameters["b2"] = tf.add(1,1)
    

    如果你想在两者之间做一些其他的事情,并且你必须关闭范围,那么你可以像这样捕获它:

    with tf.variable_scope("layer1") as s: # remembering scope in s
        [ create some tensors... ]
    [ scope closed ]
    with tf.variable_scope( s.original_name_scope ): # reopen same name scope again
        [ declare new variables within same name scope ]
    

    这将在两个variable_scopes 之间共享name_scope

    张量("layer1/Add:0", shape=(), dtype=int32)

    张量("layer1/Add_1:0", shape=(), dtype=int32)

    【讨论】:

    • 它后缀是 variable_scope 而不是 tensor name (Add:0),因此使 tensorboard 可视化变得非常困难。 variable_scope 不应该像“命名空间”吗?
    • 根据您的评论重写了我的答案。我建议在原始问题中添加这个评论,也许是一个更清晰的版本,这样到达这里的人们会更容易理解它。也可以将问题标题更改为“如何在 Tensorflow 中使用 name_scope 重用/重新打开已关闭的 variable_scope?”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多