如何将数据划分为3个集合(训练集、验证集和测试集)?

17 浏览
0 Comments

如何将数据划分为3个集合(训练集、验证集和测试集)?

我有一个pandas数据框,我希望将它分成3个独立的集合。 我知道可以使用sklearn.cross_validation中的train_test_split,将数据分成两个集合(训练集和测试集)。 但是,我找不到将数据分成三个集合的任何解决方案。 最好能够得到原始数据的索引。

我知道一种解决方法是使用train_test_split两次,并以某种方式调整索引。 但是,有没有更标准/内置的方法将数据分成三个集合,而不是两个集合?

admin 更改状态以发布 2023年5月21日
0
0 Comments

然而,将数据集划分为traintestcv的一种方法是使用train_test_split方法两次来划分为0.60.20.2

from sklearn.model_selection import train_test_split
x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

0
0 Comments

Numpy解决方案。我们将首先对整个数据集进行洗牌(df.sample(frac=1, random_state=42)),然后将数据集分为以下部分:

  • 60% - 训练集,
  • 20% - 验证集,
  • 20% - 测试集。

In [305]: train, validate, test = \
              np.split(df.sample(frac=1, random_state=42), 
                       [int(.6*len(df)), int(.8*len(df))])
In [306]: train
Out[306]:
          A         B         C         D         E
0  0.046919  0.792216  0.206294  0.440346  0.038960
2  0.301010  0.625697  0.604724  0.936968  0.870064
1  0.642237  0.690403  0.813658  0.525379  0.396053
9  0.488484  0.389640  0.599637  0.122919  0.106505
8  0.842717  0.793315  0.554084  0.100361  0.367465
7  0.185214  0.603661  0.217677  0.281780  0.938540
In [307]: validate
Out[307]:
          A         B         C         D         E
5  0.806176  0.008896  0.362878  0.058903  0.026328
6  0.145777  0.485765  0.589272  0.806329  0.703479
In [308]: test
Out[308]:
          A         B         C         D         E
4  0.521640  0.332210  0.370177  0.859169  0.401087
3  0.333348  0.964011  0.083498  0.670386  0.169619

[int(.6*len(df)), int(.8*len(df))] - 是numpy.split()indices_or_sections数组。

以下是np.split()用法的小演示 - 让我们将20个元素的数组分成以下部分:80%、10%、10%:

In [45]: a = np.arange(1, 21)
In [46]: a
Out[46]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))])
Out[47]:
[array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]),
 array([17, 18]),
 array([19, 20])]

0