问题描述
我想在Python中实现自定义损失函数,它应该像下面的伪代码一样工作:
I want to implement a custom loss function in Python and It should work like this pseudocode:
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)
我开始像这样定义指标:
I started to define the metric like this:
def custom_metric(y_true,y_pred):
# y_true:
res = K.abs((y_true-y_pred) / y_pred, axis = 1)
....
但是我不知道如何获取 if 和 else 的res值.我也想知道什么必须返回该函数.
But I do not know how to get the value of the res for the if and else. Also I want to know what have to return the function.
谢谢
推荐答案
自定义指标可以在编译步骤中传递.
Custom metrics can be passed at the compilation step.
该函数需要以(y_true, y_pred)
作为参数并返回单个tensor
值.
The function would need to take (y_true, y_pred)
as arguments and return a single tensor
value.
您可以从result_metric
函数返回result
.
def custom_metric(y_true,y_pred):
result = K.abs((y_true-y_pred) / y_pred, axis = 1)
return result
第二步是使用keras
回调函数来查找错误的总和.
The second step is to use a keras
callback function in order to find the sum of the errors.
可以定义回调并将其传递给fit
方法.
The callback can be defined and passed to the fit
method.
history = CustomLossHistory()
model.fit(callbacks = [history])
最后一步是创建CustomLossHistory
类,以查找预期的错误列表中的sum
.
The last step is to create the the CustomLossHistory
class in order to find out the sum
of your expecting errors list.
CustomLossHistory
将继承keras.callbacks.Callback
的一些默认方法.
CustomLossHistory
will inherit some default methods from keras.callbacks.Callback
.
- on_epoch_begin :在每个纪元开始时调用.
- on_epoch_end :在每个纪元结束时调用.
- on_batch_begin :在每批开始时调用.
- on_batch_end :在每个批次结束时调用.
- on_train_begin :在模型训练开始时调用.
- on_train_end :在模型训练结束时调用.
- on_epoch_begin: called at the beginning of every epoch.
- on_epoch_end: called at the end of every epoch.
- on_batch_begin: called at the beginning of every batch.
- on_batch_end: called at the end of every batch.
- on_train_begin: called at the beginning of model training.
- on_train_end: called at the end of model training.
您可以在 Keras文档
但是在这个示例中,我们只需要on_train_begin
和on_batch_end
方法.
But for this example we only need on_train_begin
and on_batch_end
methods.
实施
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
训练好模型后,您可以使用以下语句访问错误.
After your model is trained you can access your errors using following statement.
errors = history.errors
这篇关于如何从Keras中的自定义损失函数获得结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!