【问题标题】:How to solve this error when applying SMOTE in R?在 R 中应用 SMOTE 时如何解决此错误?
【发布时间】:2021-09-27 04:10:44
【问题描述】:

我正在尝试使用以下代码将 smote 应用于我的数据集

dataset$target<- as.factor(dataset$target)
dataset <- SMOTE(target~ ., dataset, perc.over = 100, perc.under=200)
dataset$target <- as.numeric(dataset$target)

但我收到以下错误。

Warning message in smote.exs(data[minExs, ], ncol(data), perc.over, k):
“NAs introduced by coercion”
Warning message in smote.exs(data[minExs, ], ncol(data), perc.over, k):
“NAs introduced by coercion”
Warning message in smote.exs(data[minExs, ], ncol(data), perc.over, k):
“NAs introduced by coercion”
Error in factor(newCases[, a], levels = 1:nlevels(data[, a]), labels = levels(data[, : invalid 'labels'; length 0 should be 1 or 2
Traceback:

1. SMOTE(target ~ ., dataset, perc.over = 100, perc.under = 200)
2. smote.exs(data[minExs, ], ncol(data), perc.over, k)
3. factor(newCases[, a], levels = 1:nlevels(data[, a]), labels = levels(data[, 
 .     a]))
4. stop(gettextf("invalid 'labels'; length %d should be 1 or %d", 
 .     nlab, length(levels)), domain = NA)

目标列包含0和1

str(dataset$target)

它返回以下输出

 Factor w/ 2 levels "0","1": 1 1 2 2 1 1 1 1 1 1 ...

我可以知道这里有什么问题吗?我无法理解错误消息。

【问题讨论】:

  • 如果您可以将示例数据集提供给dput(),将会很有帮助。这样这个问题就可以被复制,我们可以帮助你。
  • 其实数据集在这里:kaggle.com/ealaxi/paysim1,目标列是isFraud列

标签: r smote


【解决方案1】:

我认为这取决于您的数据框中的 character 列。 SMOTE 不知道如何根据您的数据集生成新的角色观察。一种可能的解决方案是删除character 列。

library(data.table)
library(DMwR)
dataset <- fread("D:/archive/df.csv")
set.seed(4)
#sampling 10000 rows just for computational reasons
dataset <- dataset[sample(1:nrow(dataset),10000),]
dataset <- as.data.frame(dataset)
dataset$isFraud<- factor(dataset$isFraud)
table(dataset$isFraud)
str(dataset)
#drop the character column
dataset <- dataset[,!sapply(dataset, is.character)]
new.dataset <- SMOTE(isFraud ~ ., dataset, perc.over = 100, perc.under=200)
table(new.dataset$isFraud)

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2021-10-20
    • 2019-08-07
    • 2021-04-03
    相关资源
    最近更新 更多