使用tf.gradients和tf.hessian时的Tensorflow错误:TypeError:Fetch参数无无效类型<type'nonetype'=“”>

时间:2017-04-28 03:17:44

标签: tensorflow gradient nonetype hessian-matrix

我刚刚开始学习tensorflow,并在使用tf.gradients和tf.hessain函数时遇到以下错误。下面给出了tf.gradients的代码和错误。

import tensorflow as tf
a = tf.placeholder(tf.float32,shape = (2,2))
b = [[1.0,2.0],[3.0,4.0]]
c = a[0,0]*a[0,1]*a[1,0] + a[0,1]*a[1,0]*a[1,1]
e = tf.reshape(b,[4])
d = tf.gradients(c,e)
sess = tf.Session()
print(sess.run(d,feed_dict={a:b}))

我在最后一行收到以下错误

>>> print(sess.run(d,feed_dict={a:b}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 952, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 230, in for_fetch
    return _ListFetchMapper(fetch)
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 337, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/share/apps/tensorflow/20170218/python2.7/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 227, in for_fetch
    (fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <type 'NoneType'>

关于我如何调试它的任何想法?

1 个答案:

答案 0 :(得分:1)

这是因为c是根据a计算的,而不是e。您可以更改渐变张量线,如下所示。

d = tf.gradients(c,a)

BTW,在您的原始代码中,如果您打印d,您会发现它是[None]