【问题标题】:Compute efficiently a pairwise ranking loss function in Tensorflow在 Tensorflow 中高效计算成对排序损失函数
【发布时间】:2017-12-19 02:36:40
【问题描述】:

我目前正在 tensorflow 中实现 http://www.aclweb.org/anthology/P15-1061

我已经实现了成对排名损失函数(论文的第 2.5 节),如下所示:

s_theta_y = tf.gather(tf.reshape(s_theta, [-1]), y_true_index)
s_theta_c_temp = tf.reshape(tf.gather(tf.reshape(s_theta, [-1]), y_neg_index), [-1, classes_size])
s_theta_c = tf.reduce_max(s_theta_c_temp, reduction_indices=[1])

我不得不使用 tf.gather 而不是 tf.gather_nd,因为后者还没有通过梯度下降实现。我还必须使用展平矩阵将所有索引转换为正确。

如果 tf.gather_nd 是用梯度下降实现的,我的代码如下:

s_theta_y = tf.gather_nd(s_theta, y_t_index)
s_theta_c_temp = tf.gather_nd(s_theta, y_neg_index)
s_theta_c = tf.reduce_max(s_theta_c_temp, reduction_indices=[1])

s_theta 是每个类别标签的计算分数,如论文中所述。 y_true_index 包含真实类的索引,以便计算 s_theta_y。 y_neg_index 是所有负类的索引,它的维度要么是#class-1,要么是#class,是关系被归类为other。

但是,有几个句子被归类为“其他”,因此,s_theta_y 不存在,我们不应该在计算时考虑它。为了处理这种情况,我有一个常数因子 0 来取消该术语,并且对于负类具有相同的维度向量,我只是复制索引的随机值,因为最后,我们只对所有负类(而不是索引)中的最大值。

有没有更有效的方法来计算损失函数中的这些项?我的印象是使用 tf.gather 进行如此多的 reshape 非常慢

【问题讨论】:

    标签: python machine-learning tensorflow deep-learning


    【解决方案1】:

    当然,gather_nd 听起来是你想要的,但在渐变在那里实现之前,我会毫不犹豫地使用你的 reshape() 解决方案,因为 reshape() 实际上是免费的。

    C++ implementation of the reshape() op 看起来做了很多工作,但这只是对形状信息的快速错误检查。 “工作”发生在第 90 行的 CopyFrom 中,这听起来可能很昂贵,但实际上只是一个指针副本(CopyFrom 调用 CopyFromInternal 来复制指针)。

    这完全说得通:底层缓冲区只是row-major order 中的一个平面数组,并且排序不依赖于形状信息。出于同样的原因,像 tf.transpose() 这样的东西一般需要复制。

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2018-12-20
      • 2023-02-26
      相关资源
      最近更新 更多