如何将数据集划分为类之间的训练和验证集保持率? [英] how to split a dataset into training and validation set keeping ratio between classes?

查看:174
本文介绍了如何将数据集划分为类之间的训练和验证集保持率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多类分类问题,并且我的数据集存在偏差,我有100个特定类的实例,并说有10个不同类,所以如果我有100个实例,我想在各类之间分配数据集保持率某个特定的班级,我希望将30%的记录放入训练集中,我希望在那里有100个记录代表班级的30个实例和10个记录代表班级的3个实例,依此类推.

I have a multi class classification problem and my dataset is skewed, I have 100 instances of a particular class and say 10 of some different class, so I want to split my dataset keeping ratio between classes, if I have 100 instances of a particular class and I want 30% of records to go in the training set I want to have there 30 instances of my 100 record represented class and 3 instances of my 10 record represented class and so on.

推荐答案

您可以使用sklearn的

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

分层的K-folds交叉验证迭代器

Stratified K-Folds cross validation iterator

提供培训/测试 用于在火车测试集中拆分数据的索引.

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

此交叉验证对象 是KFold的变体,它返回分层的折叠.褶皱是 通过保留每个类别的样本百分比来制作.

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]

这将保留您的类别比率,以便拆分保留类别比率,这对pandas dfs可以很好地工作.

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

按照@Ali_m的建议,您可以使用 StratifiedShuffledSplit 接受拆分比率参数:

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)

将产生70%的拆分.

这篇关于如何将数据集划分为类之间的训练和验证集保持率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆