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

Split into training and testing set in R?

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

X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.2, random_state=42)   

按 80/20 的比例分成训练集和测试集。

您可以使用 caretcreateDataPartition 函数执行此操作:

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 = sample(1:length(y), ceiling(length(y) * 0.2))

创建 test_inds 'from scratch'

可能是更简单的方法

#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)

使用 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]

让我们使用 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, ]