使用 tf.gradients 和 tf.hessian 时出现 TensorFlow 错误:TypeError: Fetch argument None has invalid type <t

Posted

技术标签:

【中文标题】使用 tf.gradients 和 tf.hessian 时出现 TensorFlow 错误:TypeError: Fetch argument None has invalid type <type \'NoneType\'>【英文标题】:Tensorflow Error when using tf.gradients and tf.hessian: TypeError: Fetch argument None has invalid type <type 'NoneType'>使用 tf.gradients 和 tf.hessian 时出现 TensorFlow 错误:TypeError: Fetch argument None has invalid type <type 'NoneType'> 【发布时间】:2017-04-28 03:17:43 【问题描述】:

我刚开始学习 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】:

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

d = tf.gradients(c,a)

顺便说一句,在你的原始代码中,如果你打印d,你会发现它是一个[None]

【讨论】:

以上是关于使用 tf.gradients 和 tf.hessian 时出现 TensorFlow 错误:TypeError: Fetch argument None has invalid type <t的主要内容,如果未能解决你的问题,请参考以下文章

如何使用`tf.gradients`? `TypeError: Fetch argument None has invalid type <type 'NoneType'>`

TensorFlow梯度求解tf.gradients

TensorFlow梯度求解tf.gradients

tf.gradients() 是如何工作的?

TensorFlow tf.gradients的用法详细解析以及具体例子

tensorflow-底层梯度tf.AggregationMethod,tf.gradients