如何在训练集和测试集之间拆分我的数据集,同时保持两组中目标变量的比率?

How do I split my data set between training and testing sets while keeping the ratio of the target variable in both sets?

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

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

您要做的是对数据集进行分层拆分。您可以使用 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 

没有包裹:

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