我想学习PyMC3,我想做一个简单的高斯混合例子。我找到了this示例并希望将其转换为pymc3,但我当前在尝试绘制跟踪绘图时遇到了一个错误。在
n1 = 500
n2 = 200
n = n1+n2
mean1 = 21.8
mean2 = 42.0
precision = 0.1
sigma = np.sqrt(1 / precision)
# precision = 1/sigma^2
print "sigma1: %s" % sigma1
print "sigma2: %s" % sigma2
data1 = np.random.normal(mean1,sigma,n1)
data2 = np.random.normal(mean2,sigma,n2)
data = np.concatenate([data1 , data2])
#np.random.shuffle(data)
fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(111, xlabel='x', ylabel='y', title='mixture of 2 guassians')
ax.plot(range(0,n1+n2), data, 'x', label='data')
plt.legend(loc=0)
with pm.Model() as model:
#priors
p = pm.Uniform( "p", 0 , 1) #this is the fraction that come from mean1 vs mean2
ber = pm.Bernoulli( "ber", p = p) # produces 1 with proportion p.
precision = pm.Gamma('precision', alpha=0.1, beta=0.1)
mean1 = pm.Normal( "mean1", 0, 0.01 ) #better to use normals versus Uniforms (unless you are certain the value is truncated at 0 and 200
mean2 = pm.Normal( "mean2", 0, 0.01 )
mean = pm.Deterministic('mean', ber*mean1 + (1-ber)*mean2)
process = pm.Normal('process', mu=mean, tau=precision, observed=data)
# inference
step = pm.Metropolis()
trace = pm.sample(10000, step)
pm.traceplot(trace)
错误:
^{pr2}$
我知道这个问题是老问题,但我正在尝试不同的PyMC3用法示例,以适应PyMC3中的建模。上面给出的答案在PyMC3的当前版本1.0中不起作用(它不能正确地分配这两种方法)。为了使它正常工作,我必须做的最小的改变如下:
以防其他人也有类似的问题。在
更简单、更快速的版本如下:
感谢Fonnesbeck在github issue tracker上回答此问题:
https://github.com/pymc-devs/pymc3/issues/452
以下是更新后的代码:
在推断Bernoulli随机变量时,需要使用binarymetropoli
相关问题 更多 >
编程相关推荐