tf.gradients ---错误FetchargumentNonehasinvalidtype

使用tensorflow执行如下最简单梯度下降的代码:
import tensorflow as tf

w1 = tf.Variable([[1,2]])
w2 = tf.Variable([[3,4]])

y = tf.matmul(w1, [[9], [10]])
grads = tf.gradients(y, [w1])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)

报错信息最下边部分如下:
    256     if fetch is None:
    257       raise TypeError('Fetch argument %r has invalid type %r' % (fetch,
--> 258                                                                  type(fetch)))
    259     elif isinstance(fetch, (list, tuple)):
    260       # NOTE(touts): This is also the code path for namedtuples.

TypeError: Fetch argument None has invalid type

报错原因:该错误信息指的是grads操作没有结果返回,导致sess.run()的参数是NoneType。
进一步原因分析:
tensorflow gradients好像不支持 int型的Tensor 的gradients,如果把w1的设置成float类型的例如tf.float32就会执行成功。
修改为:
import tensorflow as tf

w1 = tf.Variable([[1.0,2.0]])
w2 = tf.Variable([[3.0,4.0]])

y = tf.matmul(w1, [[9.0], [10.0]])
grads = tf.gradients(y, [w1])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)

猜你喜欢

转载自blog.csdn.net/monk1992/article/details/89531227
tf
今日推荐