[英]What I am doing wrong in R to python translation?
我在 R 中有一個代碼,它實現了 Metropolis Hastings 算法:
trials <- 100000
sim <- numeric(trials)
sim[1] <- 2
for (i in 2: trials) {
old <- sim[i-1]
prop <- runif(1,0,5)
acc <- (exp(-(prop-1)^2/2) + exp(-(prop-4)^2/2)) /
( (exp(-(old-1)^2/2) + exp(-(old-4)^2/2)) )
if (runif(1) < acc)
sim[i] <- prop
else
sim[i] <- old }
mean(sim)
var(sim)
結果是正確的。
但是當我在 Python 中翻譯它時,結果就不同了。
trials = 100000
sim = np.repeat(0,trials+1)
sim[0] = 2
for i in range (2, trials):
old = sim[i-1]
prop = np.random.uniform(0,5,1)
acc = (np.exp(-(prop-1)**2/2) + np.exp(-(prop-4)**2/2)) /( (np.exp(-(old-1)**2/2) + np.exp(-(old-4)**2/2)) )
if np.random.uniform(1) < acc:
sim[i] = prop
else:
sim[i] = old
為什么? 我在這里做錯了什么?
首先,由於 Python 從0
開始,因此您希望在range(1, trials)
中的i=1
處啟動 python for 循環。
其次, if np.random.uniform(1)
你只是生產1.0
,所以需要改變,例如np.random.uniform(min, max, size=1)
或np.random.uniform(size=1)
如果您只想要一個介於 0 和 1 之間的統一數字。如果不清楚,請查看np.random.uniform
的文檔。
更新
第三,你在不知不覺中轉換為整數,所以這也需要處理。 當習慣了 R 時,這很容易忘記(我只是自己做的)。 我在下面重構了您的代碼,該解決方案應該為您提供與您在 R 中看到的類似的結果。
在這里,我將 sim 轉換為float
向量,並確保在exp
函數中使用浮點數進行減法和除法。 希望這對你有用。
trials = 100000
sim = np.repeat(0,trials).astype(np.float64)
sim[0] = 2.0
for i in range (1, trials):
old = sim[i-1]
prop = np.random.uniform(0,5,1)
acc = (np.exp(-(prop-1.0)**2/2.0) + np.exp(-(prop-4.0)**2/2.0)) \
/ ( (np.exp(-(old-1.0)**2/2.0) + np.exp(-(old-4.0)**2/2.0)) )
if np.random.uniform(size=1) < acc:
sim[i] = prop
else:
sim[i] = old
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.