【发布时间】:2019-04-30 12:41:15
【问题描述】:
我正在尝试在 TensorFlow 2.0 中执行最基本的功能最小化,就像问题 Tensorflow 2.0: minimize a simple function 中一样,但是我无法让那里描述的解决方案起作用。这是我的尝试,主要是复制粘贴,但添加了一些似乎缺少的部分。
import tensorflow as tf
x = tf.Variable(2, name='x', trainable=True, dtype=tf.float32)
with tf.GradientTape() as t:
y = tf.math.square(x)
# Is the tape that computes the gradients!
trainable_variables = [x]
#### Option 2
# To use minimize you have to define your loss computation as a funcction
def compute_loss():
y = tf.math.square(x)
return y
opt = tf.optimizers.Adam(learning_rate=0.001)
train = opt.minimize(compute_loss, var_list=trainable_variables)
print("x:", x)
print("y:", y)
输出:
x: <tf.Variable 'x:0' shape=() dtype=float32, numpy=1.999>
y: tf.Tensor(4.0, shape=(), dtype=float32)
所以它说最小值是x=1.999,但显然这是错误的。所以发生了什么事?我想它只执行了一个最小化器循环或其他什么?如果是这样,那么“最小化”似乎是一个糟糕的函数名称。这应该如何工作?
附带说明,我还需要知道在损失函数中计算的中间变量的值(该示例只有 y,但想象一下计算 y 需要几个步骤,我想要所有这些数字)。我认为我也没有正确使用渐变带,对我来说,它与损失函数中的计算有什么关系并不明显(我只是从另一个问题中复制了这些东西)。
【问题讨论】:
标签: python tensorflow tensorflow2.0