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

目录
相关文章
|
开发工具 Docker 容器
Docker配置阿里云加速器
Docker配置阿里云加速器
|
12月前
|
Kubernetes Cloud Native Nacos
MCP 网关实战:基于 Higress + Nacos 的零代码工具扩展方案
本文介绍一种基于开源 Higress 与 Nacos 的私有化 MCP 智能体网关架构,实现工具动态注册、Prompt 实时更新、多租户安全隔离,并支持在无外网、无 Helm 的生产环境中一键部署。
1507 25
MCP 网关实战:基于 Higress + Nacos 的零代码工具扩展方案
|
12月前
|
机器学习/深度学习 人工智能 前端开发
AI大模型爆火的SSE技术到底是什么?万字长文,一篇读懂SSE!
本文从SSE(Server-Sent Events)技术的原理到示例代码,为你通俗易懂的讲解SSE技术的方方面面。
2200 2
|
人工智能 JavaScript API
AI Agent Registry and Growth 对比各种AI Agent注册和发布的渠道生态 OpenAI Google Claude 开源工具 agtm等
本文对比了OpenAI、Google、Claude及开源平台如agtm 的AI Agent注册与发布方法,重点介绍AI Agent Registry API、社区和Marketplace三种方式,帮助开发者和产品经理提升智能体的可见性与分发渠道。
AI Agent Registry and Growth 对比各种AI Agent注册和发布的渠道生态 OpenAI Google Claude 开源工具 agtm等
|
11月前
|
IDE 安全 开发工具
告别频繁切换分支!用 Git Worktrees + Claude Code 构建高效并行开发流
本文介绍 Git Worktrees 与 Claude Code 的高效组合:用 Worktrees 创建多分支独立工作区,零拷贝、秒级切换;Claude 则在隔离环境中安全试错、并行开发。告别 stash 焦虑,实现真正并行开发流。(239字)
4568 1
|
缓存 Rust NoSQL
Higress 基于自定义插件访问 Redis
本文介绍了Higress,一个支持基于WebAssembly (WASM) 的边缘计算网关,它允许用户使用Go、C++或Rust编写插件来扩展其功能。文章特别讨论了如何利用Redis插件实现限流、缓存和会话管理等高级功能。
154482 142
|
人工智能 Java Nacos
基于 Nacos + Higress 的 MCP 开发新范式,手把手教程来了!
本文介绍了如何使用 Nacos 3.0.1 与 Higress 配合,实现 HTTP 服务转化为 MCP 协议服务,并支持自动注册与代理。通过 Docker 部署环境,结合 Spring AI Alibaba 框架,可实现服务的自动暴露和动态配置管理,适用于零改造存量应用适配 MCP 协议的场景。
4715 24