使用 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])
Run Code Online (Sandbox Code Playgroud)
在磁带中,您只需要计算前向传递,优化器和最小化定义不是前向传递的一部分,因此您必须远程处理它们。
而且,如果你想使用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])
Run Code Online (Sandbox Code Playgroud)
当然你不能应用渐变
opt = tf.optimizers.Adam()
opt.apply_gradients(zip([y], [x]))
Run Code Online (Sandbox Code Playgroud)
因为x不是一个可训练的变量,而是一个常量(apply_gradients调用将引发异常)
| 归档时间: |
|
| 查看次数: |
5709 次 |
| 最近记录: |