TensorFlow - tf.VariableScope 和 tf.variable_scope 之间的区别

TensorFlow - Difference between tf.VariableScope and tf.variable_scope

在 TensorFlow 网站上找到两个指向 variable scope 的链接,一个是 tf.variable_scope which is the one most commonly used, and the other 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)

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

由于作用域要先压栈(tensorflow内部class_VariableStore负责),然后从栈中弹出,手动实例化tf.VariableScope 乏味且容易出错。这就是上下文管理器的用武之地。

tf.variable_scope 是一个上下文管理器,可以更轻松地使用变量范围。如文档所述:

A context manager for defining ops that creates variables (layers).

This context manager validates that the (optional) values are from the same graph, ensures that graph is the default graph, and pushes a name scope and a variable scope.

实际使用变量的工作委托给在幕后创建的 tf.VariableScope 对象。