首页 > 解决方案 > Tensorflow 2.0: AttributeError: Tensor.name 在启用 Eager Execution 时毫无意义

问题描述

使用 tensorflow 2.0 不断出现这些错误。这应该工作吗?

import tensorflow as tf
import numpy as np

x = tf.constant(3.0)
with tf.GradientTape() as t:
    t.watch(x)
    y = (x - 10) ** 2
    opt = tf.optimizers.Adam()
    opt.minimize(lambda: y, var_list=[x])

标签: tensorflow2.0

解决方案


在磁带中,您只需要计算优化器的正向传递,并且最小化定义不是正向传递的一部分,因此您必须远程处理它们。

而且,如果你想使用minimize优化器的方法,你不必使用tf.GradienTape对象,而只需将前向传递(损失计算)定义为一个函数,那么优化器将为你创建磁带+最小化函数.

但是,由于您想使用常量而不是变量,因此您必须使用 atf.GradientTape并手动计算损失值。

import tensorflow as tf

x = tf.constant(3.0)
with tf.GradientTape() as t:
    t.watch(x)
    y = (x - 10) ** 2
grads = t.gradient(y, [x])

当然你不能应用渐变

opt = tf.optimizers.Adam()
opt.apply_gradients(zip([y], [x]))

since x is not a trainable variable, but a constant (the apply_gradients call will raise an exception)


推荐阅读