【问题标题】:Randomly divide a pandas dataframe into groups at once for x-fold crossvalidation一次将 pandas 数据帧随机分组以进行 x 折交叉验证
【发布时间】:2019-03-05 14:35:15
【问题描述】:

假设我有一个包含 500 行的数据框。我想执行 10 倍交叉验证。所以,我需要将这些数据分成 10 组,每组包含 50 行。我也想随机一次将整个数据分成 10 个组。

有没有办法使用任何库,如 pandas、numpy 等?

【问题讨论】:

    标签: python pandas dataframe machine-learning


    【解决方案1】:

    你可以使用 sklearn 的KFold:

    import numpy as np
    import pandas as pd
    from sklearn.model_selection import KFold 
    
    # create dummy dataframe with 500 rows
    features = np.random.randint(1, 100, 500)
    labels = np.random.randint(1, 100, 500)
    df = pd.DataFrame(data = {"X": features, "Y": labels})
    
    kf = KFold(n_splits=10, random_state=42, shuffle=True) # Define the split - into 10 folds 
    kf.get_n_splits(df) # returns the number of splitting iterations in the cross-validator
    print(kf) 
    
    for train_index, test_index in kf.split(df):
        print("TRAIN:", train_index) 
        print("TEST:", test_index)
        X_train, X_test = df.loc[train_index, "X"], df.loc[test_index, "X"]
        y_train, y_test = df.loc[train_index, "Y"], df.loc[test_index, "Y"]
    

    例如taken from here。

    【讨论】:

    • 我实际上应该编辑这个问题。实际上我根本不想使用 KFold。我想得到一个逻辑,可以一次将数据随机分成 10 组。我猜在任何模块中都没有这种方法。我制定了自己的逻辑。但是,如果有一些优化的解决方案,我将不胜感激。
    • @A.Sinha 感谢您的更新。我建议您将此作为新问题发布,然后关闭此问题或接受我的回答,以便其他人可以看到问题已解决。无论如何——祝你的项目好运!
    猜你喜欢
    • 2013-05-03
    • 2020-03-08
    • 2021-12-16
    • 1970-01-01
    • 2017-04-25
    • 2020-09-10
    • 2021-06-05
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多