【问题标题】:Performing pairways interactions between all fields using recipes使用配方在所有字段之间执行配对交互
【发布时间】:2019-09-08 07:19:48
【问题描述】:

我正在尝试在 glmnet 模型的数据集的每个字段之间创建配对交互,而不必单独命名每个字段。但是,当它尝试自动执行此操作时,它会挂起为针对自身的 one-hot 编码分类变量的所有变体创建它们(例如,它在 Gender_Male 和 Gender_Female 之间创建一个交互列,然后可以t 找到任何值,所以整个东西都被NaNs) 填充,然后使glmnet 抛出错误。

这里有一些示例代码:

library(dplyr)
library(tidyr)
library(rsample)
library(recipes)
library(glmnet)

head(credit_data)

t <- credit_data %>%
  mutate(Status = as.character(Status)) %>%
  mutate(Status = if_else(Status == "good", 1, 0)) %>%
  drop_na()

set.seed(1234)
partitions <- initial_split(t, prop = 9/10, strata = "Status")

parsed_recipe <- recipe(Status ~ ., data = t)  %>%
  step_dummy(one_hot = TRUE, all_predictors(), -all_numeric()) %>%
  step_interact(~.:.) %>% #My attempt to apply the interaction
  step_scale(all_predictors()) %>%
  prep(training = training(partitions))

train_data <- bake(parsed_recipe, new_data = training(partitions))
test_data <- bake(parsed_recipe, new_data = testing(partitions))

fit <- train_data %>%
  select(-Status) %>%
  as.matrix() %>%
  glmnet(x = ., y = train_data$Status, family = "binomial", alpha = 0)

当我最后运行glmnet 部分时,它给了我这个错误:

Error in lognet(x, is.sparse, ix, jx, y, weights, offset, alpha, nobs,  : 
  NA/NaN/Inf in foreign function call (arg 5)

看了this的问题,我意识到数据中一定有NAs/NaNs,所以我跑了summary(train_data),结果是这样的:

所以,glmnet 不高兴也就不足为奇了,但我也不知道如何解决它。我真的不想自己手动定义每一个配对。是否有 recipes 命令可以删除包含 NaNs 的潜在预测列?

【问题讨论】:

    标签: r tidymodels


    【解决方案1】:

    我不确定这是否是一个完美(甚至好)的解决方案,但我使用答案here 来查找包含NAs 的列,然后将它们全部删除。

    所以parsed_recipe 之后的位被切换到了这个:

    interim_train <- bake(parsed_recipe, new_data = training(partitions))
    
    columns_to_remove <- colnames(interim_train)[colSums(is.na(interim_train)) > 0]
    
    train_data <- interim_train %>%
      select(-columns_to_remove)
    
    summary(train_data)
    
    test_data <- bake(parsed_recipe, new_data = testing(partitions)) %>%
      select(-columns_to_remove)
    

    到目前为止,它的表现似乎更有希望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      相关资源
      最近更新 更多