如何在急执行模式下重用tensorflow变量?

2024-10-06 13:57:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在tensorflow中调用get_variable()函数时,“重用”标志的行为在要自动重用的tensorflow api doc中定义:

reuse: True, None, or tf.AUTO_REUSE; ... When eager execution is enabled, this argument is always forced to be tf.AUTO_REUSE.

但是,当我真正按照网页上的建议运行演示代码时:

tf.enable_eager_execution()
def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v
v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2

它失败了。(如果第一行如预期的那样被删除,则通过。)

那么如何在急切模式下重用变量呢?这是虫子还是我遗漏了什么?在


Tags: 函数autogetfoois标志tftensorflow
3条回答

在渴望模式下,事情更简单。。。除了那些因为长时间使用图形模型而大脑受损的人(比如我)。在

Eager以一种标准的方式工作,变量只有在被引用时才持续。如果你停止引用它们,它们就会消失。在

为了实现变量共享,您可以做同样的事情,如果您要使用numpy(或者其他任何东西)来进行计算,您将变量存储在一个对象中,然后重用这个对象。在

这就是为什么eager与kerasapi有如此密切的关系,因为keras主要处理对象。在

所以再看看你的函数,比如numpy(对于像我这样从图中恢复的人来说很有用)。您希望对foo进行两次调用以返回相同的数组对象吗?当然不是。在

我发现在急切执行中重用变量最简单的方法是简单地传递对同一变量的引用:

import tensorflow as tf
tf.enable_eager_execution()
import numpy as np

class MyLayer(tf.keras.layers.Layer):
    def __init__(self):
        super(MyLayer, self).__init__()

    def build(self, input_shape):
        # bias specific for each layer
        self.B = self.add_variable('B', [1])

    def call(self, input, A):
        # some function involving input, common weights, and layer-specific bias
        return tf.matmul(input, A) + self.B

class MyModel(tf.keras.Model):    
    def __init__(self):
        super(MyModel, self).__init__()

    def build(self, input_shape):
        # common vector of weights
        self.A = self.add_variable('A', [int(input_shape[-1]), 1])

        # layers which will share A
        self.layer1 = MyLayer()
        self.layer2 = MyLayer()

    def call(self, input):
        result1 = self.layer1(input, self.A)
        result2 = self.layer2(input, self.A)
        return result1 + result2

if __name__ == "__main__":
    data = np.random.normal(size=(1000, 3))
    model = MyModel()
    predictions = model(data)
    print('\n\n')
    model.summary()
    print('\n\n')
    print([v.name for v in model.trainable_variables])

输出为:

enter image description here

因此,我们有一个维度3的共享权重参数my_model/A,以及维度1的两个偏差参数my_model/my_layer/B和{},总共有5个可训练参数。代码是独立运行的,所以可以随意使用它。在

tensorflow/python/ops/variable_scope.py中的文档似乎已更新。在

line 310

"reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of variables. When eager execution is enabled this argument is always forced to be False."

line 2107

"When eager execution is enabled, new variables are always created unless an EagerVariableStore or template is currently active."

相关问题 更多 >