如何使用样本函数将数据拆分为训练/测试集

Sus*_*mby 145 r sample

我刚刚开始使用R,我不知道如何将我的数据集与以下示例代码合并:

sample(x, size, replace = FALSE, prob = NULL)
Run Code Online (Sandbox Code Playgroud)

我有一个数据集,我需要进行培训(75%)和测试(25%)设置.我不确定我应该把什么信息放入x和大小?x是数据集文件,并确定了我有多少个样本?

dic*_*koa 230

有许多方法可以实现数据分区.有关更完整的方法,请查看包中的createDataPartition函数caTools.

这是一个简单的例子:

data(mtcars)

## 75% of the sample size
smp_size <- floor(0.75 * nrow(mtcars))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(mtcars)), size = smp_size)

train <- mtcars[train_ind, ]
test <- mtcars[-train_ind, ]
Run Code Online (Sandbox Code Playgroud)

  • 不是“createDataPartition”在“caret”中而不是“caTools”中吗? (4认同)
  • 我有点困惑是什么保证此代码返回唯一的测试并训练 df?它似乎有效,不要误会我的意思。只是无法理解如何减去指数会导致独特的观察结果。例如,如果你有一个 df 有 10 行和一列,并且一列包含 1,2,3,4,5,6,7,8,9,10 并且你遵循了这个代码,是什么阻止了火车有索引 4 和测试也有 -6 -&gt; 10 - 6 = 4? (2认同)
  • 谢谢。我尝试了 `mtcars[!train_ind]`,虽然没有失败,但没有按预期工作。我如何使用`!`进行子集化? (2认同)
  • @VedaadShakib 当您使用“-”时,它会从您的数据中省略 train_ind 中的所有索引。看看 http://adv-r.had.co.nz/Subsetting.html 。希望能帮助到你 (2认同)

The*_*eMI 84

它可以通过以下方式轻松完成:

set.seed(101) # Set Seed so that same sample can be reproduced in future also
# Now Selecting 75% of data as sample from total 'n' rows of the data  
sample <- sample.int(n = nrow(data), size = floor(.75*nrow(data)), replace = F)
train <- data[sample, ]
test  <- data[-sample, ]
Run Code Online (Sandbox Code Playgroud)

通过使用caTools包:

require(caTools)
set.seed(101) 
sample = sample.split(data$anycolumn, SplitRatio = .75)
train = subset(data, sample == TRUE)
test  = subset(data, sample == FALSE)
Run Code Online (Sandbox Code Playgroud)

  • 我最近在麻省理工学院上了一门课程,他们一直使用caTools的方法.谢谢 (4认同)
  • `sample = sample.split(data[,1], SplitRatio = .75)` 应该消除命名列的需要。 (2认同)

Kat*_*ova 28

这几乎是相同的代码,但更好看

bound <- floor((nrow(df)/4)*3)         #define % of training and test set

df <- df[sample(nrow(df)), ]           #sample rows 
df.train <- df[1:bound, ]              #get training set
df.test <- df[(bound+1):nrow(df), ]    #get test set
Run Code Online (Sandbox Code Playgroud)


Edw*_*win 27

我会用dplyr它,使它变得非常简单.它确实需要在您的数据集中使用id变量,这无论如何都是一个好主意,不仅用于创建集合,还用于项目期间的可跟踪性.如果不包含它,请添加它.

mtcars$id <- 1:nrow(mtcars)
train <- mtcars %>% dplyr::sample_frac(.75)
test  <- dplyr::anti_join(mtcars, train, by = 'id')
Run Code Online (Sandbox Code Playgroud)


hyu*_*ong 21

我将把'a'分成火车(70%)和测试(30%)

    a # original data frame
    library(dplyr)
    train<-sample_frac(a, 0.7)
    sid<-as.numeric(rownames(train)) # because rownames() returns character
    test<-a[-sid,]
Run Code Online (Sandbox Code Playgroud)

DONE

  • 你需要导入dpyr包,require(dplyr) (4认同)

小智 21

library(caret)
intrain<-createDataPartition(y=sub_train$classe,p=0.7,list=FALSE)
training<-m_train[intrain,]
testing<-m_train[-intrain,]
Run Code Online (Sandbox Code Playgroud)

  • 虽然仅代码答案是一个答案,但最好提供一些解释. (3认同)

Ale*_*exG 16

我的解决方案与dickoa的解决方案基本相同,但更容易理解:

data(mtcars)
n = nrow(mtcars)
trainIndex = sample(1:n, size = round(0.7*n), replace=FALSE)
train = mtcars[trainIndex ,]
test = mtcars[-trainIndex ,]
Run Code Online (Sandbox Code Playgroud)


小智 10

我可以建议使用 rsample 包:

# choosing 75% of the data to be the training data
data_split <- initial_split(data, prop = .75)
# extracting training data and test data as two seperate dataframes
data_train <- training(data_split)
data_test  <- testing(data_split)
Run Code Online (Sandbox Code Playgroud)


Sha*_*ani 7

使用awesome dplyr库只是一种更简单,更简单的方法:

library(dplyr)
set.seed(275) #to get repeatable data

data.train <- sample_frac(Default, 0.7)

train_index <- as.numeric(rownames(data.train))
data.test <- Default[-train_index, ]
Run Code Online (Sandbox Code Playgroud)


小智 6

在浏览了此处发布的所有不同方法后,我没有看到有人使用TRUE/FALSE来选择和取消选择数据。所以我想我会分享一种利用该技术的方法。

n = nrow(dataset)
split = sample(c(TRUE, FALSE), n, replace=TRUE, prob=c(0.75, 0.25))

training = dataset[split, ]
testing = dataset[!split, ]
Run Code Online (Sandbox Code Playgroud)

解释

从 R 中选择数据的方法有多种,最常见的是人们使用正/负索引分别选择/取消选择。但是,可以通过使用TRUE/FALSE选择/取消选择来实现相同的功能。

考虑以下示例。

# let's explore ways to select every other element
data = c(1, 2, 3, 4, 5)


# using positive indices to select wanted elements
data[c(1, 3, 5)]
[1] 1 3 5

# using negative indices to remove unwanted elements
data[c(-2, -4)]
[1] 1 3 5

# using booleans to select wanted elements
data[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
[1] 1 3 5

# R recycles the TRUE/FALSE vector if it is not the correct dimension
data[c(TRUE, FALSE)]
[1] 1 3 5
Run Code Online (Sandbox Code Playgroud)


cam*_*sia 6

scorecard包有一个有用的功能,您可以在其中指定比率和种子

library(scorecard)

dt_list <- split_df(mtcars, ratio = 0.75, seed = 66)
Run Code Online (Sandbox Code Playgroud)

测试和训练数据存储在列表中,可以通过调用dt_list$train和访问dt_list$test


use*_*836 5

如果输入:

?sample
Run Code Online (Sandbox Code Playgroud)

如果将启动帮助菜单来解释样本函数的参数含义.

我不是专家,但这里有一些代码:

data <- data.frame(matrix(rnorm(400), nrow=100))
splitdata <- split(data[1:nrow(data),],sample(rep(1:4,as.integer(nrow(data)/4))))
test <- splitdata[[1]]
train <- rbind(splitdata[[1]],splitdata[[2]],splitdata[[3]])
Run Code Online (Sandbox Code Playgroud)

这将为您提供75%的火车和25%的测试.