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)]
顺利输出