首页 > 解决方案 > 如何从具有 np 概率数组的 2d np 数组中选择随机行?

问题描述

我在从我的 np 数组中选择一个随机行(在我的情况下为点)时遇到了一些困难。我想用每个点的概率来做到这一点(所以我有一个 P_i np 数组,其中每一行都是一个点的概率)。我试图用 np.random.choice 来做它并得到“它必须是一个一维数组”所以我对行数做了 np.random.choice 所以我得到了一个随机的行索引。但是我如何用每个点的概率来做到这一点?

标签: pythonarraysnumpy

解决方案


您可以将 np.choice 与总和为 1 的概率分布一起使用。

获得总和为 1 的概率

重塑

如果您的概率总和为1,那么您只需压缩您的概率向量:

# Example of probability vector
probs = np.array([[0.1, 0.2, 0.5, 0.2]])
# array([[0.1, 0.2, 0.5, 0.2]])
probs.shape
# > (1, 4)
p_squeezed = probs.squeeze()
# > array([0.1, 0.2, 0.5, 0.2])
p_squeezed.shape
# > (4,)

获得适当的概率分布

如果你自己probs加起来不等于 1,那么你可以申请 adivision by the sum或 a softmax

只是生成随机数据:

import numpy as np
# Random 2D points
points = np.random.randint(0,10, size=(10,2))
# random independant probabilities
probs = np.random.rand(10).reshape(-1, 1)
data = np.hstack((probs, points))
print(data)
# > array([[0.01402932, 5.        , 5.        ],
#          [0.01454579, 5.        , 6.        ],
#          [0.43927214, 1.        , 7.        ],
#          [0.36369286, 3.        , 7.        ],
#          [0.09703463, 9.        , 9.        ],
#          [0.56977406, 1.        , 4.        ],
#          [0.0453545 , 4.        , 2.        ],
#          [0.70413767, 4.        , 4.        ],
#          [0.72133774, 7.        , 1.        ],
#          [0.27297051, 3.        , 6.        ]])

应用softmax:

from scipy.special import softmax
scale_softmax = softmax(data[:,0])
# > array([0.07077797, 0.07081454, 0.1082876 , 0.10040494, 0.07690364,
#  0.12338291, 0.0730302 , 0.14112644, 0.14357482, 0.09169694])

应用除以总和:

scale_divsum = data[: ,0] / data[:, 0].sum()
# > array([0.00432717, 0.00448646, 0.13548795, 0.11217647, 0.02992911,
#  0.17573962, 0.01398902, 0.21718238, 0.22248752, 0.08419431])

以下是我提出的缩放函数的累积分布:

累积分布

Softmax使其更有可能选择任何点division by the sum,但后者可能更适合您的需求。

选择随机行

现在您可以使用np.random.choice并将您的概率分布赋予参数p

rand_idx = np.random.choice(np.arange(len(data)), p=scale_softmax)
data[rand_idx]
# > array([0.70413767, 4.        , 4.        ])

# or just the point:
data[rand_idx, 1:]
# > array([4., 4.])

推荐阅读