tensroflow2.0 报错AttributeError: Tensor.name is meaningless when eager execution is enabled.解决

报错代码如下:

import random
import tensorflow as tf

def Z(a):
    return a*(4**2 + 4)

def Y(a, x):
    return a*(x**2 + 4)

x = tf.constant(0.0)
optimizer = tf.keras.optimizers.Adam(0.01)

for _ in range(500):
    input = random.randint(1,255)
    target = Z(input)
    with tf.GradientTape() as tape:
        pre = Y(input, x)
        loss = abs(pre - target)

    gradient = tape.gradient(loss,x)
    optimizer.apply_gradients([(gradient, x)])

    if _%100 == 0:
        print("loss:", loss.numpy())
print("x: ", x.numpy())

代码里面因为x这不是一个可训练的变量,而是一个常量, optimizer.apply_gradients([(gradient, x)])调用将引发异常。

x = tf.constant(0.0)
改为
x = tf.Variable(0.0,name = ‘var’)
即可

你可能感兴趣的:(tensorfolw2.0)