我正在尝试为 Keras 回归任务创建自定义损失函数。
我正在预测一场比赛中每分钟的得分,并以分钟为单位对可变长度的“比赛”进行训练。为了帮助模型学习,我想将小组玩的分钟数作为损失函数的一部分,这样我们就可以适当地“惩罚”长时间玩的小组的缺失。
我知道我需要使用 Keras 后端/张量操作,但我被困在如何准备分钟/如何乘以分钟张量。这是我到目前为止的一些基本代码(伪代码/在不重要的地方跳过):
def penalized_loss(minutes):
# minutes is np.array - do we need to convert to tensor?
# Is this useful/how to do it?
minutes_tensor = K.constants(minutes)
def loss(y_true, y_pred):
# Normal mean_squared_error - this makes sense to me
lost = K.mean(K.square(y_pred - y_true), axis=-1)
# Would like something like this where minutes are included, but as a valid tensor operation
not_valid_result = K.mean(K.square(y_pred - y_true) * minutes, axis=-1)
# Is this closer to what we need to do?
maybe_closer_result = K.mean(K.dot(K.square(y_pred - y_true), minutes), axis=-1)
return lost
return loss
# minutes is np.array, shape (12024,)
# input/predictions also have shape 12024
def baseline_model():
model = Sequential()
# Create the model....
# Compile model
model.compile(loss=[penalized_loss(minutes)], optimizer='adam')
return model
在几分钟内通过的关闭按我的预期工作,我只是坚持如何进行* minutes损失计算的部分。我浏览了文档,我觉得我错过了一些简单/明显的东西。谁能指出我正确的方向?