出于某种原因,我在尝试使用Keras模型指定f1分数时收到错误消息:
model.compile(optimizer='adam', loss='mse', metrics=['accuracy', 'f1_score'])
我收到此错误:
ValueError: Unknown metric function:f1_score
提供' f1_score'我在同一个文件中使用' model.compile'像这样:
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.save(model_path) # works ok
然后将其加载到另一个程序中:
from keras import models
model = models.load_model(model_path)
失败并显示错误:
ValueError: Unknown metric function:f1_score
指定' f1_score'这次在同一档案中没有帮助,Keras没有看到它。怎么了?如何使用Keras模型的F1得分?
答案 0 :(得分:8)
加载模型时,您必须将该指标作为custom_objects
包的一部分提供。
试试这样:
from keras import models
model = models.load_model(model_path, custom_objects= {'f1_score': f1_score})
f1_score
是您通过compile
传递的函数。
答案 1 :(得分:0)
为了实现f1_score
工作,我必须在函数声明中切换y_true
和y_pred
。
P.S。:那些问过:K = keras.backend
答案 2 :(得分:0)
更改:
metrics=['accuracy', f1_score]
收件人:
metrics=[f1_score]