【问题标题】:Splitting data 80/20 per class每类拆分数据 80/20
【发布时间】:2021-04-14 11:24:25
【问题描述】:

在将我的数据拆分为 80/20 训练/验证集时,我正在寻求在各种数据集中平均分布我的样本。我不想随机进行,因为我需要在两组中平均分配样本并避免产生偏差。但是,我想确保对于每个类别的标签,80% 的样本都在训练集中。

有了这个,我想尝试在 R 的 caret 包中执行此操作,例如:

data_split <- createDataPartition(y=data$column, p=0.8, list=F) #splits data
training <- data[data_split,] #call training data
testing <- data[-data_split,] #call testing or validation data

例如我有 64 个班级,并且正在考虑对每个班级进行随机数据分区。

这是正确的吗?

【问题讨论】:

  • 您发布的代码中的类分布如何?

标签: r machine-learning r-caret


【解决方案1】:

如果我正确理解了您想要什么,那么您做得很好。 createDataPartition 函数正好适用于这种情况。它根据vignette 上报告的结果执行简单的拆分

随机抽样发生在每个类中,应保留数据的整体类分布

我们可以用一个简单的情节检查是否为真

library(caret)
library(ggplot2)
set.seed(5)
df <- 
data.frame(a=runif(1000),b=runif(1000)*10,c=sample(as.character(1:64),1000,replace = 
T))
str(df)
#split the data in 80/20 train/test
ind <- createDataPartition(df$c, p=0.8,list = F)
train <- df[ind,]
test <- df[-ind,]
#frequencies of each class for the whole dataset
x <- table(df$c)/length(df$c)
#for the training set
x_train <- table(train$c)/length(train$c)
#for the testing set
x_test<- table(test$c)/length(test$c)

freq <- data.frame(class=names(x),df=as.numeric(x),train=as.numeric(x_train),test=as.numeric(x_test))


ggplot(freq,aes(x=class))+
geom_line(aes(y=df,group=1),col="red")+
geom_line(aes(y=train,group=1),col="green")+
geom_line(aes(y=test,group=1),col="blue")+
ylab("frequencies")

如你所见,每个类的分布都被保留了

【讨论】:

  • 嘿,Elia,这绝对回答了我正在寻找的东西。感谢您的出色输入,我已经对其进行了测试,它确实有效:D
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2019-02-16
相关资源
最近更新 更多