【问题标题】:Modifying train_test_split function修改 train_test_split 函数
【发布时间】:2018-12-30 09:32:01
【问题描述】:

我可以使用train_test_split()而不是传递test_sizerandom_state参数,根据索引值(每10行作为训练数据,其余作为测试数据)将数据集分成训练集和测试集吗?

【问题讨论】:

  • 您的问题不够清楚...能否请您提供更多详细信息
  • 我知道 sklearn 库下的 train_test_split() 根据 test_size 参数将数据集拆分为训练和测试数据。如果 test_size 为 0.2,它将以 80:20 的比例拆分数据集。但是,如果我想将数据集的每 10 行拆分为训练数据,其余的作为测试,我该怎么做呢?

标签: python machine-learning scikit-learn classification


【解决方案1】:

好吧试试这个,你可以使用::n,它会返回你指定的每n个,这里是例子:

df=pd.DataFrame({'number': np.arange(100), })

如果我们想每 10 次获取一次值:

print(df[::10])

结果:

    number
0        0
10      10
20      20
30      30
40      40
50      50
60      60
70      70
80      80
90      90

你可以用 numpy 数组做同样的事情:

np.arange(100)

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

每 9 个值:

np.arange(100)[::9]

输出:

array([ 0,  9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99])

编辑:

def getting_train_val(dataframe, interval=10):
    x_valid = dataframe[::interval]
    x_test = dataframe[~ dataframe(dataframe[::interval])].dropna()
    return x_valid, x_test

【讨论】:

  • 感谢您的评论。我相信这不能使用 train_test_split 函数来完成。使用 df[::10] 可以得到火车数据集。但是如何才能将剩余的行放入测试数据集中?
  • 是的,它有效!谢谢您的帮助! :) 我刚刚意识到使用:for index, row in df.iterrows(): X_train = df[(df.index)% 5 != 0] 也可以达到目的:)
  • 太棒了!=) 编码愉快!
  • @RachaelE 请接受 H.Bukharis 的回答作为您的解决方案,以便其他人可以看到问题已解决。谢谢!
  • @petezurich 接受它:)
猜你喜欢
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2020-03-18
  • 2016-05-27
相关资源
最近更新 更多