2017-04-09 46 views
1

numpy或scipy中是否有任何函数对于给定的pdf,从该分布采样的点将返回?Numpy采样函数

例如,我有高斯分布的混合物:

means = 0., 8. 
stdevs = 1.0,1.0 
weights = 0.75,0.25 

pdfs = [p * norm.pdf(x, mu, sd) for mu, sd, p in zip(means, stdevs, weights)] 

为PDF的曲线图和用于从该分布采样应该像点直方图: enter image description here

感谢

回答

0

你可以用numpy解决这个问题

import numpy as np 
x_vals = np.random.normal(0., 1.0, 100) 
y_vals = np.random.normal(8., 1.0, 100) 
x_norm = [*x_vals, *y_vals] 
+0

什么是*之前x_vals和y_vals意味着在那里?顺便说一下,它是高斯混合而不是多元高斯。 –

0

如果要合并多个pdf,以便仍然可以通过x,则需要创建一个新函数。做到这一点的一种方法是创建一个函数返回一个函数与高斯的加权和。

from scipy.stats import norm 
import numpy as np 

def create_mixed_pdf(means, stdevs, weights): 
    # this uses a lambda function to return the weighted sum of the pdfs at x 
    return lambda x: sum([p*norm(mu, sd).pdf(x) for mu, sd, p in zip(means, stdevs, weights)]) 

# this sets `my_pdf` to be the combined pdf distributions 
my_pdf = create_mixed_pdf(means, stdevs, weights) 

# testing: 
import matplotlib.pyplot as plt 
x = np.arange(-4, 12, .05) 

plt.plot(x, my_pdf(x)) 
plt.show() 

enter image description here

+0

非常感谢!但是我想要做的不仅仅是绘制pdf,我还想从这个pdf中抽取一些数据点。我怎么做? –

+0

你想从分布中随机抽样吗? – James

+0

是的,这就是我想要做的。 –