使用 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])
使用 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])
在磁带中,您只需要计算优化器的正向传递,并且最小化定义不是正向传递的一部分,因此您必须远程处理它们。
而且,如果你想使用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)