TensorFlow - tf.VariableScope和tf.variable_scope之间的差异

时间:2017-11-13 05:04:51

标签: python tensorflow contextmanager

在TensorFlow网站上找到了两个指向variable scope的链接,一个是tf.variable_scope,这是最常用的一个,另一个是tf.VaribleScope

由于tf.VariableScope的应用没有任何示例,只是阅读文档,我无法区分两者之间是否存在差异。试图通过将tf.variable_scope替换为tf.VariableScope来实施,但却出现以下错误(表明存在一些差异)

Traceback (most recent call last):
  File "/home/NER/window_model.py", line 105, in <module>
    model = NaiveNERModel(embeddings)
  File "/home/NER/window_model.py", line 64, in __init__
    pred = self.add_prediction_op(embed)
  File "/home/NER/window_model.py", line 82, in add_prediction_op
    with tf.VariableScope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
AttributeError: __enter__

原始可行代码的片段

with tf.variable_scope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
        W = tf.get_variable("W", [self.dim * self.window_size, self.dim * self.window_size])
        b1 = tf.get_variable("b1", [self.dim * self.window_size])
        h = tf.nn.relu(tf.matmul(embed, W) + b1)

1 个答案:

答案 0 :(得分:1)

tf.VariableScope是一个实际的范围类,它包含nameinitializerregularizerpartitioner以及传播到变量的许多其他属性在该范围内定义。此类更多是属性集合而不是上下文管理器,因此您无法在with语句中使用它(这是错误告诉您的内容)。

由于范围必须首先被推到堆栈顶部(tensorflow内部类_VariableStore负责这个),然后从堆栈弹回,tf.VariableScope的手动实例化是单调乏味的错误-易于。那就是上下文管理器的用武之地。

tf.variable_scope是一个上下文管理器,可以更轻松地使用变量作用域。正如文档所描述的那样:

  

用于定义创建变量(层)的操作的上下文管理器。

     

此上下文管理器验证(可选)值来自同一图表,确保图形是默认图形,并推送名称范围和变量范围。

将变量的实际工作委托给在引擎盖下创建的tf.VariableScope对象。