我想在 Python 中实现自定义损失函数,它应该像这样的伪代码:
aux = | Real - Prediction | / Prediction
errors = []
if aux <= 0.1:
errors.append(0)
elif aux > 0.1 & <= 0.15:
errors.append(5/3)
elif aux > 0.15 & <= 0.2:
errors.append(5)
else:
errors.append(2000)
return sum(errors)
我开始这样定义指标:
def custom_metric(y_true,y_pred):
# y_true:
res = K.abs((y_true-y_pred) / y_pred, axis = 1)
....
但我不知道如何获取if 和else 的res 值。另外我想知道什么必须返回函数。
谢谢
最佳答案
Also I want to know what have to return the function.
可以在编译步骤传递自定义指标。
该函数需要将 (y_true, y_pred)
作为参数并返回单个 tensor
值。
But I do not know how to get the value of the res for the if and else.
您可以从 result_metric
函数返回 result
。
def custom_metric(y_true,y_pred):
result = K.abs((y_true-y_pred) / y_pred, axis = 1)
return result
第二步是使用 keras
回调函数来计算错误的总和。
可以定义回调并将其传递给fit
方法。
history = CustomLossHistory()
model.fit(callbacks = [history])
最后一步是创建 CustomLossHistory
类,以便找出您预期的错误 列表的sum
。
CustomLossHistory
将从 keras.callbacks.Callback
继承一些默认方法。
- on_epoch_begin:在每个纪元开始时调用。
- on_epoch_end:在每个纪元结束时调用。
- on_batch_begin:在每个批处理开始时调用。
- on_batch_end:在每个批处理结束时调用。
- on_train_begin:在模型训练开始时调用。
- on_train_end:在模型训练结束时调用。
您可以在 Keras Documentation 中阅读更多内容
但对于这个例子,我们只需要 on_train_begin
和 on_batch_end
方法。
实现
class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.errors= []
def on_batch_end(self, batch, logs={}):
loss = logs.get('loss')
self.errors.append(self.loss_mapper(loss))
def loss_mapper(self, loss):
if loss <= 0.1:
return 0
elif loss > 0.1 & loss <= 0.15:
return 5/3
elif loss > 0.15 & loss <= 0.2:
return 5
else:
return 2000
模型训练完成后,您可以使用以下语句访问您的错误。
errors = history.errors
关于python - 如何从 Keras 中的自定义损失函数中获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061393/