基于JAGS的贝叶斯回归敏感性分析:多数据集生成与预测结果统计实现方法问询
Got it, let's walk through how to integrate this sensitivity analysis workflow into your existing Bayesian regression model step by step. Here's a practical, reproducible approach:
First, instead of writing the model to a text file every time, we'll define it as a string and use textConnection() to pass it to JAGS directly—this avoids messy file I/O in loops.
library(rjags) library(R2jags) # Define the Bayesian model as a string model_str <- "model{ for(i in 1 :N){ y[i] ~ dnorm(theta[i],tau) theta[i] <- beta[1] + beta[2]*x1[i] + beta[3]*x2[i] } for(j in 1:3){ beta[j] ~ dnorm(0,0.001) } sigma ~ dgamma(0.001,0.001) tau <- pow(sigma,-2) }"
Generate all possible pairs of v (0 to 51, step 1) and m (2 to 48, step 1) using expand.grid():
# Create all v and m combinations v_vals <- seq(0, 51, by = 1) m_vals <- seq(2, 48, by = 1) param_grid <- expand.grid(v = v_vals, m = m_vals)
Wrap the entire workflow (data generation, model training, prediction, counting matches) into a reusable function. I've assumed your "y基准值" is a range (e.g., y_pred between -1 and 1)—adjust this threshold to match your actual needs!
# Define your y baseline threshold (modify this to match your requirements) y_baseline_low <- -1 y_baseline_high <- 1 run_sensitivity_iteration <- function(v_val, m_val) { # Generate the dataset for this v/m combination: 20 rows with fixed v and m set.seed(123) # Optional: ensures reproducibility across iterations dd <- data.frame( y = rnorm(20, 0, 1), # Random y values as specified x1 = rep(v_val, 20), # All x1 = current v value x2 = rep(m_val, 20) # All x2 = current m value ) d <- with(dd, list(N = length(y), y = y, x1 = x1, x2 = x2)) # Train the Bayesian model model_fit <- jags( data = d, inits = NULL, parameters.to.save = c("beta", "tau"), n.chains = 3, n.iter = 10000, n.burnin = 5000, n.thin = 10, model.file = textConnection(model_str) # Use the model string directly ) # Extract posterior mean of beta coefficients for prediction beta_estimates <- colMeans(model_fit$BUGSoutput$sims.list$beta) # Predict 20 y values using the trained beta coefficients y_pred <- beta_estimates[1] + beta_estimates[2] * dd$x1 + beta_estimates[3] * dd$x2 # Count how many predictions fall within the baseline range match_count <- sum(y_pred >= y_baseline_low & y_pred <= y_baseline_high) return(match_count) }
Since we have 52 * 47 = 2444 combinations, running this serially might be slow. We'll use parallel processing to speed things up (skip this if you don't need it, but it's highly recommended):
# Optional: Parallel processing to speed up the loop library(foreach) library(doParallel) # Set up parallel cluster (use all cores minus 1) cl <- makeCluster(detectCores() - 1) registerDoParallel(cl) # Run the function across all parameter combinations param_grid$match_count <- foreach( i = 1:nrow(param_grid), .packages = c("rjags", "R2jags"), .combine = c ) %dopar% { run_sensitivity_iteration(param_grid$v[i], param_grid$m[i]) } # Stop the parallel cluster stopCluster(cl) # If you don't want parallel processing, use this serial loop instead: # param_grid$match_count <- apply(param_grid, 1, function(row) { # run_sensitivity_iteration(as.numeric(row["v"]), as.numeric(row["m"])) # })
- Dataset Generation: I assumed each dataset has 20 rows with fixed
vandmvalues. If you meant something else (e.g.,vranges from 0 to the current value instead of being fixed), adjust thedddata frame in the function. - Baseline Value: Modify
y_baseline_lowandy_baseline_highto match your actual "y基准值"—this could be a single value (usey_pred == baseline), a range, or another criterion. - Reproducibility: The
set.seed(123)inside the function ensures each iteration's dataset is consistent. Remove it if you want fully random datasets each time.
内容的提问来源于stack exchange,提问作者new_student

