2013-04-26 80 views
1

我正在寻找一种方法来做一个逆加权分布。这里是我的一个简单的线性码称重分布:逆加权分布

total = 0 
cumulative_distribution = [] 

for value in distribution: 
    total += value 
    cumulative_distribution.append(total) 

selected = total * random.random() 

index = 0 
while cumulative_distribution[index] < selected: 
    index += 1 

return index 

我怎么可能逆此所以在列表中的项目具有最小的权重有被选择的概率最高?有什么方法来标准化和切换它们?

+1

这取决于你想如何衡量他们。最简单的方法是用'max_weight - weight + 1'或者别的东西来替换权重,以便以前最高的权重变成1,而以前的权重为零的权重将是'max_weight'。你可以做各种其他类型的转换,具体取决于你希望它具有的属性... – Dougal 2013-04-26 03:01:37

+0

我并不是真正关心权重,而是从分布中选择实际的索引。只要他们获得了比25更好的选择机会,这很好。 – Clev3r 2013-04-26 03:02:48

+0

您可以在不进行两次循环迭代的情况下执行此操作:一个用于构建分布,一个用于重新排列? – Clev3r 2013-04-26 03:09:52

回答

2

正如评论中所提到的,这取决于你想如何衡量它们。使用您的语句:

最小的权重有被选择

两个@Blckknght的概率最高和我有同样的想法,简单地加权每个点在PDF中与它的倒数。我建议通过参数一样

inverse_PDF = 1/(PDF + delta) 

加权,其中delta是你可以控制你的口味的参数。如果delta=0那么PDF中原始权重为零的任何点都会抛出一个ZeroDivisionError,这通常是不可取的。下面是一个使用numpy的一些示例代码实现上述:

import numpy as np 

# Generate a random points 
pts = np.random.normal(size=(10**6,)) 

# Compute a PDF 
PDF,bins = np.histogram(pts, bins=50) 

# Normalize (could have used normed=True in hist) 
PDF = PDF/np.trapz(PDF, bins[1:]) 

# Create the inverse distribution 
delta = .1 
inverse_PDF = 1/(PDF + delta) 

# Normalize 
inverse_PDF = inverse_PDF/np.trapz(inverse_PDF, bins[1:]) 

# Plot the results 
import pylab as plt 
plt.subplot(211) 
plt.plot(bins[1:],PDF,lw=4,alpha=.7) 
plt.title("Original Distribution") 
plt.subplot(212) 
plt.plot(bins[1:],inverse_PDF,lw=4,alpha=.7) 
plt.title(r"'Inverse' Distribution with $\delta=%.3f$" % delta) 
plt.tight_layout() 
plt.show() 

enter image description here

+1

干得好,感谢全力以赴。 – Clev3r 2013-04-26 15:17:28