![](/img/trans.png)
[英]How to calculate the joint probability distribution of two binomially distributed variables in Python?
[英]Two problems on writing a script to compute markov joint distribution (in python)
我是python的新手,最近我正在做一些項目,以執行markov進程的聯合分布計算。
隨機核的一個例子是漢密爾頓(2005)最近的一項研究中使用的一個核,該核根據美國失業數據研究了商業周期的非線性統計模型。 作為計算的一部分,他估算了內核
pH := 0.971 0.029 0
0.145 0.778 0.077
0 0.508 0.492
這里
S = {x1, x2, x3} = {NG, MR, SR}
,其中NG
正常增長,MR
輕度衰退,而SR
嚴重衰退。 例如,在一個時期內從嚴重衰退過渡到輕微衰退的可能性為0.508。 期限為一個月。
基於上述馬爾科夫過程的鍛煉是
關於漢密爾頓的內核
pH
,並使用相同的初始條件ψ=(0.2,0.2,0.6),計算在0、1、2周期內經濟開始並保持衰退的概率(即xt = NG fort = 0、1、2)。
我的劇本就像
import numpy as np
## In this case, X should be a matrix rather than vector
## and we compute w.r.t P rather than merely its element [i][j]
path = []
def path_prob2 (p, psi , x2): # X a sequence giving the path
prob = psi # initial distribution is an row vector
for t in range(x2.shape[1] -1): # .shape[1] grasp # of columns
prob = np.dot(prob , p) # prob[t]: marginal distribution at period t
ression = np.dot(prob, x2[:,t])
path.append(ression)
return path,prob
p = ((0.971, 0.029, 0 ),
(0.145, 0.778, 0.077),
(0 , 0.508, 0.492))
# p must to be a 2-D numpy array
p = np.array(p)
psi = (0.2, 0.2, 0.6)
psi = np.array(psi)
x2 = ((0,0,0),
(1,1,1),
(1,1,1))
x2 = np.array(x2)
path_prob2(p,psi,x2)
在執行過程中,出現兩個問題。 第一個是,在第一輪循環中,我不需要初始分布psi
來乘以交易矩陣p
,因此“保持衰退狀態”的概率應為0.2 + 0.6 = 0.8,但我不知道如何編寫if語句。 第二個是,正如您可能注意到的,我使用一個名為path
的列表來收集每個時期“保持衰退”的可能性。 最后,我需要將列表中的每個元素一次一乘,我沒有設法找到一種方法來實現這種任務,例如path[0]*path[1]*path[2]
(np.multiply據我所知,只能接受兩個參數)。 如果確實存在這種方法,請給我一些線索。 另一個問題是,請給我任何您認為可以使代碼更有效的建議。 謝謝。
如果我正確地理解了這一點,那么它應該可以工作(我很樂意為某些步驟/結果進行一些人工計算),請注意以下事實:我沒有使用if / else語句,而是從第二列開始進行迭代:
import numpy as np
# In this case, X should be a matrix rather than vector
# and we compute w.r.t P rather than merely its element [i][j]
path = []
def path_prob2(p, psi, x2): # X a sequence giving the path
path.append(np.dot(psi, x2[:, 0])) # first step
prob = psi # initial distribution is an row vector
for t in range(1, x2.shape[1]): # .shape[1] grasp # of columns
prob = np.dot(prob, p) # prob[t]: marginal distribution at period t
path.append(np.prod(np.dot(prob, t)))
return path, prob
# p must to be a 2-D numpy array
p = np.array([[0.971, 0.029, 0],
[0.145, 0.778, 0.077],
[0, 0.508, 0.492]])
psi = np.array([0.2, 0.2, 0.6])
x2 = np.array([[0, 0, 0],
[1, 1, 1],
[1, 1, 1]])
print path_prob2(p, psi, x2)
對於第二個問題,我相信Numpy.prod將使您在列表/數組的所有元素之間相乘。
您可以這樣使用prod:
>>> np.prod([15,20,31])
9300
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.