Sou*_*oti 0 functional-programming scala
我有一个List[(String, Double)]变量,其中元组的第二个元素表示第一个元素中的字符串出现在语料库中的概率。例如,[(Apple, 0.2), (Banana, 0.3), (Lemon, 0.5)]Apple 在字符串列表中出现的概率为 0.2。我想根据字符串出现的概率从字符串列表中随机采样,类似于 numpyrandom.choice()方法。在 Scala 中执行此操作的正确方法是什么?
另一个解决方案:
def choice(samples: Seq[(String, Double)], n: Int): Seq[String] = {
val (strings, probs) = samples.unzip
val cumprobs = probs.scanLeft(0.0){ _ + _ }.init
def p2s(p: Double): String = strings(cumprobs.lastIndexWhere(_ <= p))
Seq.fill(n)(math.random).map(p2s)
}
Run Code Online (Sandbox Code Playgroud)
用法(并验证):
>> val ss = choice(Seq(("Apple", 0.2), ("Banana", 0.3), ("Lemon", 0.5)), 10000)
>> ss.groupBy(identity).map{ case(k, v) => (k, v.size)}
Map[String, Int] = Map(Banana -> 3013, Lemon -> 4971, Apple -> 2016)
Run Code Online (Sandbox Code Playgroud)