首页 > 解决方案 > 如何从 parsnip::nearest_neighbor() 中查看选定的 k

问题描述

如果我使用 拟合k最近邻模型,如果我没有指定如何调整,会选择parsnip::nearest_neighbor()什么k ?

我想弄清楚这里选择了什么k :

the_model <- nearest_neighbor() %>%
  set_engine("kknn") %>% 
  set_mode("classification") 

the_workflow <- 
  workflow() %>% 
  add_recipe(the_recipe) %>% 
  add_model(the_model) 

the_results <-
  the_workflow %>%
  fit_resamples(resamples = cv_folds, 
                metrics = metric_set(roc_auc),
                control = control_resamples(save_pred = TRUE)) 

我知道如果我使用nearest_neighbor(neighbors = tune())我可以使用k取回, select_best("roc_auc")但没有指定如何调整我得到结果但select_best()不返回k。它使用什么k值(以及你是如何找出答案的)?

标签: rknntidymodels

解决方案


如果您没有在 parsnip 中为模型规范指定参数,则该值将由底层引擎实现中的默认值确定,除非文档中另有说明。

查看文档nearest_neighbors()并继续讨论它在邻居下所说的论点

对于 kknn,如果未指定邻居,则使用值 5。

您还可以使用translate(){parsnip} 中的函数来查看模型规范创建的代码

library(parsnip)

the_model <- nearest_neighbor() %>%
  set_engine("kknn") %>% 
  set_mode("classification") 

the_model %>%
  translate()
#> K-Nearest Neighbor Model Specification (classification)
#> 
#> Computational engine: kknn 
#> 
#> Model fit template:
#> kknn::train.kknn(formula = missing_arg(), data = missing_arg(), 
#>     ks = min_rows(5, data, 5))

我们看到ks设置为 的位置min_rows(5, data, 5),如果我们neighborsnearest_neighbors()该值中指定将更改

nearest_neighbor(neighbors = 25) %>%
  set_engine("kknn") %>% 
  set_mode("classification") %>%
  translate()
#> K-Nearest Neighbor Model Specification (classification)
#> 
#> Main Arguments:
#>   neighbors = 25
#> 
#> Computational engine: kknn 
#> 
#> Model fit template:
#> kknn::train.kknn(formula = missing_arg(), data = missing_arg(), 
#>     ks = min_rows(25, data, 5))

推荐阅读