You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tidymodels中使用classification_cost和自定义成本矩阵调参报错如何解决

问题根因

tune_grid调用自定义概率指标时,会自动传入estimator和event_level两个yardstick标准参数,你最初定义的自定义函数没有预留这两个参数的接收位,就会触发「未使用参数」的报错。你提到的yardstick_event_level()是yardstick包内置的上下文辅助函数,不需要用户手动调用,只需将参数透传给内部的classification_cost即可。

修复方案

只需修改自定义指标函数的定义,增加两个标准参数并透传到内部调用即可,修改后的完整代码如下:

library(tidymodels)

# 加载示例数据
data("two_class_example")
data("two_class_dat")

# 修复后的自定义惩罚型分类成本指标
classification_cost_penalized <- function(
  data,
  truth,
  class_prob, # 统一参数名,避免调用时匹配错误
  na_rm = TRUE,
  # 新增tune_grid自动传入的两个标准参数
  estimator = NULL,
  event_level = "first"
) {
  
  # 自定义成本矩阵:假阴性(Class1预测为Class2)惩罚为假阳性的2倍
  cost_matrix <- tribble(
    ~truth, ~estimate, ~cost,
    "Class1", "Class2",  2,
    "Class2", "Class1",  1
  )
  
  classification_cost(
    data = data,
    truth = !! rlang::enquo(truth),
    !! rlang::enquo(class_prob), 
    costs = cost_matrix,
    na_rm = na_rm,
    # 透传标准参数到内置指标
    estimator = estimator,
    event_level = event_level
  )
}

# 注册为概率型指标,优化方向为最小化
classification_cost_penalized <- new_prob_metric(
  classification_cost_penalized, 
  direction = "minimize"
)

# 单测验证
two_class_example %>% 
  classification_cost_penalized(truth = truth, class_prob = Class1)

# 调参流程(原有代码无需修改)
my_model <- 
  rand_forest(mtry = tune(), 
              min_n = tune(),
              trees = 500) %>% 
  set_engine("ranger") %>% 
  set_mode("classification")

my_recipe <- recipe(Class ~ A + B, data = two_class_dat)

my_wf <- workflow() %>% 
  add_model(my_model) %>% 
  add_recipe(my_recipe)

tuned_rf <- my_wf %>% 
  tune_grid(
    resamples = vfold_cv(two_class_dat, v = 5),
    grid = 5,
    metrics = metric_set(classification_cost_penalized)
  )
补充说明
  • 如果你的正例是分类因子的第二个水平,只需将event_level的默认值改为"second"即可
  • 所有自定义yardstick指标都需要预留estimator和event_level两个参数,才能适配tidymodels的调参流程

内容的提问来源于stack exchange,提问作者O René

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:45:04