【问题标题】:Gradient of a function evaluated over a batch在批次上评估的函数的梯度
【发布时间】:2019-05-01 16:31:14
【问题描述】:

我想使用 Tensorflow 来计算函数的梯度。但是,如果我使用 tf.gradients 函数,它会返回一个渐变列表。如何为批次的每个点返回一个列表?

# in a tensorflow graph I have the following code
tf_x = tf.placeholder(dtype=tf.float32, shape=(None,N_in), name='x')
tf_net #... conveniently defined neural network
tf_y = tf.placeholder(dtype=tf.float32, shape=(None,1), name='y')

tf_cost = (tf_net(tf_x) - tf_y)**2  # this should have length N_samples because I did not apply a tf.reduce_mean

tf_cost_gradients = tf.gradients(tf_cost,tf_net.trainable_weights)

如果我们在 tensorflow 会话中运行它,

# suppose myx = np.random.randn(N_samples,N_in) and myy conveniently chosen
feed = {tf_x:myx, tx_y:myy}
sess.run(tf_cost_gradients,feed)

我只得到一个列表,而不是我想要的每个样本的列表。我可以使用

for i in len(myx):
    feed = {tf_x:myx[i], tx_y:myy[i]}
    sess.run(tf_cost_gradients,feed)

但这太慢了!我能做些什么?谢谢

【问题讨论】:

  • 批次上的函数梯度在您的情况下确实是一个向量。如果您打算计算函数 w.r.t 每个样本的梯度,则称为随机梯度下降,您需要按照代码中所示的方式一一进行。
  • @danyfang,不,SGD 是当您计算和应用数据部分的 grads 时。 GD 是所有数据的毕业生。所以从技术上讲,批次上的毕业生也是 SGD。
  • @danyfang 是的,这正是我的意思,我想通过喂一批来加快速度。有什么想法吗?
  • 由于您只有一个计算图并且在一个会话中只能有一个图,我认为您必须按照您发布的方式进行操作,例如一个一个地运行它。任何大于 1 的批量大小都不会为您提供每个样本的梯度。

标签: python tensorflow keras deep-learning gradient


【解决方案1】:

虽然在 tf.gradients 中有一个 'aggregation_method' 参数,但要获得单个梯度并不容易。

aggregation_method: Specifies the method used to combine gradient terms.

请查看以下主题:

https://github.com/tensorflow/tensorflow/issues/15760 https://github.com/tensorflow/tensorflow/issues/4897

在其中一个线程 (#4897) 中,Ian Goodfellow 提出以下建议以加快单个梯度计算:

This is only pseudocode, but basic idea is:

examples = tf.split(batch)
weight_copies = [tf.identity(weights) for x in examples]
output = tf.stack(f(x, w) in zip(examples, weight_copies))
cost = cost_function(output)
per_example_gradients = tf.gradients(cost, weight_copies)

【讨论】:

  • 在这个例子中f是什么?
  • 问题是,如果权重是 Keras 中定义的神经网络的参数,我该如何使用它?
  • f 是将输入映射到输出的函数。在你的例子中,神经网络。
  • 但这意味着我每次评估时都需要给神经网络赋予权重。如果我有一个使用 tf_net(x_in) 评估的 keras 模型 tf_net = keras.model(tf_in, f),我该如何指定权重?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2021-05-19
  • 2018-02-09
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多