TensorFlow gradients 求梯度报错 Fetch argument None has invalid type

tf.gradients 求梯度报错 TypeError: Fetch argument None has invalid type <class 'NoneType'>

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,w2])#w2不相干,会报错
grads = tf.gradients(y, [w1])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)
Traceback (most recent call last):
  File "E:/人工智能/python学习/test814.py", line 18, in <module>
    gradval = sess.run(grads)
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
    run_metadata_ptr)
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 1158, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 474, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 264, in for_fetch
    return _ListFetchMapper(fetch)
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 373, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 373, in <listcomp>
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "C:\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 261, in for_fetch
    type(fetch)))
TypeError: Fetch argument None has invalid type <class 'NoneType'>

原因:用tf.gradients()求梯度输入张量必须是float类型,不能是整型

改为以下代码

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,w2])#w2不相干,会报错
grads = tf.gradients(y, [w1])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    gradval = sess.run(grads)
    print(gradval)
[array([[ 9., 10.]], dtype=float32)]

顺利输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值