首页 > 解决方案 > ValueError:没有为任何变量提供渐变,请检查您的图表是否有不支持渐变的操作

问题描述

我有一个简单的代码如下。当我尝试运行它时,出现以下错误:

ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'Variable:0' shape=(2,) dtype=int32_ref>"] and loss Tensor("Sum:0", shape=(), dtype=float32)

知道我应该怎么做吗?谢谢。

import tensorflow as tf

def compute_objfunc(x1, x2, shift):

    part11 = tf.slice(x1, [shift[0]], [100-shift[0]])
    part12 = tf.zeros((shift[0],), dtype=tf.float32)
    y1 = tf.concat([part11, part12], axis=0)

    part21 = tf.slice(x2, [shift[1]], [100-shift[1]])
    part22 = tf.zeros((shift[1],), dtype=tf.float32)
    y2 = tf.concat([part21, part22], axis=0)

    return tf.reduce_sum(y1+y2)

shift = tf.Variable([1, 2], dtype=tf.int32)

x1 = tf.placeholder("float", [100,])
x2 = tf.placeholder("float", [200,])

J = compute_objfunc(x1, x2, shift)

train_op = tf.train.AdamOptimizer(0.01).minimize(J)

标签: tensorflow

解决方案


这里只有一个变量,shift. 由于它是一个整数变量,它不会贡献任何梯度。(浮点变量贡献梯度。当您认为应该使用梯度对变量的值进行微小更改时,整数变量没有梯度是有道理的,但整数变量不能以小于 1 的值改变。)

应该x1并且x2是变量而不是占位符?


推荐阅读