python - 可以在 TensorFlow 中使用 Rank Correlation 作为成本函数吗?

标签 python tensorflow

我正在处理偶尔会夹杂异常值的极其嘈杂的数据,因此我主要依赖相关性作为我神经网络中准确性的衡量标准。

是否可以明确使用诸如等级相关性(Spearman 相关系数)之类的东西作为我的成本函数?到目前为止,我主要依赖 MSE 作为相关性的代理。

我现在遇到三个主要障碍:

1) 排名的概念随着小批量变得更加模糊。

2) 你如何动态地进行排名? TensorFlow 不会有梯度错误/无法跟踪权重/偏差的变化如何影响成本吗?

3) 如何确定运行时所查看的张量的大小?

例如,如果我只使用相关性,下面的代码是我想大致做的。实际上,长度需要传入而不是在运行时确定。

length = tf.shape(x)[1] ## Example code. This line not meant to work.

original_loss =  -1 * length * tf.reduce_sum(tf.mul(x, y)) - (tf.reduce_sum(x) * tf.reduce_sum(y))
divisor = tf.sqrt(
  (length * tf.reduce_sum(tf.square(x)) - tf.square(tf.reduce_sum(x))) *
  (length * tf.reduce_sum(tf.square(y)) - tf.square(tf.reduce_sum(y)))
)
original_loss = tf.truediv(original_loss, divisor)

最佳答案

这是 Spearman 相关的代码:

predictions_rank = tf.nn.top_k(predictions_batch, k=samples, sorted=True, name='prediction_rank').indices
real_rank = tf.nn.top_k(real_outputs_batch, k=samples, sorted=True, name='real_rank').indices
rank_diffs = predictions_rank - real_rank
rank_diffs_squared_sum = tf.reduce_sum(rank_diffs * rank_diffs)
six = tf.constant(6)
one = tf.constant(1.0)
numerator = tf.cast(six * rank_diffs_squared_sum, dtype=tf.float32)
divider = tf.cast(samples * samples * samples - samples, dtype=tf.float32)
spearman_batch = one - numerator / divider

Spearman 相关性的问题在于您需要使用排序算法(在我的代码中为 top_k)。并且没有办法将其转化为损失值。没有排序算法的派生。您可以使用正态相关,但我认为使用均方误差在数学上没有区别。

我现在正在为图像做这件事。我在他们用来将排名添加到损失函数中的论文中读到的是比较 2 或 3 个图像(我说图像你可以说任何你想排名的东西)。

比较两个元素:

enter image description here

enter image description here

其中 N 是元素总数,α 是边距值。我从 Photo Aesthetics Ranking Network with Attributes and Content Adaptation 得到这个方程式

您还可以对 3 个元素使用损失,将其中两个具有相似排名的元素与另一个具有不同排名的元素进行比较:

enter image description here

但是在这个等式中你还需要加上排名的方向,更多细节在Will People Like Your Image? .在本文的案例中,他们使用矢量编码而不是实际值,但您也可以只对数字进行编码。

在图像的情况下,当这些图像相关时,图像之间的比较更有意义。因此,运行聚类算法来创建(也许?)10 个集群是个好主意,这样您就可以使用同一集群的元素而不是非常不同的元素来进行比较。这将有助于网络,因为输入以某种方式相关而不是完全不同。

作为旁注,您应该知道什么对您更重要,是最终排名顺序还是排名值。如果它是你应该使用均方误差的值,如果它是排名顺序你可以使用我之前写的损失。或者您甚至可以将它们结合起来。

How do you determine the size of the tensors you're looking at during runtime?

tf.shape(tensor) 返回具有形状的张量。然后你可以使用 tf.gather(tensor,index) 来获取你想要的值。

关于python - 可以在 TensorFlow 中使用 Rank Correlation 作为成本函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487410/

相关文章:

python - TF slice_input_producer 没有保持张量同步

python - 按元组元素过滤元组列表

python - 如何使用 `scipy.optimize.linprog` 来实现更复杂的目标函数?

python - 如何在 2.0 和 1.x 之间切换 TensorFlow 版本?

tensorflow - GPU -> CPU Memcpy 在 tensorflow word2vec 中失败 gpu 发生

tensorflow - 在 tensorflow 2.0 中编写我们自己的自定义训练循环时如何执行提前停止?

python - 如何仅对列表中的指定位进行异或

python - 当我想要的时候 GameOver 屏幕没有出现 - pygame

tensorflow - 如何增加 Keras 中的数据训练偏差?

amazon-web-services - 如何快速调试 SageMaker 训练脚本?