【问题标题】:Stratified splitting of pandas dataframe into training, validation and test set将 pandas 数据帧分层拆分为训练、验证和测试集
【发布时间】:2018-11-19 17:59:34
【问题描述】:

以下极其简化的 DataFrame 代表了一个更大的包含医疗诊断的 DataFrame:

medicalData = pd.DataFrame({'diagnosis':['positive','positive','negative','negative','positive','negative','negative','negative','negative','negative']})
medicalData

    diagnosis
0   positive
1   positive
2   negative
3   negative
4   positive
5   negative
6   negative
7   negative
8   negative
9   negative

问题:对于机器学习,我需要将这个数据帧随机分成三个子帧,方法如下:

trainingDF, validationDF, testDF = SplitData(medicalData,fractions = [0.6,0.2,0.2])

...其中拆分数组指定进入每个子帧的完整数据的部分。

【问题讨论】:

  • 喜欢这个? *.com/a/24151789/4909087
  • 你知道你可以再次将测试分成两部分。
  • 谢谢,但我在问题中明确提到这些解决方案不满足我的第二个要求,即每个子集需要大致包含相同比例的正样本。

标签: python pandas dataframe machine-learning sampling


【解决方案1】:

np.array_split

如果你想推广到 n 拆分,np.array_split 是你的朋友(它适用于 DataFrames)。

fractions = np.array([0.6, 0.2, 0.2])
# shuffle your input
df = df.sample(frac=1) 
# split into 3 parts
train, val, test = np.array_split(
    df, (fractions[:-1].cumsum() * len(df)).astype(int))

train_test_split

使用train_test_split 进行分层拆分的有风解决方案。

y = df.pop('diagnosis').to_frame()
X = df

X_train, X_test, y_train, y_test = train_test_split(
        X, y,stratify=y, test_size=0.4)

X_test, X_val, y_test, y_val = train_test_split(
        X_test, y_test, stratify=y_test, test_size=0.5)

X 是您的特征的 DataFrame,y 是您的标签的单列 DataFrame。

【讨论】:

  • 谢谢,这涵盖了我的第一个要求。但是我的第二个要求是每个子集需要大约包含相同比例的正样本呢?
  • @user1934212 假设您有相同数量的样本和足够的数据,应该没问题(感谢随机性)。但是,如果您对那些东西特别感兴趣,我认为您无法使用它。也许看看 StratifiedKFold 用 sklearn 拆分。
  • 医学数据的本质是,阳性诊断通常比阴性诊断少得多。至少在我的情况下#positive/#negative == 20/80
  • 我可以将数据帧传递给 train_test_split 吗?或者根据我的代码示例,参数 X 和 y 是什么?
  • @user1934212 y 是您的标签列,X 是不包括 y 的每一列。
【解决方案2】:

pandas解决方案

以 70 / 20 / 10% 的比例分为训练 / 验证 / 测试:

train_df = df.sample(frac=0.7, random_state=random_seed)
tmp_df = df.drop(train_df.index)
test_df = tmp_df.sample(frac=0.33333, random_state=random_seed)
valid_df = tmp_df.drop(test_df.index)

assert len(df) == len(train_df) + len(valid_df) + len(test_df), "Dataset sizes don't add up"
del tmp_df

【讨论】:

  • 这不符合分层拆分的 OP 请求。
【解决方案3】:

这是一个 Python 函数,它使用分层抽样将 Pandas 数据帧拆分为训练、验证和测试数据帧。它通过调用 scikit-learn 的函数 train_test_split() 两次来执行这种拆分。

import pandas as pd
from sklearn.model_selection import train_test_split

def split_stratified_into_train_val_test(df_input, stratify_colname='y',
                                         frac_train=0.6, frac_val=0.15, frac_test=0.25,
                                         random_state=None):
    '''
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    '''

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
                         (frac_train, frac_val, frac_test))

    if stratify_colname not in df_input.columns:
        raise ValueError('%s is not a column in the dataframe' % (stratify_colname))

    X = df_input # Contains all columns.
    y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(X,
                                                          y,
                                                          stratify=y,
                                                          test_size=(1.0 - frac_train),
                                                          random_state=random_state)

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(df_temp,
                                                      y_temp,
                                                      stratify=y_temp,
                                                      test_size=relative_frac_test,
                                                      random_state=random_state)

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test

下面是一个完整的工作示例。

考虑一个数据集,该数据集具有您要在其上执行分层的标签。这个标签在原始数据集中有自己的分布,比如 75% foo、15% bar 和 10% baz。现在让我们使用 60/20/20 的比率将数据集拆分为训练、验证和测试的子集,其中每个拆分都保留相同的标签分布。见下图:

这是示例数据集:

df = pd.DataFrame( { 'A': list(range(0, 100)),
                     'B': list(range(100, 0, -1)),
                     'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )

df.head()
#    A    B label
# 0  0  100   foo
# 1  1   99   foo
# 2  2   98   foo
# 3  3   97   foo
# 4  4   96   foo

df.shape
# (100, 3)

df.label.value_counts()
# foo    75
# bar    15
# baz    10
# Name: label, dtype: int64

现在,让我们从上面调用 split_stratified_into_train_val_test() 函数,以按照 60/20/20 的比率获取训练、验证和测试数据帧。

df_train, df_val, df_test = \
    split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)

df_traindf_valdf_test 三个数据框包含所有原始行,但它们的大小将遵循上述比例。

df_train.shape
#(60, 3)

df_val.shape
#(20, 3)

df_test.shape
#(20, 3)

此外,三个拆分中的每一个都将具有相同的标签分布,即 75% foo、15% bar 和 10% baz

df_train.label.value_counts()
# foo    45
# bar     9
# baz     6
# Name: label, dtype: int64

df_val.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

df_test.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

【讨论】:

  • 这个函数返回如下错误 ValueError: The minimum population class in y has only 1 member, 太少了。任何类的最小组数不能小于 2。 value_counts() Skyra_0 105 Skyra_2 37 Skyra_1 29 Skyra_3 18 TrioTim_4 7 Skyra_4 5 TrioTim_2 5 TrioTim_5 5 Skyra_5 5 TrioTim_3 3