报错代码如下:
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’)
即可