简体   繁体   中英

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

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

You can use sklearn's StratifiedKFold , from the online docs:

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]

This will preserve your class ratios so that the splits retain the class ratios, this will work fine with pandas dfs.

As suggested by @Ali_m you could use StratifiedShuffledSplit which accepts a split ratio param:

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

would produce a 70% split.

As simple as :

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)

You can simply use the following:

But make sure that you reset stratify from None to the class labels:

"stratify : array-like or None (default is None) If not None, data is split in a stratified fashion, using this as the class labels."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM