如何有效地将列表转换为概率分布?



我正在尝试将列表转换为概率分布。

x = [2, 4]

我希望它按该顺序排列以下数组。

probability_array = [1-(2+4)/10, 2/10, 4/10]

所以我做了以下工作...

y = 1 - (2 + 4)/10
new_x = [2/10, 4/10]
probability_array = [y] + new_x

问题是我正在使用 10,000 个数据集,例如x.有没有更快的方法来做到这一点?

我认为您可以使用numpy轻松做到这一点。这是正确性的示例

x=[[1, 2], [3,4]]
x=np.array(x)
sum1 = np.sum(x, axis=1).reshape(2,1)
prob = x/sum1

我认为即使大小为 x>10000,也会很快。让我们为10000个示例取100个特征

x=np.random.randint(1, 100, size=1000000)
print(x.shape)
start=time.time()
x=x.reshape(-1, 10000)
sum1=np.sum(x, axis=1).reshape((-1, 1))
prob=x/sum1
stop=time.time()
print(stop-start)

这在我的 MBP 上大约需要0.021秒。

最新更新