如何使用 Numpy 生成不相关的样本

How to generate uncorrelated samples with Numpy

我想在 python 上生成随机样本,但每个样本都有自己的标准差。

我以为我可以用 np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations)

但是,当我将数组用于缩放(这与我从文档中理解的相反)并且只需要一个浮点数作为参数时,bumpy 似乎不起作用。

我的目标是渲染一个大小为(标准偏差数 X 模拟数)的数组,其中每一行只是 np.random.normal(0, scale=np.array(standard_deviation)[i], size= (1,number_of_simulations)

我想我可以做一个循环,然后连接每个结果,但如果没有必要我不想这样做,因为我相信你通过做循环失去了 Numpy 和 Pandas 的兴趣。

希望我说清楚了,感谢您的帮助!

NumPy 随机函数 do 接受数组,但当您还提供 size 参数时,形状必须兼容。

改变这个:

np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations)

np.random.normal(0, scale=standard_deviation, size=(number_of_simulations, len(standard_deviation)))

结果的形状为 (number_of_simulations, len(standard_deviation))

这是 ipython 会话中的具体示例。请注意,我没有使用 numpy.random.normal,而是使用较新的 NumPy 随机 API,在其中我创建了一个名为 rng 的生成器并调用其 normal() 方法:

In [103]: rng = np.random.default_rng()

In [104]: standard_deviation = np.array([1, 5, 25])

In [105]: number_of_simulations = 6

In [106]: rng.normal(scale=standard_deviation, size=(number_of_simulations, len(standard_deviation)))
Out[106]: 
array([[ -0.31088926,   1.95005394,  -8.77983357],
       [  1.80907248,   4.27082827,  31.13457498],
       [ -0.27178958, -12.6589072 , -31.70729135],
       [  0.2848883 ,   1.71198071, -23.6336055 ],
       [  0.78457822,   2.78281586,  32.61089728],
       [ -0.7014944 ,   5.47845616,   5.34276638]])