python - 如何在 Keras 模型中使用 F1 Score?

标签 python keras

出于某种原因,我在尝试使用 Keras 模型指定 f1 分数时收到错误消息:

model.compile(optimizer='adam', loss='mse', metrics=['accuracy', 'f1_score'])

我收到这个错误:

ValueError: Unknown metric function:f1_score

在我使用“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.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 Score?

最佳答案

加载模型时,您必须提供该指标作为 custom_objects 包的一部分。

像这样尝试:

from keras import models 
model = models.load_model(model_path, custom_objects= {'f1_score': f1_score})

其中 f1_score 是您通过compile 传递的函数。

关于python - 如何在 Keras 模型中使用 F1 Score?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411902/

相关文章:

python - Google 应用引擎静态文件处理程序示例

python - 如何使用 flask 创建进度条?

python - 在字符串内打印单引号

python - 从自动编码器 : ValueError: Input 0 of layer dense_3 is incompatible with the layer: 定义编码器和解码器模型

tensorflow - Tensorflow 如何计算模型的准确率?

python - 如何使用conda安装本地包

python - GridSearchCV - 错误 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

python - 二维数组内的填充列表

tensorflow - 使用 Keras 进行多输出分类

machine-learning - 深度学习: small dataset with keras : local minima