douhui9192 2018-06-14 21:58
浏览 51


I have a big array of items and another array of weights of the same size. I would like to sample without replacement from the first array based on the weights from the second array. Is there a way to do this using gonum?

  • 写回答

1条回答 默认 最新

  • dpndp64206 2018-06-14 22:54

    Weighted and its relative method .Take() look exactly like what you want.

    From the doc:

    func NewWeighted(w []float64, src *rand.Rand) Weighted

    NewWeighted returns a Weighted for the weights w. If src is nil, rand.Rand is used as the random source. Note that sampling from weights with a high variance or overall low absolute value sum may result in problems with numerical stability.

    func (s Weighted) Take() (idx int, ok bool)

    Take returns an index from the Weighted with probability proportional to the weight of the item. The weight of the item is then set to zero. Take returns false if there are no items remaining.

    Therefore Take is indeed what you need for sampling without replacement.

    You can use NewWeighted to create a Weighted with the given weights, then use Take to extract one index with probability based on the previously set weights, and then select the item at the extracted index from your array of samples.

    Working example:

    package main
    import (
    func main() {
        samples := []string{"hello", "world", "what's", "going", "on?"}
        weights := []float64{1.0, 0.55, 1.23, 1, 0.002}
        w := sampleuv.NewWeighted(
        i, _ := w.Take()
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 conda 命令用不了 conda就是用不了 一用就显示core dumped
  • ¥100 基于delphi10.2几个功能的程序demo
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word
  • ¥15 请教怎么用MATLAB求坐标
  • ¥15 gradle整合es,在创建索引时报错