首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

r语言使用rjags R2jags建立贝叶斯模型

本文是通过对area,perimeter,campactness几个变量的贝叶斯建模,来查看他们对groovelength这个变量的影响,并且对比rjags R2jags和内置贝叶斯预测函数的结果。

相关视频

读取数据

seed=read.csv("seeds_dataset.csv")

seed=seed\[,1:7\]

查看数据的结构

str(seed)

'data.frame':    209 obs. of  7 variables:

$ area        : num  14.9 14.3 13.8 16.1 14.4 ...

$ perimeter   : num  14.6 14.1 13.9 15 14.2 ...

$ campactness : num  0.881 0.905 0.895 0.903 .895 ...

$ length      : num  5.55 5.29 5.32 5.66 5.39 ...

$ width       : num  3.33 3.34 3.38 3.56 3.31 ...

$ asymmetry   : num  1.02 2.7 2.26 1.35 2.46 ...

$ groovelength: num  4.96 4.83 4.8 5.17 4.96 ...

建立回归模型

Residuals:

Min       1Q   Median       3Q      Max

-0.66375 -0.10094  0.00175  0.11081  0.45132

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept)  19.46173    2.45031   7.943 1.29e-13 ***

area          0.49724    0.08721   5.701 4.10e-08 ***

perimeter    -0.63162    0.18179  -3.474 0.000624 ***

campactness -14.05218    1.34325 -10.461  

---

Signif. codes:   '***' .001 '**' .01 '*' .05 '.' .1 ' ' 1

Residual standard error: .1608 on 205 degrees of freedom

Multiple R-squared:  .895,  Adjusted R-squared:  .8934

F-statistic: 582.4 on 3 and 205 DF,  p-value: 

从回归模型的结果来看,三个自变量对因变量都有显著的意义。其中,area有正向的影响。而其他两个变量是负向的影响。从r方的结果来看,达到了0.895,模型具有较好的解释度。

建立贝叶斯回归模型

Bayesian analysis

With bayesglm

Deviance Residuals:

Min        1Q    Median        3Q       Max

-0.66331  -0.09974  -0.00002   0.11110   0.44841

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept)  18.90538    2.41549   7.827 2.63e-13 ***

area          0.47826    0.08604   5.559 8.40e-08 ***

perimeter    -0.59252    0.17937  -3.303  0.00113 **

campactness -13.74353    1.32463 -10.375  

---

Signif. codes:   '***' .001 '**' .01 '*' .05 '.' .1 ' ' 1

(Dispersion parameter for gaussian family taken to be 0.02584982)

Null deviance: 50.4491  on 208  degrees of freedom

Residual deviance:  5.2992  on 205  degrees of freedom

AIC: -164.91

Number of Fisher Scoring iterations: 6

从内置贝叶斯模型的结果来看,3个变量同样是非常显著,因此模型的结果和回归模型类似。然后我们使用BUGS/JAGS软件包来建立贝叶斯模型

使用 BUGS/JAGS软件包来建立贝叶斯模型

建立贝叶斯模型

jags(model.file='bayes.bug',

parameters=c("area","perimeter","campactness","int"),

data = list('a' = seed$area, 'b' = seed$perimete

n.cha

查看模型结果:

从上面的图中,我们可以看到自变量的中位数和置信区间。从置信区间来看,各个变量的取值和贝叶斯模型的结果类似。贝叶斯结果的值全部落入在了置信区间内。

然后绘制每次迭代中各个变量参数的轨迹图

trace + density #轨迹图

可以看到每个变量的参数都在一定区间内波动。同时可以看到误差在一定的迭代次数之后趋于收敛。

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20221017A04T8J00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券