【问题标题】:Function gradients with gather operations in tensorflow张量流中具有聚集操作的函数梯度
【发布时间】:2018-05-11 23:44:53
【问题描述】:

我正在尝试使用 tensorflow 编写一个复杂的计算图,并计算关于函数参数的符号梯度。 但是,当我的函数/图形涉及某些参数的收集操作时,我正在为此苦苦挣扎。问题是 Session.run 返回的梯度不仅是张量,而且是 IndexedSlices 对象。而且我不知道如何正确地将其转换为张量。

这是一个说明问题的玩具示例

import tensorflow as tf
import numpy as np
from tensorflow.python.ops import gradients_impl as GI

T_W = tf.placeholder(tf.float32, [2], 'W') # parameter vector
T_data = tf.placeholder(tf.float32, [10], 'data') # data vector
T_Di = tf.placeholder(tf.int32, [10], 'Di') # indices vector
T_pred = tf.gather(T_W,T_Di)
T_loss = tf.reduce_sum(tf.square(T_data-T_pred)) # loss function

T_grad = tf.gradients(T_loss,[T_W])
#T_grad=GI._IndexedSlicesToTensor(T_grad)                                       

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    feed_dict={T_W: [1.,2.],
           T_data: np.arange(10)**2,
           T_Di: np.arange(10)%2}
    dl, dgrad = sess.run(
    [T_loss, T_grad], feed_dict=feed_dict)
    grad = np.array(dgrad)
    print (grad)

哪些输出

[[array([   4.,    4.,   -4.,  -12.,  -28.,  -44.,  -68.,  -92., -124.,
   -156.], dtype=float32)
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1], dtype=int32)
array([2], dtype=int32)]]

在这里,我得到这个 indexedSlices 对象,而不是应该是两个元素的向量的渐变。

我看到内部模块 tensorflow.python.ops.gradients_impl 有某种内部转换器 _indexedSlicesToTensor,但我觉得奇怪的是,没有“官方”方法将梯度作为张量。例如,在 theano 中,就没有这样的问题。

【问题讨论】:

    标签: python tensorflow differentiation


    【解决方案1】:

    答案很简单。我只需要使用 tf.convert_to_tensor() 函数

    T_grad = tf.gradients(T_loss,[T_W])
    T_grad = tf.convert_to_tensor(T_grad[0])
    

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多