Tensorflow 2.0中的基本功能最小化和可变跟踪



我试图在Tensorflow 2.0中执行最小化最小的功能,就像问题Tensorflow 2.0:最小化简单功能一样,但是我无法在其中描述的解决方案来工作。这是我的尝试,主要是复制的,但似乎添加了一些位。

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的几个步骤,我想要所有这些数字(。我认为我也不正确地使用渐变胶带,对我而言,这与损失功能中的计算有任何关系(我只是从另一个问题中复制了这些东西(。

<(。

您需要多次调用minimize,因为minimize仅执行优化的一个步骤。

以下应该有效

import tensorflow as tf
x = tf.Variable(2, name='x', trainable=True, dtype=tf.float32)
# Is the tape that computes the gradients!
trainable_variables = [x]
# To use minimize you have to define your loss computation as a funcction
class Model():
    def __init__(self):
        self.y = 0
    def compute_loss(self):
        self.y = tf.math.square(x)
        return self.y
opt = tf.optimizers.Adam(learning_rate=0.01)
model = Model()
for i in range(1000):
    train = opt.minimize(model.compute_loss, var_list=trainable_variables)
print("x:", x)
print("y:", model.y)

最新更新