【发布时间】:2017-02-28 15:41:21
【问题描述】:
我在使这个自定义损失函数(它检查y_pred 数据的排序是否与y_true 提供的实际排序索引一致)工作时遇到了一些问题:
def custom_objective(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
ordered_output = tf.cast(tf.nn.top_k(-y_pred, k=5)[1], tf.float32)
return tf.sqrt(tf.reduce_mean(tf.square(ordered_output - y_true), axis=-1))
我可以使用示例数据正确运行它:
with tf.Session() as sess:
print(custom_objective(tf.constant([0, 1, 2, 3, 4, 5]),
tf.constant([0.0, 0.9, 0.2, 0.3, 0.5, 0.8])).eval()) # 1.82574
但如果我在model.compile 中使用它,它会以某种方式不起作用,因为它会引发:
/Users/luca/.virtualenvs/python3/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
358 else:
359 if values is None:
--> 360 raise ValueError("None values not supported.")
361 # if dtype is provided, forces numpy array to be the type
362 # provided if possible.
ValueError: None values not supported.
请注意,如果我将ordered_output = tf.cast(tf.nn.top_k(-y_pred, k=5)[1], tf.float32) 更改为ordered_output = -y_pred,我的训练测试集中没有“无”值,模型编译良好并开始正确训练(但这显然不是我想要的损失函数)。
我有一种微妙的感觉,在损失函数中使用 top_k 可能有问题,因为我看不出它是如何可区分的,但我没有更好的想法来评估预测排序的差异。提示/想法/论文/参考? :)
【问题讨论】:
-
y_true是订单数据还是订单数据的索引? -
@MarcinMożejko 第二个。 y 最初是有序的,然后在训练之前被打乱,y_true 表示我想要预测的有序数据的索引。 atm 我默认使用 MSE 来预测它,但它不是超级高效
-
我可能会向您展示如何重写您的模型以优化它以获得您想要的结果。目前 - 您的模型可能做得很差。
-
今晚我也在问自己同样的问题:“top-k 是否可微分?”我遇到了this sister site answer,它的评论指向this paper with a differentiable top-k approximation。
标签: python tensorflow neural-network keras