官方 ZeroOut 梯度示例错误:属性错误:"列表"对象没有属性"eval"



我遵循了tensorflow网站的官方教程:https://www.tensorflow.org/extend/adding_an_op 在教程中还描述了如何调用示例 ZeroOut 的梯度,我想在下面的这个简短代码片段中尝试。

我在这里找到了代码:https://github.com/MatteoRagni/tf.ZeroOut.gpu

import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import sparse_ops
zero_out_module = tf.load_op_library('./libzeroout.so')
@ops.RegisterGradient("ZeroOut")
def _zero_out_grad(op, grad):
to_zero = op.inputs[0]
shape = array_ops.shape(to_zero)
index = array_ops.zeros_like(shape)
first_grad = array_ops.reshape(grad, [-1])[0]
to_zero_grad = sparse_ops.sparse_to_dense([index], shape, first_grad, 0)
return [to_zero_grad]  # List of one Tensor, since we have one input
t_in = tf.placeholder(tf.int32, [None,None])
ret = zero_out_module.zero_out(t_in)
grad = tf.gradients(ys=tf.reduce_sum(ret), xs=t_in)
with tf.Session(''):
feed_dict = {t_in: [[1, 2], [3, 4]]}
print "ret val: ", ret.eval(feed_dict=feed_dict)
print "grad: ", grad
print "grad: ", grad.eval(feed_dict=feed_dict)

我收到此错误...

AttributeError: 'list' object has no attribute 'eval'

。但我可以做 ret.eval()。

为什么我不能调用grad.eval()?我想在渐变张量中看到这些值。如何调试梯度?

老问题的答案

实施

def _zero_out_grad(op, *grads):
topdiff = grads[0]
bottom = op.inputs[0]
shape = array_ops.shape(bottom)
index = array_ops.zeros_like(shape)
first_grad = array_ops.reshape(topdiff, [-1])[0]
to_zero_grad = sparse_ops.sparse_to_dense([index], shape, first_grad, 0)
return to_zero_grad

在这里效果很好。你确定"@ops。RegisterGradient("ZeroOut")"在tf.Session()之前执行

?通常

zero_out_module = tf.load_op_library('./libzeroout.so')
@ops.RegisterGradient("ZeroOut")
def _zero_out_grad(op, grad):
# ...

放置在不同的文件中并刚刚导入。即使使用最近的TensorFlow版本,这里也有一个完整的工作示例。

完全改变的问题的答案

你的梯度函数返回一个列表,而 Python 列表没有 'eval()'。尝试以下任一操作:

grad = tf.gradients(ys=tf.reduce_sum(ret), xs=t_in)[0]

或遵循最佳实践并使用

grad = tf.gradients(ys=tf.reduce_sum(ret), xs=t_in)
with tf.Session() as sess:
sess.run(grad, feed_dict=feed_dict)

请不要更改整个问题

最新更新