[英]How to use F1 Score with Keras model?
For some reason I get error message when trying to specify f1 score with Keras model:出于某种原因,我在尝试使用 Keras 模型指定 f1 分数时收到错误消息:
model.compile(optimizer='adam', loss='mse', metrics=['accuracy', 'f1_score'])
I get this error:我收到此错误:
ValueError: Unknown metric function:f1_score
After providing 'f1_score' function in the same file where I use 'model.compile' like this:在我使用 'model.compile' 的同一个文件中提供 'f1_score' 函数后:
def f1_score(y_true, y_pred):
# Count positive samples.
c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
# If there are no true samples, fix the F1 score at 0.
if c3 == 0:
return 0
# How many selected items are relevant?
precision = c1 / c2
# How many relevant items are selected?
recall = c1 / c3
# Calculate f1_score
f1_score = 2 * (precision * recall) / (precision + recall)
return f1_score
model.compile(optimizer='adam', loss='mse', metrics=['accuracy', f1_score])
Model compiles all right and can be saved to a file:模型编译没问题,可以保存到文件中:
model.save(model_path) # works ok
Yet loading it in another program, :然而在另一个程序中加载它,:
from keras import models
model = models.load_model(model_path)
fails with an error:失败并出现错误:
ValueError: Unknown metric function:f1_score
Specifying 'f1_score' in the same file this time does not help, Keras does not see it.这次在同一个文件中指定 'f1_score' 没有帮助,Keras 没有看到它。 What's wrong?
怎么了? How to use F1 Score with Keras model?
如何在 Keras 模型中使用 F1 Score?
When you load the model, you have to supply that metric as part of the custom_objects
bag.当您加载模型时,您必须提供该指标作为
custom_objects
包的一部分。
Try it like this:像这样尝试:
from keras import models
model = models.load_model(model_path, custom_objects= {'f1_score': f1_score})
Where f1_score
is the function that you passed through compile
.其中
f1_score
是您通过compile
传递的函数。
For your implementation of f1_score
to work I had to switch y_true
and y_pred
in the function declaration.为了使
f1_score
实现起作用,我必须在函数声明中切换y_true
和y_pred
。 PS: for those who asked: K = keras.backend
PS:对于那些问:
K = keras.backend
change:改变:
metrics=['accuracy', f1_score]
to:到:
metrics=[f1_score]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.