【问题标题】:Basic function minimisation and variable tracking in TensorFlow 2.0TensorFlow 2.0 中的基本函数最小化和变量跟踪
【发布时间】: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


    【解决方案1】:

    您需要多次调用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)
    
    

    【讨论】:

    • 好的,如果我提高学习率,我可以让它工作,但是我得到“NameError:name 'y' is not defined”。
    • 更改了我的代码以反映,我没有明确存储y。现在它应该可以工作了。
    • 好的,它适用于这种确切的情况,但总的来说,我实际上需要在损失函数中计算的东西的值,而不仅仅是最终结果。如何存储这些值?
    • 您可以使用全局变量来存储您的值,或者我宁愿将损失函数封装在一个类中,然后您可以使用自引用访问属性。
    猜你喜欢
    • 2017-06-14
    • 2023-03-25
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多