開始使用免費開始

馬可夫鏈追蹤圖

「追蹤圖」能視覺化馬可夫鏈的縱向行為。具體來說,\(m\) 鏈的追蹤圖會將觀察到的鏈值(y 軸)對應到各自的迭代編號(x 軸)。

你將用兩種方式為 \(m\) 鏈建立追蹤圖:一是將內建的 plot() 套用到 mcmc.list 物件 sleep_sim;另一種是為了更細緻地掌控圖形(以及之後章節更細緻的分析),把 ggplot() 套用到 data.frame 物件 sleep_chainssleep_simsleep_chains 都已在你的工作環境中:

sleep_sim <- coda.samples(model = sleep_jags, variable.names = c("m", "s"), n.iter = 10000)
sleep_chains <- data.frame(sleep_sim[[1]], iter = 1:10000)

本練習屬於課程

使用 RJAGS 的貝氏建模

檢視課程

練習說明

  • sleep_sim 使用 plot(),並設定 density = FALSE,以建立 \(m\) 與 \(s\) 兩條鏈的追蹤圖。注意:記錄的 10,000 個 Iterations 是在「燒入(burn-in)」期間捨棄樣本之後才開始的。因此 Iterations 的計數未必從 1 開始!

  • sleep_chains 使用 ggplot() 加上 geom_line() 圖層,重現 \(m\) 鏈的追蹤圖。

  • 放大檢視:使用 ggplot() 繪製 \(m\) 鏈「前 100 次迭代」的追蹤圖。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Use plot() to construct trace plots of the m and s chains


# Use ggplot() to construct a trace plot of the m chain
ggplot(___, aes(x = ___, y = ___)) + 
    geom_line()

# Trace plot the first 100 iterations of the m chain
ggplot(___, aes(x = ___, y = ___)) + 
    geom_line()
編輯並執行程式碼