【问题标题】:How to split data into two sets using row batches of N?如何使用 N 行批次将数据分成两组?
【发布时间】:2020-06-06 21:30:49
【问题描述】:

我需要使用 2 个批次将我的数据集 df 随机分成两组(比例 70:30)。通过“批次”,我的意思是 2 个(批次大小)连续行应该始终属于同一个集合.

  col1    col2    col3
  1       0.5     10
  1       0.3     11
  5       1.4     1
  3       1.5     2
  1       0.9     10
  3       0.4     7
  1       1.2     9
  3       0.1     11

示例结果(由于随机性,输出可能会有所不同,但这只是一个示例):

set1
      col1    col2    col3
      1       0.5     10
      1       0.3     11
      1       0.9     10
      3       0.4     7
      1       1.2     9
      3       0.1     11

set2
      5       1.4     1
      3       1.5     2

我知道如何使用 1 个批次随机拆分数据:

import numpy as np

msk = np.random.rand(len(df)) < 0.7
set1 = df[msk]
set2 = df[~msk] 

但是,不确定如何引入灵活批处理。

谢谢。

更新:

这是我目前拥有的,但最后一行代码失败。 set1set2 应该是 pandas 数据帧。

n = 3
df_batches = [df[i:i+n] for i in range(0, df.shape[0],n)]

set1_idx = np.random.randint(len(df_batches), size=int(0.7*len(df_batches)))
set2_idx = np.random.randint(len(df_batches), size=int(0.3*len(df_batches)))
set1, set2 = df_batches[set1_idx,:], df_batches[set2_idx,:]

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

这是一个基于随机整数做你想做的事情然后取 30% 的函数:

def split_data(df, batchsize):
    x = np.random.randint(0, len(df))
    idx = round(len(df) * batchsize)

    # so we don't get out of the bounds of our index
    if x + idx > len(df):
        x = x - idx

    batch1 = df.loc[np.arange(x, x+idx)]
    batch2 = df.loc[~df.index.isin(batch1.index)]

    return batch1, batch2

df1, df2 = split_data(df, 0.3)
print(df1, '\n')
print(df2)

   col1  col2  col3
4     1   0.9    10
5     3   0.4     7 

   col1  col2  col3
0     1   0.5    10
1     1   0.3    11
2     5   1.4     1
3     3   1.5     2
6     1   1.2     9
7     3   0.1    11

【讨论】:

  • 谢谢。哪个参数定义了批量大小?
  • 您能解释一下您的解决方案吗?行总是连续的吗? (这是强制性要求)。我的意思是,如果 df1 包含第 3 行然后包含第 5 行,那就错了。
  • 我添加了参数batchsize,由于np.arange,行将始终是连续的
  • 好吧,我有点不清楚为什么batchsize0.3?在我的例子中,batchsize 是整数,它表示应该是连续的行数。例如batchsize为10,则需要将70%的批次10用于set1,30%的批次10用于set2。
  • 那我想我误解了你,我以为你想要一批 30% 的数据是顺序的。从您的示例中看起来就是这样。
【解决方案2】:

为了获得更多随机性,您可以使用 numpy 函数 np.random.permutation。这是一个例子:

batchsizes = np.asarray([0.7])
permutations = np.random.permutation(len(df))

batchsizes *= len(permutations)
slices = np.split(permutations, batchsizes.round().astype(np.int))
batchs = [df.loc[s] for s in slices] 

这具有更好的随机性,因为它不再依赖于数据帧的初始形式。您可以拥有超过 2 个部分。例如,您可以使用batchsizes = np.asarray([0.3,0.1,0.3]),它会以 30:10:30:30 的比例进行切片。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    相关资源
    最近更新 更多