使用指示 R 中的观察的变量创建折叠
create folds with variable indicating an observation in R
我正在使用 R 分析一些数据,我需要创建折叠以进行交叉验证。一个观察结果由几行组成,因此我不能简单地使用(例如)CreateFolds 函数。我有一个变量指示哪一行属于哪个主题,所以我想我需要使用它来创建折叠。
我该怎么做?
示例:
indicator var1 var2 var3 y
1 2 2 3 10
1 2 3 3 10
2 2 1 1 4
2 1 2 2 4
该指标表明是同题
我想我明白了!如果您执行以下操作,它不会分隔指示符
指示的行
# get the levels of the indicator
d$indicator <- as.factor(d$indicator)
indicatorlevels <- levels(d$indicator)
# create folds with these levels
library(caTools)
set.seed(1)
folds <- sample.split(indicatorlevels, SplitRatio = 0.8)
# select test ans training vacancies
training.indicator <- subset(indicatorlevels, folds == TRUE)
test.indicator <- subset(indicatorlevels, folds == FALSE)
# create test and training dataset
train <- d[d$indicator %in% training.indicator,]
test <- d[d$indicator %in% test.indicator,]
有人知道更优雅的方法吗?
如果你有 data.frame
并且你想做一个 K 交叉验证,你可以做
library(dplyr)
mutate(df, fold = sample(rep_len(1:K, n_distinct(indicator)))[indicator])
我正在使用 R 分析一些数据,我需要创建折叠以进行交叉验证。一个观察结果由几行组成,因此我不能简单地使用(例如)CreateFolds 函数。我有一个变量指示哪一行属于哪个主题,所以我想我需要使用它来创建折叠。
我该怎么做?
示例:
indicator var1 var2 var3 y
1 2 2 3 10
1 2 3 3 10
2 2 1 1 4
2 1 2 2 4
该指标表明是同题
我想我明白了!如果您执行以下操作,它不会分隔指示符
指示的行# get the levels of the indicator
d$indicator <- as.factor(d$indicator)
indicatorlevels <- levels(d$indicator)
# create folds with these levels
library(caTools)
set.seed(1)
folds <- sample.split(indicatorlevels, SplitRatio = 0.8)
# select test ans training vacancies
training.indicator <- subset(indicatorlevels, folds == TRUE)
test.indicator <- subset(indicatorlevels, folds == FALSE)
# create test and training dataset
train <- d[d$indicator %in% training.indicator,]
test <- d[d$indicator %in% test.indicator,]
有人知道更优雅的方法吗?
如果你有 data.frame
并且你想做一个 K 交叉验证,你可以做
library(dplyr)
mutate(df, fold = sample(rep_len(1:K, n_distinct(indicator)))[indicator])