Olá
Alguém sabe como customizar a função de sumarização para a modelagem?
Utilizando tidymodels, na preparação do fit temos: “metric_set()”. Gostaria de utilizar uma função de avaliação customizada. Alguém já fez isso? Estou em dúvida se o caminho é via yardstick ou outro.
Desde já, obrigada!
Athos
Julho 1, 2021, 7:43pm
2
@talitalobo fiquei chocado com a complexidade de criar uma metrica customizada, mas segue o passo a passo rs
library(magrittr)
library(rlang)
#>
#> Attaching package: 'rlang'
#> The following object is masked from 'package:magrittr':
#>
#> set_names
library(yardstick)
#> For binary classification, the first factor level is assumed to be the event.
#> Use the argument `event_level = "second"` to alter this as needed.
minha_metrica_vec <- function(truth, estimate, na_rm = TRUE, ...) {
minha_metrica_impl <- function(truth, estimate) {
mean((truth - estimate) ^ 2) # <------ aqui que mexe na conta da métrica
}
metric_vec_template(
metric_impl = minha_metrica_impl,
truth = truth,
estimate = estimate,
na_rm = na_rm,
cls = "numeric",
...
)
}
minha_metrica <- function(data, ...) {
UseMethod("minha_metrica")
}
minha_metrica <- new_numeric_metric(minha_metrica, direction = "minimize")
minha_metrica.data.frame <- function(data, truth, estimate, na_rm = TRUE, ...) {
metric_summarizer(
metric_nm = "minha_metrica",
metric_fn = minha_metrica_vec,
data = data,
truth = !! enquo(truth),
estimate = !! enquo(estimate),
na_rm = na_rm,
...
)
}
mtcars[1:3, ] %>% rmse(mpg, vs)
#> # A tibble: 1 x 3
#> .metric .estimator .estimate
#> <chr> <chr> <dbl>
#> 1 rmse standard 21.3
mtcars[1:3, ] %>% minha_metrica(mpg, vs)
#> # A tibble: 1 x 3
#> .metric .estimator .estimate
#> <chr> <chr> <dbl>
#> 1 minha_metrica standard 452.
r <- rsample::initial_split(mtcars)
m <- parsnip::linear_reg("regression") %>% parsnip::set_engine("lm")
f <- tune::last_fit(m, mpg ~ ., r, metrics = yardstick::metric_set(rmse, minha_metrica))
#> Registered S3 method overwritten by 'tune':
#> method from
#> required_pkgs.model_spec parsnip
collect_metrics(f)
#> # A tibble: 2 x 4
#> .metric .estimator .estimate .config
#> <chr> <chr> <dbl> <chr>
#> 1 rmse standard 3.44 Preprocessor1_Model1
#> 2 minha_metrica standard 11.8 Preprocessor1_Model1
Created on 2021-07-01 by the reprex package (v2.0.0)
1 curtida