在任何情况下,您是否更喜欢O(log n)
时间复杂度和O(1)
时间复杂度?或O(n)
到O(log n)
?
你有什么例子吗?
我试图矢量化以下代码:
for i in xrange(s.shape[0]):
a[i] = np.argmax(np.random.multinomial(1,s[i,:]))
Run Code Online (Sandbox Code Playgroud)
s.shape = 400 x 100
[给定].
a.shape = 400
[预期].
s是2D矩阵,包含对的概率.期望多项式从s矩阵的每一行中抽取随机样本并将结果存储在向量a中.
Numpy 具有该random.choice
功能,可让您从分类分布中进行采样。你会如何在一个轴上重复这个?为了说明我的意思,这是我当前的代码:
categorical_distributions = np.array([
[.1, .3, .6],
[.2, .4, .4],
])
_, n = categorical_distributions.shape
np.array([np.random.choice(n, p=row)
for row in categorical_distributions])
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想消除 for 循环。
I regularly find myself in the position of needing a random index to an array or a list, where the probabilities of indices are not uniformly distributed, but according to certain positive weights. What's a fast way to obtain them? I know I can pass weights to numpy.random.choice
as optional argument p
, but the function seems quite slow, and building an arange
to pass it is not ideal either. The sum of weights can be an arbitrary positive number …