【问题标题】:How to repeat a certain command (BOOTSTRAP RESAMPLING) with Python如何使用 Python 重复某个命令(BOOTSTRAP RESAMPLING)
【发布时间】:2020-10-28 14:00:20
【问题描述】:

我有一个数据框(长度为 4 个数据点)并想做一个 Bootstrap X 次。

数据帧示例:

              Index A B
                0   1 2
                1   1 2
                2   1 2
                3   1 2 

我为引导重采样找到了这段代码

      boot = resample(df, replace=True, n_samples=len(df), random_state=1)
      print('Bootstrap Sample: %s' % boot)

但现在我喜欢重复这个 X 次。我该怎么做?

x=20 的输出。

  Sample Nr.    Index A B
      1         0   1 2
                1   1 2
                2   1 2
                3   1 2 
     ...
      20        0   1 2
                1   1 2
                1   1 2
                2   1 2   

谢谢你们。

最好的

【问题讨论】:

  • 你的意思是我想从我的数据中获取 n 个不同的引导样本?
  • 是的,没错@MiguelTrejo。上面的代码只能创建 1 个引导示例。但我想得到 X 很多(比如可能 > 1000)。非常感谢
  • 你是指sample函数还是resample函数?,你指定的参数是针对示例函数的?
  • 用于重采样功能。所以要更清楚地解释:1)我们有原始数据2)在重新采样的数据中创建这个原始数据的X倍。 2) 代码: boot = resample(df, replace=True, n_samples=len(df), random_state=1) print('Bootstrap Sample: %s' % boot) 从原始数据中仅创建 1 个重采样数据。 --> 所以从原始数据创建更多的重采样数据是目标(重复采样)。 @MiguelTrejo

标签: python dataframe resampling statistics-bootstrap


【解决方案1】:

方法 1:并行样本数据

由于调用 n 时间作为数据帧的示例方法可能很耗时,因此可以考虑并行应用 sample 方法。

import multiprocessing
from itertools import repeat

def sample_data(df, replace, random_state):
    '''Generate one sample of size len(df)'''
    return df.sample(replace=replace, n=len(df), random_state=random_state)

def resample_data(df, replace, n_samples, random_state):
    '''Call n_samples time the sample method parallely'''
    
    # Invoke lambda in parallel
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    bootstrap_samples = pool.starmap(sample_data, zip(repeat(df, n_samples), repeat(replace), repeat(random_state)))
    pool.close()
    pool.join()

    return bootstrap_samples

现在,如果我想生成 15 个样本,resample_data 将返回一个包含来自 df 的 15 个样本的列表。

samples = resample_data(df, True, n_samples=15, random_state=1)

请注意,要返回不同的结果,将random_state 设置为None 会很方便。

方法 2:线性采样数据

另一种获取样本数据的方法是通过列表推导,因为函数 sample_data 已经定义,因此可以直接在列表中调用它。

def resample_data_linearly(df, replace, n_samples, random_state):
    
    return [sample_data(df, replace, random_state) for _ in range(n_samples)] 

# Generate 10 samples of size len(df)
samples = resample_data_linearly(df, True, n_samples=10, random_state=1)

【讨论】:

  • 非常感谢。但是输出似乎产生了很多错误:(在当前进程完成其引导阶段之前尝试启动一个新进程。这可能意味着您没有使用 fork 启动子进程并且您忘记了例如,在主模块中使用正确的成语:)。 @MiguelTrejo
  • 并且新样本的长度必须与原始样本的长度相同。 (所以 n_samples = 15 不会做 15 个新样本,而是用原始样本中的 15 个数据点创建一个样本来创建一个新样本。
  • 看来问题出在 Windows 上,也许你可以使用 docker 容器来运行你的代码,这在 Linux 上运行良好
  • 如果样本大小应该是可以更改的数据大小,您是对的,我会进行编辑。
  • @LinhTran 您可以使用列表理解,请参阅最后的编辑以获取代码示例。我希望这对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 2012-02-03
  • 1970-01-01
  • 2021-12-31
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多