如何在火车中重复少数族裔的行?

时间:2018-10-22 07:00:27

标签: r machine-learning classification repeat sampling

我想在我的火车上重复少数班的特定行。我知道,这不是一种非常理想的工作方式,但我只想尝试一下。

假设我有这个数据框:

> df

    group     type  number
1   class1     one    4
2   class1   three   10
3   class1    nine    3
4   class4   seven    9
5   class1   eight    4
6   class1     ten    2
7   class1     two   22
8   class4  eleven    8

现在,我要重复少数类(class4)的行,以至于在新数据框中有50%的class1和50%的class4。

我知道有功能 rep ,但是我只能找到重复整个数据框的解决方案。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

Base R方法

#Count frequency of groups
tab <- table(df$group)

#Count number of rows to be added
no_of_rows <- max(tab) - min(tab)

#count number of rows which are already there in the dataframe for the minimum group
existing_rows <- which(df$group %in% names(which.min(tab)))

#Add new rows
new_df <- rbind(df, df[rep(existing_rows,no_of_rows/length(existing_rows)), ])

#Check the count
table(new_df$group)

#class1 class4 
#     6      6 

答案 1 :(得分:1)

这里是使用tidyverse

的选项
library(tidyverse)
n1 <- df %>% 
        count(group) %>% 
        slice(which.max(n)) %>%
        pull(n) 
df %>%
   filter(group == "class4") %>%
   mutate(n = n1/2) %>% 
   uncount(n) %>%
   bind_rows(filter(df, group == "class1"))
#    group   type number
#1  class4  seven      9
#2  class4  seven      9
#3  class4  seven      9
#4  class4 eleven      8
#5  class4 eleven      8
#6  class4 eleven      8
#7  class1    one      4
#8  class1  three     10
#9  class1   nine      3
#10 class1  eight      4
#11 class1    ten      2
#12 class1    two     22

答案 2 :(得分:1)

我建议您使用“综合少数群体过采样技术( SMOTE )”(Chawla等,2002)或“随机过采样示例( ROSE )” (Menardi和Torelli,2013年)。

1),您可以通过在sampling=中添加trainControl来调整每个交叉验证折叠中的样本。

例如:

trainControl(method = "repeatedcv", 
                     number = 10, 
                     repeats = 10, 
                     sampling = "up")

2),或者在训练之前通过调用 SMOTE ROSE 函数来调整采样。

library("DMwR") #for smote
library("ROSE")

dat <- iris[1:70,]
dat$Species <- factor(dat$Species)

table(dat$Species) #class imbalances

setosa versicolor 
    50         20     

set.seed(100)
smote_train <- SMOTE(Species ~ ., data  = dat)                         
table(smote_train$Species)

setosa versicolor 
    80         60 


set.seed(100)
rose_train <- ROSE(Species ~ ., data  = dat)$data    
table(rose_train$Species)


setosa versicolor 
    37         33