首页 > 解决方案 > 为什么在使用 R 的 ROSE 包时我的数据框不被识别为一个?

问题描述

在构建二进制分类的预测模型时,我将数据分层为训练、验证和测试集。它们被放入数据框列表中,并在需要时调用。由于一个结果是少数类,我想使用 R 的 ROSE 包下的各种功能来平衡我的训练集。

但是,我想在 ROSE 提供的用于实验的不同平衡方法之间切换,而不需要在我的 R 脚本中重复大块相同的代码,因此我创建了一个函数 Balance 来执行此操作。Balance 包含一个数据框和一个键,用于在包的功能之间切换。

问题是:当我使用列表中的数据框作为输入调用 Balance 时,我收到一条错误消息,指出 as.data.frame.default 无法将类“函数”强制转换为 data.frame。我在下面提供了我的代码的简化版本。

如果有人可以看一下,我将不胜感激。我对 R 和建模也很陌生,如果有任何建议,我将不胜感激。

# make dataframe with variable and predictor columns; minority class: Predictor == 1
dataset <- as.data.frame(runif(100, min = 0, max = 100))
colnames(dataset) <- c("Var")
dataset$Predictor <- ifelse(dataset$Var < 20, 1, 0)

# stratify into train and test sets
prop <- c(train = .8, test = .2)
g <- sample(cut(
  seq(nrow(dataset)),
  nrow(dataset) * cumsum(c(0, prop)),
  labels = names(prop)))
ls <- split(dataset, g)

# balance using different functions in ROSE package
library(ROSE)
Balance <- function(df, key) {
  if (key == "under") {
    return(ovun.sample(
      Predictor ~.,
      data = df, 
      method = "under", 
      N = nrow(subset(df, Predictor == 1)) * 2)$data)
  } else if (key == "over") {
      return(ovun.sample(
        Predictor ~., 
        data = df, 
        method = "over", 
        N = nrow(subset(df, Predictor == 0)) * 2)$data)
  }
}

我确定 Balance 会根据输入键返回一个数据帧,调用 class(ls$train) 也会给出 data.frame。但:

# this gives the below error
balancedTrain <- Balance(ls$train, "under")

# Error in as.data.frame.default(data, optional = TRUE) :
# cannot coerce class '"function"' to a data.frame

# yet when ls$train is assigned to df, the object name used in Balance, it works
df <- ls$train
balancedTrain <- Balance(df, "under")

我不确定发生了什么事。有人可以帮忙吗?

标签: rerror-handlingprediction

解决方案


推荐阅读