44

我正在尝试建立一些机器学习模型,

所以我需要训练数据和验证数据

所以假设我有 N 个示例,我想在数据框中选择随机 x 个示例。

例如,假设我有 100 个示例,并且我需要 10 个随机数,有没有办法(有效地)为我生成 10 个随机 INTEGER 数来从我的样本数据中提取训练数据?

我尝试使用while循环,慢慢改变重复的数字,但运行时间不是很理想,所以我正在寻找一种更有效的方法来做到这一点。

有人可以帮忙吗?

4

3 回答 3

67

sample (or sample.int) does this:

sample.int(100, 10)
# [1] 58 83 54 68 53  4 71 11 75 90

will generate ten random numbers from the range 1–100. You probably want replace = TRUE, which samples with replacing:

sample.int(20, 10, replace = TRUE)
# [1] 10  2 11 13  9  9  3 13  3 17

More generally, sample samples n observations from a vector of arbitrary values.

于 2013-07-21T13:59:13.577 回答
3

如果我理解正确,您正在尝试创建一个保留抽样。这通常使用概率来完成。因此,如果您有n.rows样本并希望将其中的一小部分training.fraction用于训练,您可以执行以下操作:

select.training <- runif(n=n.rows) < training.fraction
data.training <- my.data[select.training, ]
data.testing <- my.data[!select.training, ]

如果您想指定确切的培训案例数量,您可以执行以下操作:

indices.training <- sample(x=seq(n.rows), size=training.size, replace=FALSE) #replace=FALSE makes sure the indices are unique
data.training <- my.data[indices.training, ]
data.testing <- my.data[-indices.training, ] #note that index negation means "take everything except for those"
于 2013-07-21T19:42:53.510 回答
0

raster包装:

raster::sampleInt(242, 10, replace = FALSE)
##  95 230 148 183  38  98 137 110 188  39

如果限制太大,这可能会失败:

sample.int(1e+12, 10)
于 2019-02-01T03:26:41.323 回答