【问题标题】:boost random sample like python random.sample提升随机样本,如 python random.sample
【发布时间】:2013-04-04 06:46:09
【问题描述】:

我正在尝试使用 C++ 来模仿 python

random.sample(a_set, n_samples)

类似C++的函数

set<string> sample(set<string> input, int n_samples)

在我自己写之前,有没有图书馆这样做?我的电脑上有boost 1.46。

【问题讨论】:

  • 如果我猜对了,你需要一个函数来生成n_samples 唯一的随机数,对吧?
  • @KirilKirov 从a_set 的群体中选择n_samples 的独特元素。

标签: c++ python boost random random-sample


【解决方案1】:

从 C++17 开始就有std::sample:

std::sample(input.begin(), input.end(), std::back_inserter(out),
            n_samples, std::mt19937{std::random_device{}()});

原始答案如下。我把它留在这里供参考。


SGI's implementation of the STL 具有 random_samplerandom_sample_n 函数:

template <class InputIterator, class RandomAccessIterator>
Random AccessIterator random_sample(InputIterator first, InputIterator last,
                                    RandomAccessIterator ofirst,
                                    RandomAccessIterator olast) 

template <class ForwardIterator, class OutputIterator, class Distance>
OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last,
                               OutputIterator out, Distance n)

random_sample_n[first, last) 范围内的元素样本随机复制到[out, out + n) 范围内。输入范围内的每个元素在输出范围内最多出现一次,样本以均匀概率选择。

很遗憾

Matt Austern 提出了几个额外的算法(大部分取自 SGI 的标准库的原始 STL 实现)。其中包括 random_samplerandom_sample_n

(来自N3925

但是

在 Sophia-Antipolis 会议上经过 WG21 审议后,Austern 更新了提案,产生了 [N2666]。在其他变化中,他撤回了采样算法,因为“LWG 担心它们可能对标准化的理解不够好……为 TR2 提出这些算法可能是合适的”。 LWG 随后取得了稳固的成绩 共识(10-1, 2 abs.)以支持在未来的技术报告(现在称为技术规范)中包含这些算法。

random_sample_n 算法的一个版本已进入 Library Fundamentals TS,称为 std::experimental::sample,提案的最新迭代 N3925 于 2014-02 年被采用,但仍未成为标准的一部分(可能在 C++17 中)。

除了水库采样算法,您还可以看看 Donald Knuth 在 The计算机编程艺术 - 第 2 卷 - §3.4.2。

【讨论】:

    【解决方案2】:

    您要解决的问题称为reservoir sampling。我尝试在谷歌上搜索“水库采样 C++ 实现”。 Google 会自动为我完成查询,但粗略浏览一下结果并没有找到实际的库。

    该算法非常简单,自己学习和编写也很有趣,所以我建议这样做。

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 2012-01-31
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2013-01-26
      相关资源
      最近更新 更多