shp*_*igi 14 python markov-chains pymc
我试图弄清楚如何正确地制作离散状态马尔可夫链模型pymc.
作为一个例子(在nbviewer中的视图),让我们做一个长度为T = 10的链,其中马尔可夫状态是二进制的,初始状态分布是[ 0.2,0.8 ]并且在状态1中切换状态的概率是0.01而在状态2它是0.5
import numpy as np
import pymc as pm
T = 10
prior0 = [0.2, 0.8]
transMat = [[0.99, 0.01], [0.5, 0.5]]
Run Code Online (Sandbox Code Playgroud)
为了制作模型,我创建了一个状态变量数组和一个依赖于状态变量的转换概率数组(使用pymc.Index函数)
states = np.empty(T, dtype=object)
states[0] = pm.Categorical('state_0', prior0)
transPs = np.empty(T, dtype=object)
transPs[0] = pm.Index('trans_0', transMat, states[0])
for i in range(1, T):
states[i] = pm.Categorical('state_%i' % i, transPs[i-1])
transPs[i] = pm.Index('trans_%i' %i, transMat, states[i])
Run Code Online (Sandbox Code Playgroud)
对模型进行抽样显示状态边缘应该是它们应该是什么(与使用Matlab中的Kevin Murphy的BNT包构建的模型相比)
model = pm.MCMC([states, transPs])
model.sample(10000, 5000)
[np.mean(model.trace('state_%i' %i)[:]) for i in range(T)]
Run Code Online (Sandbox Code Playgroud)
打印出来:
[-----------------100%-----------------] 10000 of 10000 complete in 7.5 sec
[0.80020000000000002,
0.39839999999999998,
0.20319999999999999,
0.1118,
0.064199999999999993,
0.044600000000000001,
0.033000000000000002,
0.026200000000000001,
0.024199999999999999,
0.023800000000000002]
Run Code Online (Sandbox Code Playgroud)
我的问题是 - 这似乎不是用pymc建立马尔可夫链的最优雅方式.是否有更简洁的方法不需要确定性函数数组?
我的目标是为更一般的动态贝叶斯网络编写一个基于pymc的包.
据我所知,您必须将每个时间步的分布编码为前一个时间步的确定性函数,因为这就是它的本质——参数中不涉及随机性,因为您在问题设置中定义了它们。但是,我认为您的问题可能更多的是寻找一种更直观的方式来表示模型。一种替代方法是直接将时间步转换编码为前一时间步的函数。
from pymc import Bernoulli, MCMC
def generate_timesteps(N,p_init,p_trans):
timesteps=np.empty(N,dtype=object)
# A success denotes being in state 2, a failure being in state 1
timesteps[0]=Bernoulli('T0',p_init)
for i in xrange(1,N):
# probability of being in state 1 at time step `i` given time step `i-1`
p_i = p_trans[1]*timesteps[i-1]+p_trans[0]*(1-timesteps[i-1])
timesteps[i] = Bernoulli('T%d'%i,p_i)
return timesteps
timesteps = generate_timesteps(10,0.8,[0.001,0.5])
model = MCMC(timesteps)
model.sample(10000) # no burn in necessary since we're sampling directly from the distribution
[np.mean( model.trace(t).gettrace() ) for t in timesteps]
Run Code Online (Sandbox Code Playgroud)