Skip to content

confusion between metric name and metric type #1120

@topepo

Description

@topepo

For custom metrics, tune doesn't work well, mostly because it can't differentiate between the metric type and the name.

library(tidymodels)

set.seed(1)
rs <- vfold_cv(two_class_dat)
custom_cost <- function(
  data,
  truth,
  ...,
  na_rm = TRUE,
  event_level = "Class1",
  case_weights = NULL
) {
  custom_cost_vals <- tibble::tribble(
    ~truth   , ~estimate , ~cost ,
    "Class1" , "Class2"  ,    10 ,
    "Class2" , "Class1"  ,     2
  )

  classification_cost(
    data = data,
    truth = !!rlang::enquo(truth),
    ...,
    na_rm = na_rm,
    costs = custom_cost_vals
  )
}

custom_cost <- new_prob_metric(custom_cost, "minimize")

cls_mtr <- metric_set(custom_cost, accuracy, roc_auc)
cart_wflow <- workflow(
  Class ~ .,
  decision_tree(min_n = tune(), mode = "classification")
)

set.seed(2)
res <-
  cart_wflow |>
  tune_grid(resamples = rs, metrics = cls_mtr)
# Errors in finding the metric: 

select_best(res)
#> Warning in select_best(res): No value of `metric` was given; "custom_cost" will
#> be used.
#> Error in `.filter_perf_metrics()`:
#> ! No results are available. Please use `collect_metrics()` to see if
#>   there were any issues.
autoplot(res)

# This works though:
.get_tune_metric_names(res)
#> [1] "custom_cost" "accuracy"    "roc_auc"

# The .metric value is "classification_cost": 
res |> collect_metrics() |> count(.metric)
#> # A tibble: 3 × 2
#>   .metric                 n
#>   <chr>               <int>
#> 1 accuracy               10
#> 2 classification_cost    10
#> 3 roc_auc                10
# When subsetting, it looks for `metric = "custom_cost"` but the data has
# a `.metric` value of "classification_cost" 

set.seed(2)
res_bayz <-
  cart_wflow |>
  tune_bayes(resamples = rs, metrics = cls_mtr)
#> → A | error:   subscript out of bounds
#> There were issues with some computations   A: x1
#> Error in `check_gp_failure()`:
#> ! Gaussian process model was not fit.
#> ✖ Optimization stopped prematurely; returning current results.
#> There were issues with some computations   A: x1There were issues with some computations   A: x1

Created on 2026-01-12 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions