我有一些问题,使得这个自定义损失函数(它会检查是否y_pred
数据与由y_true
提供真正的订货指数连贯有序的)工作:如何在keras丢失函数中使用tf.nn.top_k?
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'订单数据还是有序数据的indeces? –
@MarcinMożejko第二。 y最初是有序的,然后在训练之前进行洗牌,y_true表示我想要预测的有序数据的索引。 atm我默认使用MSE来预测它,但它不是超高效的 – luke14free
我可能会告诉你如何重写你的模型来优化它以获得你想要的结果。目前 - 你的模型可能做得很差。 –