每行具有不同标准偏差的块状数组 [英] Numpy array with different standard deviation per row

查看:66
本文介绍了每行具有不同标准偏差的块状数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to get an NxM matrix where numbers in each row are random samples generated from different normal distributions(same mean but different standard deviations). The following code works:

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])

但是,由于涉及到 for 循环,因此该代码效率不高.有没有更快的方法可以做到这一点?

However, this code is not quite efficient as there is a for loop involved. Is there a faster way to do this?

推荐答案

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

np.random.normal() is vectorized; you can switch axes and transpose the result:

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]

也就是说, scale 参数是的标准偏差,因此需要通过 .T 进行转置明智的输入.

That is, the scale parameter is the column-wise standard deviation, hence the need to transpose via .T since you want row-wise inputs.

这篇关于每行具有不同标准偏差的块状数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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