将 NumPy 数组随机拆分为训练和测试/验证数据集的好方法是什么?类似于 Matlab 中的 cvpartition
或 crossvalind
函数。
最佳答案
如果要将数据集一分为二,可以使用numpy.random.shuffle
,如果需要保留numpy.random.permutation
跟踪索引(请记住修复随机种子以使所有内容可重现):
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]
或
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]
There are many ways other ways重复划分相同的数据集以进行交叉验证。其中许多是available in the sklearn
library (k 折,留出,...)。 sklearn
还包括更高级的"stratified sampling"方法创建一个关于某些特征平衡的数据分区,例如确保在训练和测试集中有相同比例的正例和负例。
关于python - 如何将数据集拆分/分区为训练和测试数据集,例如交叉验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3674409/