Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tensorflow中的变量没有梯度_Python_Tensorflow - Fatal编程技术网

Python Tensorflow中的变量没有梯度

Python Tensorflow中的变量没有梯度,python,tensorflow,Python,Tensorflow,我正在学习在Tensorflow中训练变量。但我甚至连最简单的一个例子都不正确。以下代码将产生ValueError:没有为任何变量提供梯度。有人能帮我吗?谢谢 import tensorflow as tf import click tf.compat.v1.enable_eager_execution() #tf.config.run_functions_eagerly(True) @click.command() @click.option('--lr', default = 0.001)

我正在学习在Tensorflow中训练变量。但我甚至连最简单的一个例子都不正确。以下代码将产生
ValueError:没有为任何变量提供梯度。有人能帮我吗?谢谢

import tensorflow as tf
import click
tf.compat.v1.enable_eager_execution()
#tf.config.run_functions_eagerly(True)

@click.command()
@click.option('--lr', default = 0.001)
@click.option('--epochs', default = 10)
def main(lr, epochs):
    optimizer = tf.optimizers.Adam(learning_rate=lr)

    v = tf.Variable([0,0],trainable=True)
    w = tf.convert_to_tensor([1,1])

    def loss():
        loss_value = tf.reduce_sum(tf.square(v-w))
        return loss_value

    variables = [v]
    for epoch in range(epochs):
        optimizer.minimize(loss,variables)
        #print("epoch ", epoch, ": loss: ",loss_value.numpy())

if __name__ == '__main__':
    main()
你好, 可以通过提及创建的每个变量的数据类型来解决此错误。
v=tf.Variable([0,0],trainable=True,dtype=tf.float32)

w=tf.convert_to_tensor([1,1],dtype=tf.float32)

优化器中的
损失是什么。最小化(损失,变量)
?为什么要将函数引用传递给它?尝试
优化器。最小化(loss(),variables)
。我按照Armin的建议添加了数据类型,现在问题解决了。我认为错误信息在这里不是很有用。是否有任何参考文献概括了此类问题?我不知道有任何此类参考文献。