在R的tidymodels中自定义G-mean评估指标失败,求排查错误
修复tidymodels自定义G-mean指标的问题
原代码的核心问题
- 函数名不匹配:定义了
g_mean_rate_impl但未使用,反而在metric_vec_template中调用不存在的g_mean_impl,导致函数找不到 - 核心计算缺失:直接写
sqrt(sensitivity * specificity)但未实际计算这两个指标,没有基于输入的truth和estimate生成对应数值 - 未调用官方指标函数:没有借助yardstick包的向量版指标函数来正确计算敏感度和特异度
修复后的完整代码
library(yardstick) library(tidyverse) # 向量版G-mean计算函数 g_mean_vec <- function(truth, estimate, estimator = NULL, na_rm = TRUE, event_level = "first", ...) { # 自动确定评估器类型(二分类/多分类) estimator <- finalize_estimator(truth, estimator) # 核心计算逻辑 g_mean_impl <- function(truth, estimate) { # 调用yardstick内置函数计算敏感度和特异度 sens <- sensitivity_vec(truth, estimate, event_level = event_level) spec <- specificity_vec(truth, estimate, event_level = event_level) # 计算G-mean sqrt(sens * spec) } # 使用框架模板封装指标函数 metric_vec_template( metric_impl = g_mean_impl, truth = truth, estimate = estimate, na_rm = na_rm, cls = "factor", estimator = estimator, ... ) } # 创建分类指标对象,指定方向为最大化(G-mean越高越好) g_mean <- new_class_metric(g_mean, direction = "maximize") # 数据框接口函数 g_mean.data.frame <- function(data, truth, estimate, na_rm = TRUE, ...) { metric_summarizer( metric_nm = "g_mean", metric_fn = g_mean_vec, data = data, truth = !!enquo(truth), estimate = !!enquo(estimate), na_rm = na_rm, ... ) }
测试代码
用yardstick内置的二分类数据集验证功能:
# 加载测试数据 data(two_class_example) # 计算G-mean g_mean(two_class_example, truth = truth, estimate = predicted) # 管道式调用 two_class_example %>% g_mean(truth, predicted)
注意事项
- 确保提前加载
yardstick和tidymodels相关依赖包 - G-mean默认适用于二分类场景,若需支持多分类,需扩展
g_mean_impl中的计算逻辑(如macro/micro平均) event_level参数控制正样本类别位置,保持和其他指标设置一致即可
内容的提问来源于stack exchange,提问作者JorRu
相关产品推荐
相关产品推荐

