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

目录
相关文章
|
Unix 网络安全 iOS开发
Mac 电脑如何安装Wireshark?
Mac 电脑如何安装Wireshark?
1175 0
Mac 电脑如何安装Wireshark?
|
机器学习/深度学习 算法
【基础回顾】在回归任务中常见的损失函数比较(mse、mae、huber)
【基础回顾】在回归任务中常见的损失函数比较(mse、mae、huber)
1429 0
【基础回顾】在回归任务中常见的损失函数比较(mse、mae、huber)
|
数据处理 Python
|
5月前
|
人工智能 编解码 算法
AI生成视频告别剪辑拼接!MAGI-1:开源自回归视频生成模型,支持一镜到底的长视频生成
MAGI-1是Sand AI开源的全球首个自回归视频生成大模型,采用创新架构实现高分辨率流畅视频生成,支持无限扩展和精细控制,在物理行为预测方面表现突出。
531 1
AI生成视频告别剪辑拼接!MAGI-1:开源自回归视频生成模型,支持一镜到底的长视频生成
|
数据采集 存储 缓存
【Python-Tensorflow】tf.data.Dataset的解析与使用
本文详细介绍了TensorFlow中`tf.data.Dataset`类的使用,包括创建数据集的方法(如`from_generator()`、`from_tensor_slices()`、`from_tensors()`)、数据集函数(如`apply()`、`as_numpy_iterator()`、`batch()`、`cache()`等),以及如何通过这些函数进行高效的数据预处理和操作。
440 7
|
机器学习/深度学习 人工智能 自然语言处理
大模型的演进之路:从萌芽到ChatGPT的辉煌
大模型的演进之路:从萌芽到ChatGPT的辉煌
|
JavaScript 前端开发 C++
jupyter lab最强代码提示插件来了
jupyter lab最强代码提示插件来了
853 0
|
机器学习/深度学习 数据可视化 TensorFlow
TensorFlow 实战(七)(2)
TensorFlow 实战(七)
148 0