TensorFlow 梯度 : Getting unnecessary 0. tf.gradients 的 0 个梯度

标签 tensorflow embedding word-embedding gradient

假设我有以下变量

embeddings = tf.Variable(tf.random_uniform(dtype=tf.float32,shape = [self.vocab_size, self.embedding_dim], minval=-0.001, maxval=0.001))

sent_1 = construct_sentence(word_ids_1)

sent_2 = construct_sentence(word_ids_2)



在哪里 construct_sentence是一种基于占位符 word_ids_1 获得句子表示的方法和 word_ids_2
假设我有一些损失:

loss = construct_loss(sent_1, sent_2, label)



现在,当我尝试使用以下方法获取渐变时:

gradients_wrt_w = tf.gradients(loss, embeddings)



而不是只获得与 construct_sentence 中涉及的特定变量有关的梯度和 construct_loss ,我得到变量 embeddings 中每个嵌入的梯度(对于那些不参与损失和句子表示的嵌入,梯度为 0)。

如何获得我只感兴趣的渐变 wrt 变量?

此外,由于涉及偏导数,我得到了一些变量的重复(具有相同的值)。由于嵌入是一个二维变量,我不能像这样进行简单的查找:

tf.gradients(loss, tf.nn.embedding_lookup(embeddings, word_ids))



这会导致性能大幅下降,因为我正在处理大量的词嵌入,并且我希望每次只对一些词嵌入进行导数。

此外,我得到了很多重复的渐变(因为偏导数),我尝试使用 tf.AggregationMethod 但没有成功。

最佳答案

你不能做tf.gradients(loss, tf.nn.embedding_lookup(embeddings, word_ids)) ,
但你可以直接做tf.gradients(loss, embeddings)这会给你一个tf.IndexedSlices仅包含受影响单词 id 的梯度的对象。

关于重复单词id对应的梯度聚合,调用optimizer.apply_gradients时自动完成。 ,但您可以使用 tf.unsorted_segment_sum 复制此内容和 tf.unique如下:

embedding_table = tf.random_uniform((10, 5))
word_ids = tf.placeholder(shape=(None), dtype=tf.int32)
temp_emb = tf.nn.embedding_lookup(embedding_table, word_ids)
loss = tf.reduce_sum(temp_emb, axis=0)

g = tf.gradients(loss, embedding_table)[0].values
repeating_indices = tf.gradients(loss, embedding_table)[0].indices # This is the same as word_ids.

unique_indices, idx_in_repeating_indices = tf.unique(repeating_indices)

agg_gradients = tf.unsorted_segment_sum(g,
                                        idx_in_repeating_indices,
                                        tf.shape(unique_indices)[0])

sess = tf.Session()
unique_indices_v, agg_gradients_v, _ = \
    sess.run([unique_indices, agg_gradients, loss],
         feed_dict={word_ids: np.array([6, 1, 5, 1, 1, 5])})


print(unique_indices_v)
print(agg_gradients_v)

给上面的例子:
[6 1 5]

[[1. 1. 1. 1. 1.]
 [3. 3. 3. 3. 3.]
 [2. 2. 2. 2. 2.]]

关于TensorFlow 梯度 : Getting unnecessary 0. tf.gradients 的 0 个梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48625454/

相关文章:

ios - 如何在iOS中运行Tensorflow对象检测API模型?

python - 从c中的嵌入式python代码加载DLL

python - 了解 Keras LSTM 中的字符级嵌入

deep-learning - 如何使用 GPU 训练数百万个 doc2vec 嵌入?

machine-learning - 用于理解上下文单词的自然语言处理技术

python - 索引错误 : List index out of range.。尽管在范围内?

python - 云预测和本地预测返回的结果不一样

python-2.7 - BeamSearch 在 Tensorflow 中花费了很长时间

python-3.x - 如何从 tfrecord 解码 vggish 音频集嵌入?

nlp - wmd(词移动距离)和基于 wmd 的相似度有什么区别?