将数据集拆分为训练和测试数据,保持比例

Splitting data set into training and test data, keeping the ratio

我有 Iris 数据集(可在此处找到:https://www.kaggle.com/uciml/iris),我应该将其分成测试集和训练集。但是,我需要拆分它,以便训练和测试集中的 class 分布与完整数据集中的分布相同。

我看到了这个问题的最佳答案: 但由于我对数据科学和 python 都是新手,所以我很迷茫。

对于 Iris 数据集,前 50 行是一种花,接下来的 50 行是第二种花,最后 50 行是第三种花。我该如何写才能得到例如。每三分之一的 50% 测试数据?在上面链接的问题中,我真的无法理解他们在哪里以及如何做到这一点。如果您能像对 child 那样解释这一点,我将不胜感激。

x_train 是否代表了花的 4 个不同特征以及 y_train 我们拥有的花的种类?

提前致谢!

编辑:我试过了

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=65)

但这样做公平吗?我选择了不同数量的随机状态,直到我在测试和训练集中得到了每种花类型的 25 个(它总是在 1/3 左右,但我得到了 65 个)。这感觉有点像作弊......

你可以在这里使用StratifiedKFold: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html

另外,train_test_split 有 stratify 参数: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html#sklearn.model_selection.train_test_split

如果您需要举例说明,请联系我。

sklearn.model_selection.train_test_split

shufflestratify 个参数。

默认 shuffle = Truestratify=None

如果您正在处理回归,train_test_split 默认情况下会为您打乱数据。

如果是处理分类,需要指定stratify = << your response variable >>

更多信息请查看documentation

谢谢