Пишу проект на Tidymodels
. Я создал набор train
и test
, разложил recipe
и model
. Когда я вызываю workflow()
, добавляю recipe
и model
, затем вызываю fit(data = df_train
, я получаю следующую ошибку.
Error:
! Can't use NA as column index with `[` at positions 3 and 4.
Я использую R версии 4.1.3 и R Studio 2022.02.0 Build 443.
Для воспроизводимости вот рабочий процесс. Обратите внимание, что данные находятся на GitHub, поэтому для загрузки данных вам потребуется подключение к Интернету.
## Load package manager
if (!require(pacman)){
install.packages("pacman")
}
## Load required packages. Download them if they do not exist in my system.
pacman::p_load(tidyverse, kableExtra, skimr, knitr, glue, GGally,
corrplot, tidymodels, themis, stargazer, rpart, rpart.plot,
vip, patchwork, data.table)
Следующим шагом будет загрузка данных.
df <- fread('https://raw.githubusercontent.com/Karuitha/data_projects/master/employee_turnover/data/employee_churn_data.csv') %>%
mutate(left = factor(left, levels = c("yes", "no")))
Затем я разделяю данные на обучающий и тестовый наборы и создаю рецепт.
## Create a split object consisting 75% of data
split_object <- initial_split(df, prop = 0.75,
strata = left)
## Generate the training set
df_train <- split_object %>%
training()
## Generate the testing set
df_test <- split_object %>%
testing()
###############################################
## Create a recipe
df_recipe <- recipes::recipe(left ~ .,
data = df_train) %>%
##We upsample the data to balance the outcome variable
themis::step_upsample(left,
over_ratio = 1,
seed = 500) %>%
##We make all character variables factors
step_string2factor(all_nominal_predictors()) %>%
##We remove one in a pair of highly correlated variables
## The threshold for removal is 0.85 (absolute)
## The choice of threshold is subjective.
step_corr(all_numeric_predictors(),
threshold = 0.85) %>%
## Train these steps on the training data
prep(training = df_train)
Затем я определяю модель и пытаюсь подогнать ее.
## Define a logistic model
logistic_model <- logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
Тогда подгоните.
workflow() %>%
add_recipe(df_recipe) %>%
add_model(logistic_model) %>%
fit(data = df_train)
Вот где я получаю ошибку
Error:
! Can't use NA as column index with `[` at positions 3 and 4.
Я проверял и перепроверял. Любая помощь приветствуется.
Я отвечаю на свой собственный вопрос.
Я понял одну вещь: проблема в шаге recipe
. Когда я заменяю step_str2factor
на step_dummy
, все работает нормально.
Я до сих пор не знаю, почему это так. Может быть, мне нужно будет изучить Tidymodels более пристально!!
В df_recipe
удалите prep(training = df_train)
, т.е. определите его так:
## Create a recipe
df_recipe <- recipes::recipe(left ~ .,
data = df_train) %>%
##We upsample the data to balance the outcome variable
themis::step_upsample(left,
over_ratio = 1,
seed = 500) %>%
##We make all character variables factors
step_string2factor(all_nominal_predictors()) %>%
##We remove one in a pair of highly correlated variables
## The threshold for removal is 0.85 (absolute)
## The choice of threshold is subjective.
step_corr(all_numeric_predictors(),
threshold = 0.85)
Удаление prep()
не привело к ошибкам при запуске fit(). Я считаю, что prep()
здесь не нужен, потому что workflow()
делает то же самое.
Из справочного сообщения ?workflow
:
When you specify and fit a model with a workflow(), parsnip and workflows match and reproduce the underlying behavior of the user-specified model’s computational engine.
От ?prep()
:
If you are using a recipe as a preprocessor for modeling, we highly recommend that you use a workflow() instead of manually estimating a recipe (see the example in recipe()).
Когда вы должны использовать prep()
тогда? По моему опыту, это полезно, когда вы хотите получить представление о том, как ваши данные будут выглядеть после обработки:
#how training data will look like after your recipe steps are applied
df_recipe %>%
prep() %>%
bake(new_data = NULL)
# A tibble: 10,134 x 9
department promoted review projects salary tenure satisfaction bonus left
<fct> <int> <dbl> <int> <fct> <dbl> <dbl> <int> <fct>
1 operations 0 0.578 3 low 5 0.627 0 no
2 sales 0 0.676 3 high 5 0.578 1 no
3 admin 0 0.620 4 high 5 0.687 0 no
4 sales 0 0.653 4 low 6 0.679 0 no
5 sales 0 0.642 3 medium 6 0.623 0 no
6 support 0 0.563 4 medium 5 0.559 0 no
7 engineering 0 0.799 3 medium 5 0.433 1 no
8 marketing 0 0.611 3 low 6 0.502 0 no
9 sales 0 0.567 3 medium 6 0.845 0 no
10 finance 0 0.583 3 medium 6 0.608 0 no
# ... with 10,124 more rows
Спасибо, Десмонд, что нашел время ответить. Я ценю. Я принял это к сведению.