我知道这篇文章已经发表很久了,但是当我搜索相同的答案时,我找到了这个问题并最终自己解决了它。 简而言之,您需要记住在定义EarlyStopping回调的度量时,同时将其作为编译模型的度量
好的,所以你已经使用类似于以下内容的代码定义了自定义损失函数或指标(取自https://github.com/keras-team/keras/issues/10018,该代码本身取自https://dev59.com/41cP5IYBdhLWcg3w-Opz#45305384):
def f1_metric(y_true, y_pred):
def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = (true_positives + K.epsilon()) / (possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = (true_positives + K.epsilon()) / (predicted_positives + K.epsilon())
return precision
precision = precision(y_true, y_pred)
recall = recall(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
现在,您可以将其作为一个字符串提供给EarlyStopping Callback使用,例如
EarlyStopping(monitor='f1_metric')
,或者,如果要针对验证进行监控,则使用
EarlyStopping(monitor='val_f1_metric')
。
但这还不够!如果你停在那里,你会得到你得到的错误。当你使用model.compile(metrics=[f1_metric])
编译你的模型时,你需要同时提供实际的函数作为参数。请注意缺少引号 - 你正在引用函数本身。
如果你通过使用metrics关键字包含该函数来编译模型,并且还包括EarlyStopping Callback,那么它应该可以干净地工作。