我正在尝试根据NumPy中的均值和协方差矩阵创建一系列高斯。
import numpy as np
from scipy.stats import multivariate_normal
means = np.array([
[ 1, 0],
[ 2, 2],
[ 3, -1]])
covs = np.array([
[[1, 0],
[0, 1]],
[[9, 0],
[0, 4]],
[[4, 1],
[1, 1]]])
# This works
gaussians = [multivariate_normal(mean, cov) for mean, cov in zip(means, covs)]
'''
[<scipy.stats._multivariate.multivariate_normal_frozen at 0x27ced7e9f60>,
<scipy.stats._multivariate.multivariate_normal_frozen at 0x27ced7e92e8>,
<scipy.stats._multivariate.multivariate_normal_frozen at 0x27ced7e92b0>]
'''
# This throws an error
vec_gaussian = np.vectorize(lambda mean, cov: multivariate_normal(mean, cov))
gaussians = vec_gaussian(means, covs)
''' ValueError: operands could not be broadcast together with shapes (3,2) (3,2,2) '''
# Adding an axis gives singular matrix error (???)
gaussians = vec_gaussian(means[:, :, np.newaxis], covs)
''' LinAlgError: singular matrix '''
有什么方法可以使用vectorize
还是我最好只使用for循环?