代码之家  ›  专栏  ›  技术社区  ›  user3115933

如何从不平衡数据创建新的平衡数据帧确保随机选择记录?

  •  0
  • user3115933  · 技术社区  · 7 年前

    我有一个称为 df1 它将用于 machine learning 分析。

    基于目标变量( Attrition ),数据帧 是:否的比率等于60:40

    我需要重新创建一个新的数据帧 所以Yes/No的目标变量是50:50

    我的挑战是我想把所有的记录保存在 损耗 =不(即 )在我的新数据帧中,我希望R从 损耗 df1型 .

    df2 ,我该怎么做?

    3 回复  |  直到 7 年前
        1
  •  1
  •   RLave    7 年前

    前60:40是 不是

    但您可以使用 caret 包裹:

    library(caret)
    set.seed(123)
    # this downsamples the majority class
    df2 <- downSample(x = df1[, -which(colnames(df1)=="Attrition")], 
                             y = df1$Attrition)
    
    #this upsamples the minority class
    df2 <- upSample(x = df1[, -which(colnames(df1)=="Attrition")], # supposing that Attrition is the last column in df1 
                             y = df1$Attrition)
    

    here

        2
  •  2
  •   milan    7 年前

    添加了一个示例。

    set.seed(1); df1 <- data.frame(Attrition=c(rep('No', 40), rep('Yes', 60)), val=rnorm(100))
    dfNo <- df1[df1$Attrition=='No',]
    dfYes <-  df1[df1$Attrition=='Yes',]
    dfYes <- dfYes[sample(nrow(dfYes), 40),]
    cbind(dfNo, dfYes)  
    
        3
  •  1
  •   Sal-laS    7 年前

    我希望你也考虑这个

    数据生成:

    att<-as.character( c(unlist(rep("NO",60)),unlist(rep("YES",40))))
    dt<-data.frame(ID=c(1:100),Attrition=att)
    dim(dt)
    

    得到“是”的观察结果

    YESdt<-subset(dt,Attrition=="YES",  )  # Get Yes observations
    sample(1:nrow(YESdt),nrow(dt)/10)   # Randomly select 10%
    

    将YESs更新为NOs

    YESdt[sample(1:nrow(YESdt),nrow(YESdt)/10),2]<-"NO"
    

    生成新数据集:

    NOdt<-subset(dt,Attrition=="NO",  )  # Get Yes observations
    newDT<-rbind(YESdt,NOdt)
    

    nrow(newDT)
    
    推荐文章