如何基于组ID生成火车测试拆分?

时间:2019-02-21 00:45:22

标签: python-3.x pandas machine-learning grouping train-test-split

我有以下数据:

pd.DataFrame({'Group_ID':[1,1,1,2,2,2,3,4,5,5],
          'Item_id':[1,2,3,4,5,6,7,8,9,10],
          'Target': [0,0,1,0,1,1,0,0,0,1]})

  Group_ID Item_id  Target
0   1          1      0
1   1          2      0
2   1          3      1
3   2          4      0
4   2          5      1
5   2          6      1
6   3          7      0
7   4          8      0
8   5          9      0
9   5         10      1

我需要根据“ Group_ID”将数据集分为训练和测试集,以便80%的数据进入训练集,而20%的数据进入测试集。

也就是说,我需要训练集看起来像这样:

Training Set:       
Group_ID Item_id    Target
    0   1          1      0
    1   1          2      0
    2   1          3      1
    3   2          4      0
    4   2          5      1
    5   2          6      1
    6   3          7      0
    7   4          8      0

测试集:

Test Set
   Group_ID Item_id Target
8   5          9      0
9   5         10      1

最简单的方法是什么?据我所知,sklearn中的标准test_train_split函数不支持按组拆分,因为我也可以指出拆分的大小(例如80/20)。

1 个答案:

答案 0 :(得分:1)

我想出了答案。这似乎可行:

      create_table "reactions", force: :cascade do |t|
        t.string "reaction_target_type"
        t.bigint "reaction_target_id"
        t.bigint "badge_id"
        t.index ["badge_id"], name: "index_reactions_on_badge_id"
        t.index ["reaction_target_type", "reaction_target_id"], name: "index_reactions_on_reaction_target_type_and_reaction_target_id"
      end
相关问题