python - 如何从python中的N个不同正态分布中采样M次?在处理时间方面有没有 "faster"方式?

标签 python numpy random

我需要从 N 个不同的正态分布中采样多次 (M)。这种重复采样将依次发生数千次。我想以最有效的方式做到这一点,因为我不想在这个过程结束之前老死。代码看起来像这样:

import numpy as np

# bunch of stuff that is unrelated to the problem

number_of_repeated_processes = 5000
number_of_samples_per_process = 20

# the normal distributions I'm sampling from are described by 2 vectors:
#
# myMEANS <- an numpy array of length 10 containing the means for the distributions
# myVAR <- an numpy array of length 10 containing the variance for the distributions


for i in range(number_of_repeated_processes):
  # myRESULT is a list of arrays containing the results for the sampling
  #
  myRESULT = [np.random.normal(loc=myMEANS[j], scale=myVAR[j], size = number_of_samples_per_process) for j in range(10)]
  #
  # here do something with myRESULT

# end for loop

问题是...有没有更好的方法来获取 myRESULT 矩阵

最佳答案

np.random.normal 直接接受 means-var 作为数组,您可以选择一个大小来覆盖一次运行中的所有采样而无需循环:

myRESULT = np.random.normal(loc=myMEANS, scale=myVAR, size = (number_of_samples_per_process, number_of_repeated_processes,myMEANS.size))

这将为您的 myMEANS-myVAR 中的每个均值-变量对返回一个 number_of_samples_per_process by number_of_repeated_processes 列大批。例如,要访问 myMEANS[i]-myVAR[i] 的示例,请使用 myRESULT[...,i]。这应该会稍微提高您的表现。

关于python - 如何从python中的N个不同正态分布中采样M次?在处理时间方面有没有 "faster"方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66286076/

相关文章:

python - 值错误 : Feature not in features dictionary

python - 在 Python 中创建矩阵

php - 如何使用 PHP 从文本文件(数组)中选择一个随机单词?

python - 如何从命令行创建 web2py 应用程序?

Python Alt Hook

python - numpy 将切片 append 到二维数组以使其成为三维数组

mysql - 稳定/可重复的随机排序(MySQL、Rails)

c# - ASP.NET5 中的随机数生成器

python - 根据某些标准更改绘图颜色

Python Beautifulsoup 从具有相同类的不同跨度中提取文本