如何将数据集拆分为训练集和验证集,保持比率在 类 之间?

how to split a dataset into training and validation set keeping ratio between classes?

我有一个多 class class 化问题,我的数据集是倾斜的,我有 100 个特定 class 的实例,并说 10 个不同的 class ,所以我想在 classes 之间拆分我的数据集保持率,如果我有 100 个特定 class 的实例,并且我希望 30% 的记录进入训练集中,我希望有 30我的 100 条记录的实例代表 class,我的 10 条记录的 3 个实例代表 class 等等。

您可以使用在线文档中的 sklearn StratifiedKFold

Stratified K-Folds cross validation iterator

Provides train/test indices to split data in train test sets.

This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class.

>>> from sklearn import cross_validation
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> skf = cross_validation.StratifiedKFold(y, n_folds=2)
>>> len(skf)
2
>>> print(skf)  
sklearn.cross_validation.StratifiedKFold(labels=[0 0 1 1], n_folds=2,
                                         shuffle=False, random_state=None)
>>> for train_index, test_index in skf:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]

这将保留您的 class 比率,以便拆分保留 class 比率,这将适用于 pandas dfs。

如@Ali_m 所建议,您可以使用 StratifiedShuffledSplit 接受分流比参数:

sss = StratifiedShuffleSplit(y, 3, test_size=0.7, random_state=0)

会产生 70% 的拆分。

简单到:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                stratify=y, 
                                                test_size=0.25)