keras 自定义 metrics

简介: 自定义 Metrics在 keras 中操作的均为 Tensor 对象,因此,需要定义操作 Tensor 的函数来操作所有输出结果,定义好函数之后,直接将其放在 model.

自定义 Metrics

keras 中操作的均为 Tensor 对象,因此,需要定义操作 Tensor 的函数来操作所有输出结果,定义好函数之后,直接将其放在 model.compile 函数 metrics 中即可生效:

def precision(y_true, y_pred):
    # Calculates the precision
    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 / (predicted_positives + K.epsilon())
    return precision


def recall(y_true, y_pred):
    # Calculates the recall
    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 / (possible_positives + K.epsilon())
    return recall

def fbeta_score(y_true, y_pred, beta=1):
    # Calculates the F score, the weighted harmonic mean of precision and recall.

    if beta < 0:
        raise ValueError('The lowest choosable beta is zero (only precision).')
        
    # If there are no true positives, fix the F score at 0 like sklearn.
    if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
        return 0

    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    bb = beta ** 2
    fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
    return fbeta_score

def fmeasure(y_true, y_pred):
    # Calculates the f-measure, the harmonic mean of precision and recall.
    return fbeta_score(y_true, y_pred, beta=1)

使用方法如下:

model.compile( 
    optimizer=Adam(), 
    loss='binary_crossentropy',
    metrics = ['accuracy',  fmeasure, recall, precision])

参考

custom metrics for binary classification in Keras

目录
相关文章
|
18天前
|
TensorFlow 算法框架/工具
【Tensorflow+Keras】tf.keras.backend.image_data_format()的解析与举例使用
介绍了TensorFlow和Keras中tf.keras.backend.image_data_format()函数的用法。
30 5
|
24天前
|
机器学习/深度学习 Python
TFLearn实例
【7月更文挑战第27天】TFLearn实例。
14 2
|
17天前
|
API 算法框架/工具
【Tensorflow+keras】使用keras API保存模型权重、plot画loss损失函数、保存训练loss值
使用keras API保存模型权重、plot画loss损失函数、保存训练loss值
12 0
|
3月前
|
机器学习/深度学习 API TensorFlow
TensorFlow的高级API:tf.keras深度解析
【4月更文挑战第17天】本文深入解析了TensorFlow的高级API `tf.keras`,包括顺序模型和函数式API的模型构建,以及模型编译、训练、评估和预测的步骤。`tf.keras`结合了Keras的易用性和TensorFlow的性能,支持回调函数、模型保存与加载等高级特性,助力提升深度学习开发效率。
|
API 算法框架/工具
越来越火的tf.keras模型,这三种构建方式记住了,你就是大佬!!!
越来越火的tf.keras模型,这三种构建方式记住了,你就是大佬!!!
104 0
sklearn.metrics中micro和macro的区别
先看以下示例,区分micro和macro的区别,这里直接调用sklearn封装好的接口
83 0
|
PyTorch 算法框架/工具
【PyTorch】自定义数据集处理/dataset/DataLoader等
【PyTorch】自定义数据集处理/dataset/DataLoader等
160 0
|
网络虚拟化
在torch_geometric.datasets中使用Planetoid手动导入Core数据集及发生相关错误解决方案
在torch_geometric.datasets中使用Planetoid手动导入Core数据集及发生相关错误解决方案
700 0
在torch_geometric.datasets中使用Planetoid手动导入Core数据集及发生相关错误解决方案
|
机器学习/深度学习 TensorFlow API
在tensorflow2.2中使用Keras自定义模型的指标度量
在tensorflow2.2中使用Keras自定义模型的指标度量
128 0
在tensorflow2.2中使用Keras自定义模型的指标度量
|
TensorFlow 算法框架/工具
TensorFlow自定义损失函数
TensorFlow自定义损失函数
110 0