簡體   English   中英

使用 python 從多元混合高斯分布采樣

[英]Sampling from multivariate mixed Gaussian distributions with python

我已經有 k 個平均向量和協方差矩陣以及權重,我如何在 python 中實現它以從混合高斯分布中采樣 n 個樣本? 對於均值和協方差是一維的情況,我幾乎可以實現它,但是如何實現它並為均值是多維的情況繪制圖表? 預先感謝您的回答。 在此處輸入圖像描述

您可以通過兩步法從混合高斯分布生成樣本。 您首先(隨機)select 根據混合物重量混合成分,然后從該特定混合物中生成樣本。

可以在下面找到示例代碼。 它使用雙變量示例來輕松可視化。 此外,將打印文本和 plot 與選定的權重、平均向量和協方差矩陣進行比較。 我希望這有幫助。

import matplotlib.pyplot as plt
import numpy as np
import random

# Bivariate example
dim = 2

# Settings
n = 500
NumberOfMixtures = 3

# Mixture weights (non-negative, sum to 1)
w = [0.5, 0.25, 0.25]

# Mean vectors and covariance matrices
MeanVectors = [ [0,0], [-5,5], [5,5] ]
CovarianceMatrices = [ [[1, 0], [0, 1]], [[1, .8], [.8, 1]], [[1, -.8], [-.8, 1]] ]

# Initialize arrays
samples = np.empty( (n,dim) ); samples[:] = np.NaN
componentlist = np.empty( (n,1) ); componentlist[:] = np.NaN

# Generate samples
for iter in range(n):
    # Get random number to select the mixture component with probability according to mixture weights
    DrawComponent = random.choices(range(NumberOfMixtures), weights=w, cum_weights=None, k=1)[0]
    # Draw sample from selected mixture component
    DrawSample = np.random.multivariate_normal(MeanVectors[DrawComponent], CovarianceMatrices[DrawComponent], 1)
    # Store results
    componentlist[iter] = DrawComponent
    samples[iter, :] = DrawSample

# Report fractions
print('Fraction of mixture component 0:', np.sum(componentlist==0)/n)
print('Fraction of mixture component 1:',np.sum(componentlist==1)/n)
print('Fraction of mixture component 2:',np.sum(componentlist==2)/n)

# Visualize result
plt.plot(samples[:, 0], samples[:, 1], '.', alpha=0.5)
plt.grid()
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM