抱歉标题措辞不好......
我有一个名为 NGram 的对象
class NGram
{
//other properties
double Probability {get; set;} //Value between 1 and 0
}
现在假设我有这些对象的列表,以便......
List<NGrams> grams = GetNGrams();
Debug.Assert(grams.Sum(x => x.Probability) == 1);
如何在考虑概率分布的同时从此列表中选择随机项目。
例如,假设grams[0].Probability == 0.5
那么应该有50%的机会选择grams[0]
我想我可能需要类似的东西rand.NextDouble()
但我不知所措。
这是一种更通用的方法(意味着你不need断言概率加到 1):
static Random rand = new Random();
public NGram GetRandom(IEnumerable<NGram> pool)
{
// get universal probability
double u = pool.Sum (p => p.Probability);
// pick a random number between 0 and u
double r = rand.NextDouble() * u;
double sum = 0;
foreach(NGram n in pool)
{
// loop until the random number is less than our cumulative probability
if(r <= (sum = sum + n.Probability))
{
return n;
}
}
// should never get here
return null;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)