[英]How to handle NAs due to novel factor levels using R recipes?
我預處理了一個訓練數據集 (A),現在想使用 R 配方為測試集 (B) 重現這些步驟。
問題是,測試集中有新的因子水平,我想忽略:
library(recipes)
(A <- data.frame(a = c(1:19, NA), b = factor(c(rep("l1",18), "l2", NA))))
(B <- data.frame(a = c(1:3, NA), b = factor(c("l1", "l2", NA, "l3"))))
rec.task <-
recipe(~ ., data = A) %>%
step_unknown(all_predictors(), -all_numeric()) %>%
step_medianimpute(all_numeric()) %>%
step_other(all_predictors(), -all_numeric(), threshold = 0.1, other=".merged") %>%
step_dummy(all_predictors(), -all_numeric())
tr.recipe <- prep(rec.task, training = A)
(AA <- juice(tr.recipe))
現在的問題是下表中的 NA:
(BB <- bake(tr.recipe, B))
a b_.merged
<dbl> <dbl>
1 1 0
2 2 1
3 3 1
4 10 NA
Warnmeldung:
There are new levels in a factor: NA
我可以在這些步驟中以某種方式避免它嗎? 我可以在配方過程中將 NA 歸為零嗎(我對基本的 R 或 dplyr 解決方案不感興趣)?
step_novel()
是解決方案。 請參閱虛擬變量小插圖。
正如 topepo 所解釋的,step_novel function 是一種可能的解決方案。 通過以下方式更改分配 rec.task 的代碼
rec.task <-
recipe(~ ., data = A) %>%
step_novel(all_predictors(), -all_numeric()) %>%
step_unknown(all_predictors(), -all_numeric()) %>%
step_medianimpute(all_numeric()) %>%
step_other(all_predictors(), -all_numeric(), threshold = 0.1, other=".merged") %>%
step_dummy(all_predictors(), -all_numeric()) %>%
step_zv(all_predictors())
那么 output 將是:
# A tibble: 4 x 2
a b_.merged
<dbl> <dbl>
1 1 0
2 2 1
3 3 1
4 10 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.