Python:具有N个均值和相同协方差矩阵的多元法线样本 [英] Python: Sample from multivariate normal with N means and same covariance matrix

查看:59
本文介绍了Python:具有N个均值和相同协方差矩阵的多元法线样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想从多个正态分布中使用相同的协方差矩阵(同一性)但均值不同的样本进行10次采样,这些均方根存储为以下矩阵的行:

Suppose I want to sample 10 times from multiple normal distributions with the same covariance matrix (identity) but different means, which are stored as rows of the following matrix:

means = np.array([[1, 5, 2],
                  [6, 2, 7],
                  [1, 8, 2]])

我该如何以最有效的方式做到这一点(即避免循环)

How can I do that in the most efficient way possible (i.e. avoiding loops)

我尝试过这样:

scipy.stats.multivariate_normal(means, np.eye(2)).rvs(10)

np.random.multivariate_normal(means, np.eye(2))

但是他们抛出一个错误,说均值应该是一维.

But they throw an error saying mean should be 1D.

import scipy
np.r_[[scipy.stats.multivariate_normal(means[i, :], np.eye(3)).rvs() for i in range(len(means))]]

推荐答案

您的协方差矩阵表明样本是独立的.您可以立即对其进行采样:

Your covariance matrix indicate that the sample are independent. You can just sample them at once:

num_samples = 10
flat_means = means.ravel()

# build block covariance matrix
cov = np.eye(3)
block_cov = np.kron(np.eye(3), cov)

out = np.random.multivariate_normal(flat_means, cov=block_cov, size=num_samples)

out = out.reshape((-1,) + means.shape)

这篇关于Python:具有N个均值和相同协方差矩阵的多元法线样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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