多个二项式随机变量的矢量化抽样 [英] Vectorized sampling of multiple binomial random variables

查看:38
本文介绍了多个二项式随机变量的矢量化抽样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对几百个二项分布的随机变量进行抽样,每个变量都有不同的 np(使用 numpy.random.binomial 文档).我会反复这样做,所以如果可能的话,我想对代码进行矢量化.举个例子:

I would like to sample a few hundred binomially distributed random variables, each with a different n and p (using the argument names as defined in the numpy.random.binomial docs). I'll be doing this repeatedly, so I'd like to vectorize the code if possible. Here's an example:

import numpy as np

# Made up parameters
N_random_variables = 500
n_vals = np.random.random_integers(100, 200, N_random_variables)
p_vals = np.random.random_sample(N_random_variables)

# Can this portion be vectorized?
results = np.empty(N_random_variables)
for i in xrange(N_random_variables):
    results[i] = np.random.binomial(n_vals[i], p_vals[i])

在每个随机变量的 np 相同的特殊情况下,我可以这样做:

In the special case that n and p are the same for each random variable, I can do:

import numpy as np

# Made up parameters
N_random_variables = 500
n_val = 150
p_val = 0.5

# Vectorized code
results = np.random.binomial(n_val, p_val, N_random_variables)

这可以推广到 np 为每个随机变量取不同值的情况吗?

Can this be generalized to the case when n and p take different values for each random variable?

推荐答案

给你,

import numpy as np

# Made up parameters
N_random_variables = 500
n_vals = np.random.random_integers(100, 200, N_random_variables)
p_vals = np.random.random_sample(N_random_variables)

# Can this portion be vectorized? Yes
results = np.empty(N_random_variables)
results = np.random.binomial(n_vals, p_vals)

这篇关于多个二项式随机变量的矢量化抽样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆