【问题标题】:Error: Attempt to redefine node in linear regression错误:尝试在线性回归中重新定义节点
【发布时间】:2020-08-17 19:52:15
【问题描述】:

我使用rjags 安装了以下simple linear regression Bayesian 模型。 我能够通过分别指定所有预测变量来运行模型(例如 lm 对象)。现在我想学习如何通过将它们作为矩阵引入而不是单独指定它们来指定预测变量。

所以我运行了以下代码,但它给出了一些错误。

我使用rrr 包中的tobbaco 数据集提供了一个可重现的示例。

library(rrr)
require(dplyr)
library(rjags)
tobacco <- as_data_frame(tobacco)
N1 = length(tobacco$Y1.BurnRate)
x1 = model.matrix(Y1.BurnRate~X2.PercentChlorine+X3.PercentPotassium ,data = tobacco)
        
bayes_model_mul1=
 "model {
      for(i in 1:N1){
        Y1.BurnRate[i]~dnorm(mu1[i],tau1)
        
        for(j in 1:3){
          mu1[i]=beta1[j]*x1[i,j]  
        }
      }
      
      for (l in 1:3) { beta1[l] ~dnorm(0, 0.001) }        
      tau1 ~ dgamma(.01,.01)
      sigma_tau1 = 1/tau1 
        
    }"
        
        
model3 <- jags.model(textConnection(bayes_model_mul1), 
                     data = list(Y1.BurnRate=tobacco$Y1.BurnRate, x1=x1, N1=N1),
                     n.chains=1)

运行 model3 后,出现以下错误。

jags.model 中的错误(textConnection(bayes_model_mul1),数据 = 列表(Y1.BurnRate = 烟草$Y1.BurnRate,:
运行时错误:
第 6 行编译错误。
尝试重新定义节点mu1[1]

谁能帮我解决这个问题? 这是因为将预测变量作为矩阵引入吗?

【问题讨论】:

    标签: r linear-regression bayesian rjags


    【解决方案1】:

    有几种方法可以做到这一点,这里有两种:

    1. 在似然循环之外使用矩阵乘法
    m1 =
     "model {
         mu1 = x1 %*% beta1 # ---> this
         for(i in 1:N1){
           Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
        }
    
        for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
        tau1 ~ dgamma(.01,.01)
        sigma_tau1 = 1/tau1 
     }"
    
    1. 使用inprod 将参数与设计矩阵相乘
    m2 = 
      "model {
        for(i in 1:N1){
          mu1[i] = inprod(beta1, x1[i,]) #----> this
          Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
        }
    
        for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
        tau1 ~ dgamma(.01,.01)
        sigma_tau1 = 1/tau1 
     }"
    

    您收到for(j in 1:3){ mu1[i] = beta1[j]* x1[i,j] } 的错误,因为每次循环参数索引j 时都会覆盖mu1[i]。它也没有总结各个条款。您也可以将mu1 与j 索引,然后将sum 索引,但未经测试...

    【讨论】:

    • 您好,谢谢您的回答。我还有另一个问题,如果您也可以对此发表评论,那就太好了。获得 MCMC 样本后,从上面的代码中,我收到以下警告消息“警告消息:以前也针对不同的贝叶斯模型收到此警告。所以我对此很好奇。你能对此发表评论吗?
    • 嗨@student_R123;请问警告信息是什么?以及生成它的代码是什么?
    • 谢谢。那来自window 函数。如果您重新运行coda.samples 而不再次运行jags.model,您可能会收到此警告/有时会出现错误。即从来没有仔细研究过,只是重新运行jags.model
    • ...如果您查看str(samps.1),您将看到一个属性attr(samps.1[[1]], "mcpar"),它会在您运行coda.samples 时增加,而无需重新运行jags.model。这会抛出 window 函数的 start 和 end 时间,我不确定为什么这个值会增加......它可能正在更新模型并从上一次运行结束开始??
    • 感谢您的评论。老实说,我对此一无所知。我正在从头开始学习贝叶斯。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2018-04-09
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2020-08-04
    相关资源
    最近更新 更多