分成R中的训练和测试集?

时间:2017-11-09 19:57:20

标签: python r machine-learning data-science training-data

如何将python中的以下编写代码写入R?

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
分为训练和测试组80/20比率 如果你们中的任何一个人能弄明白这件事,那将是一个很大的帮助。

4 个答案:

答案 0 :(得分:4)

可能是最简单的方法

#read in iris dataset 
 data(iris)  
 library(caret) #this package has the createDataPartition function

 set.seed(123) #randomization`

 #creating indices
 trainIndex <- createDataPartition(iris$Species,p=0.75,list=FALSE)

 #splitting data into training/testing data using the trainIndex object
 IRIS_TRAIN <- iris[trainIndex,] #training data (75% of data)

 IRIS_TEST <- iris[-trainIndex,] #testing data (25% of data)

答案 1 :(得分:1)

您可以使用caret createDataPartition功能

执行此操作
library(caret)

# Make example data
X = data.frame(matrix(rnorm(200), nrow = 100)) 
y = rnorm(100) 

#Extract random sample of indices for test data
set.seed(42) #equivalent to python's random_state arg
test_inds = createDataPartition(y = 1:length(y), p = 0.2, list = F) 

# Split data into test/train using indices
X_test = X[test_inds, ]; y_test = y[test_inds] 
X_train = X[-test_inds, ]; y_train = y[-test_inds]

您还可以从头开始创建test_inds&#39;使用test_inds = sample(1:length(y), ceiling(length(y) * 0.2))

答案 2 :(得分:1)

使用base R可以执行以下操作:

set.seed(12345)
#getting training data set sizes of .20 (in this case 20 out of 100)
train.x<-sample(1:100, 20)
train.y<-sample(1:100, 20)

#simulating random data
x<-rnorm(100)
y<-rnorm(100)

#sub-setting the x data
training.x.data<-x[train]
testing.x.data<-x[-train]

#sub-setting the y data
training.y.data<-y[train]
testing.y.data<-y[-train]

答案 3 :(得分:0)

让我们来研究iris数据集:

# in case you want to use a seed
set.seed(5)
## 70% of the sample size
train_size <- floor(0.75 * nrow(iris))

in_rows <- sample(c(1:nrow(iris)), size = train_size, replace = FALSE)

train <- iris[in_rows, ]
test <- iris[-in_rows, ]