什么是Python的Numpy np.random.choice的scala等价物?(scala中的随机加权选择)
我在寻找Scala的等效代码或pythons np.random.choice Numpy作为np的基础理论。我有一个类似的实现,它使用Python的np.random.choice方法从概率分布中选择随机移动 输入列表:['pooh','rabbit','Pieget','Christopher']和概率:[0.5,0.1,0.1,0.3]什么是Python的Numpy np.random.choice的scala等价物?(scala中的随机加权选择),scala,random,sampling,Scala,Random,Sampling,我在寻找Scala的等效代码或pythons np.random.choice Numpy作为np的基础理论。我有一个类似的实现,它使用Python的np.random.choice方法从概率分布中选择随机移动 输入列表:['pooh','rabbit','Pieget','Christopher']和概率:[0.5,0.1,0.1,0.3] 考虑到每个输入元素的相关概率,我想从输入列表中选择一个值。Scala标准库没有与np.random.choice等效的值,但构建自己的值应该不会太困难,这
考虑到每个输入元素的相关概率,我想从输入列表中选择一个值。Scala标准库没有与np.random.choice等效的值,但构建自己的值应该不会太困难,这取决于要模拟的选项/功能 例如,这里是一种获得无限提交项目流的方法,其中任何一个项目相对于其他项目加权的概率
def weightedSelect[T](input :(T,Int)*): Stream[T] = {
val items :Seq[T] = input.flatMap{x => Seq.fill(x._2)(x._1)}
def output :Stream[T] = util.Random.shuffle(items).toStream #::: output
output
}
这样,每个输入项都有一个乘数。因此,要获得字符c和v的无限伪随机选择,c占时间的3/5,v占时间的2/5:
val cvs = weightedSelect(('c',3),('v',2))
因此,np.random.Choiceaaa_milne_arr,5,p=[0.5,0.1,0.1,0.3]示例的粗略等价物为:
weightedSelect("pooh"-> 5
,"rabbit" -> 1
,"piglet" -> 1
,"Christopher" -> 3).take(5).toArray
或者你可能想要一个更好的,更少的伪随机分布,这可能是严重不平衡的
def weightedSelect[T](items :Seq[T], distribution :Seq[Double]) :Stream[T] = {
assert(items.length == distribution.length)
assert(math.abs(1.0 - distribution.sum) < 0.001) // must be at least close
val dsums :Seq[Double] = distribution.scanLeft(0.0)(_+_).tail
val distro :Seq[Double] = dsums.init :+ 1.1 // close a possible gap
Stream.continually(items(distro.indexWhere(_ > util.Random.nextDouble())))
}
Scala标准库没有与np.random.choice等效的库,但是构建自己的库应该不会太困难,这取决于您想要模拟的选项/功能 例如,这里是一种获得无限提交项目流的方法,其中任何一个项目相对于其他项目加权的概率
def weightedSelect[T](input :(T,Int)*): Stream[T] = {
val items :Seq[T] = input.flatMap{x => Seq.fill(x._2)(x._1)}
def output :Stream[T] = util.Random.shuffle(items).toStream #::: output
output
}
这样,每个输入项都有一个乘数。因此,要获得字符c和v的无限伪随机选择,c占时间的3/5,v占时间的2/5:
val cvs = weightedSelect(('c',3),('v',2))
因此,np.random.Choiceaaa_milne_arr,5,p=[0.5,0.1,0.1,0.3]示例的粗略等价物为:
weightedSelect("pooh"-> 5
,"rabbit" -> 1
,"piglet" -> 1
,"Christopher" -> 3).take(5).toArray
或者你可能想要一个更好的,更少的伪随机分布,这可能是严重不平衡的
def weightedSelect[T](items :Seq[T], distribution :Seq[Double]) :Stream[T] = {
assert(items.length == distribution.length)
assert(math.abs(1.0 - distribution.sum) < 0.001) // must be at least close
val dsums :Seq[Double] = distribution.scanLeft(0.0)(_+_).tail
val distro :Seq[Double] = dsums.init :+ 1.1 // close a possible gap
Stream.continually(items(distro.indexWhere(_ > util.Random.nextDouble())))
}
但我的体重可能真的很大,物品可能有数百万,这是一个比seq.fill更好的方法吗?很有趣。也许您可以发布一个更接近您实际需求的np.random.choice示例。请看我的更新。但我的体重可能非常大,物品可能有数百万,这是一种比seq.fill更好的方法吗?很有趣。也许您可以发布一个更接近您实际需求的np.random.choice示例。查看我的更新。