Tensorflow 函数不会改变属性的属性

Posted

技术标签:

【中文标题】Tensorflow 函数不会改变属性的属性【英文标题】:Tensorflow function doesn't change attribute's attribute 【发布时间】:2022-01-06 05:27:45 【问题描述】:

Tf 函数不会改变对象的属性

class f:
    v = 7
    def __call__(self):
        self.v = self.v + 1

@tf.function
def call(c):
    tf.print(c.v)  # always 7
    c()
    tf.print(c.v)  # always 8

c = f()
call(c)
call(c)

预期打印: 7 8 8 9

而是: 7 8 7 8

当我删除 @tf.function 装饰器时,一切都按预期工作。如何使用@tf.function 使我的函数按预期工作

【问题讨论】:

【参考方案1】:

此行为记录在 here:

副作用,如打印、附加到列表和改变全局变量,可能会在函数内部出现意外行为,有时会执行两次或不全部执行。它们仅在您第一次使用一组输入调用函数时发生。之后,跟踪的 tf.Graph 被重新执行,而不执行 Python 代码。一般的经验法则是避免在逻辑中依赖 Python 副作用,只使用它们来调试跟踪。否则,tf.data、tf.print、tf.summary、tf.Variable.assign 和 tf.TensorArray 等 TensorFlow API 是确保每次调用都由 TensorFlow 运行时执行代码的最佳方式。

所以,也许可以尝试使用tf.Variable 来查看预期的变化:

import tensorflow as tf
class f:
    v = tf.Variable(7)
    def __call__(self):
      self.v.assign_add(1)

@tf.function
def call(c):
    tf.print(c.v)  # always 7
    c()
    tf.print(c.v)  # always 8

c = f()
call(c)
call(c)
7
8
8
9

【讨论】:

有效!非常感谢!

以上是关于Tensorflow 函数不会改变属性的属性的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError:模块“tensorflow_core.keras.layers.experimental.preprocessing”没有属性“RandomFlip”

TestContext.TestName 属性永远不会改变

ten 特殊集合与函数

vue为啥method值不改

优化器类中 tensorflow 最小化()函数中的“gate_gradients”属性是啥?

AttributeError:“Tensor”对象在自定义损失函数中没有属性“numpy”(Tensorflow 2.1.0)