【问题标题】:How do I split my data set between training and testing sets while keeping the ratio of the target variable in both sets?如何在训练集和测试集之间拆分数据集,同时保持两组中目标变量的比率?
【发布时间】:2018-07-28 10:26:47
【问题描述】:

我有一个数据集,我打算在 training settesting set 之间拆分,以便使用 R 进行 machine learning 分析。

假设我的数据集(称为MyDataset)基于目标变量(称为Leaver)具有是(60%)和否(40%)的比率,我如何确保我的拆分将保持这一点训练集和测试集的比例?

【问题讨论】:

    标签: r machine-learning training-data


    【解决方案1】:

    您要做的是对数据集进行分层拆分。您可以使用 caret 包中的 createDataPartition 执行此操作。只需确保将您的 Leaver 变量设置为一个因素。

    请参阅下面的代码示例。

    library(caret)
    data(GermanCredit)
    
    prop.table(table(GermanCredit$Class))
     Bad Good 
     0.3  0.7 
    index <- createDataPartition(GermanCredit$Class, p = 0.6, list = FALSE)
    
    # train
    prop.table(table(GermanCredit$Class[index]))
     Bad Good 
     0.3  0.7 
    #test
    prop.table(table(GermanCredit$Class[-index]))
     Bad Good 
     0.3  0.7 
    

    【讨论】:

      【解决方案2】:

      无包装:

      GermanCredit$id<-1:dim(GermanCredit)[1]
      
      bad_id<-sample(GermanCredit$id[GermanCredit$Class=="Bad"],0.6*.3*300)
      good_id<-sample(GermanCredit$id[GermanCredit$Class=="Good"],0.6*.7*300)
      
      train_index<-sample(c(bad_id,good_id))
      #train set
      prop.table(table(GermanCredit$Class[train_index]))
      Bad Good 
      0.3  0.7 
      
      #test
      prop.table(table(GermanCredit$Class[-train_index]))
      Bad Good 
      0.3  0.7 
      

      【讨论】:

        猜你喜欢
        • 2020-09-29
        • 2015-05-18
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 2019-05-01
        相关资源
        最近更新 更多