每行具有不同标准偏差的块状数组

Ste*_*han 5 python numpy normal-distribution gaussian vectorization

我想得到一个NxM矩阵,其中每行中的数字是从不同的正态分布(相同mean但不同的标准偏差)生成的随机样本。以下代码有效:

import numpy as np

mean = 0.0 # same mean
stds = [1.0, 2.0, 3.0] # different stds
matrix = np.random.random((3,10))

for i,std in enumerate(stds):
     matrix[i] = np.random.normal(mean, std, matrix.shape[1])
Run Code Online (Sandbox Code Playgroud)

但是,此代码效率不高,因为其中for涉及到循环。有更快的方法吗?

Bra*_*mon 4

np.random.normal()被矢量化;您可以切换轴并转置结果:

np.random.seed(444)
arr = np.random.normal(loc=0., scale=[1., 2., 3.], size=(1000, 3)).T

print(arr.mean(axis=1))
# [-0.06678394 -0.12606733 -0.04992722]
print(arr.std(axis=1))
# [0.99080274 2.03563299 3.01426507]
Run Code Online (Sandbox Code Playgroud)

也就是说,scale参数是按列的标准差,因此需要转置 via .T,因为您需要按行输入。