開始使用免費開始

視覺化迴歸先驗

在前一個練習中,你為貝葉斯迴歸模型中體重 \(Y\) 與身高 \(X\) 的各個參數($a$、$b$、$s$)模擬了 10,000 筆 samples:$Y \sim N(m, s^2)$,其中平均數 $m = a + bX$。samples 的每一個「列」中的 $a$、$b$、\(s\) 值代表一組先驗下可行的迴歸情境。為了探索這些先驗情境的範圍,你將從前 12 組先驗參數($a$、$b$、$s$)的每一組,模擬 50 對身高與體重的數值。

本練習屬於課程

使用 RJAGS 的貝氏建模

檢視課程

練習說明

  • 建立資料框 prior_simulation,其中包含 samples 中前 12 組先驗參數各自的 n = 50 個「複本」(共 600 列!)。
  • 對於 600 列 prior_simulation 中的每一列:
    • 從 \(N(170, 10^2)\) 模型模擬一個 height 值。
    • 從 \(N(a + b X, s^2)\) 模型模擬一個 weight 值,其中 \(X\) 為 height,\((a,b,s)\) 為該列的先驗參數組。
  • 現在,每一組參數你都有 50 對模擬出的 heightweight。使用 ggplot() 為每個參數 set 繪製這 50 對的散佈圖。記得把 weight 放在 y 軸!

動手互動練習

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

# Replicate the first 12 parameter sets 50 times each
prior_scenarios_rep <- bind_rows(replicate(n = ___, expr = samples[1:12, ], simplify = FALSE)) 

# Simulate 50 height & weight data points for each parameter set
prior_simulation <- prior_scenarios_rep %>% 
    mutate(height = rnorm(n = 600, mean = ___, sd = ___)) %>% 
    mutate(weight = rnorm(n = 600, mean = ___, sd = ___))

# Plot the simulated data & regression model for each parameter set
ggplot(prior_simulation, aes(x = ___, y = ___)) + 
    geom_point() + 
    geom_smooth(method = "lm", se = FALSE, size = 0.75) + 
    facet_wrap(~ set)
編輯並執行程式碼