R帮忙。我正在运行一个简单的Gibbs采样器,用于mu和sig ^ 2,用于使用信息非共轭先验的正常数据

时间:2013-11-21 17:40:17

标签: r bayesian

Mu分布为N(0,1),sig ^ 2分布为IGamma(a,b),a = 1,b = 2.我试图创建几个图(直方图,散点图, ACF,PACF)但不断收到错误消息“xy.coords中的错误(x,y,xlabel,ylabel,log):   'x'和'y'长度不同“

这可能是一个愚蠢的问题,但我是r的新手。这是我到目前为止运行的程序

# Gibbs sampler, MODEL 2: semi-conjugate normal model

#
#  Density of inverse gamma distribution
#dinvgamma = function( x, shape, rate ) 
{
   exp( shape * log( rate ) - lgamma( shape ) -( shape+1)*log(x) - rate/x )
}

nn = 200
yy = rnorm( nn, 1, 4 )

mu.0 = 1.0

sig2.0 = 4^2

a = 2

b = 1

M = 10000

mu   = rep( 0, 10000 )
sig2 = rep( 1, 10000 )

mean.y = mean( yy )
var.y = var( yy )

mu[1]   = mean.y
sig2[1] = var.y 


for( ii in 2:M ) {

   mu.star <- ((1/sig2.0)*mu.0 + (nn/sig2 [ii-1])*mean(yy))/((1/sig2.0)+(nn/sig2 [ii-          1]))

   sig2.star <- 1/((1/sig2.0)+(nn/sig2[ii-1]))


   # sample mu from its full cond.
   #
   mu[ii] = rnorm( 1, mu.star, sqrt( sig2.star ))

   a.star <-  a + (nn/2)

   b.star <- (sum((yy-mu [ii])^2)/2) + b

   # sample sig2 from its full cond.
   #
   sig2[ii] = 1 / rgamma( 1, a.star, rate = b.star )

## print( c( mu[ii], sig2[ii] ))
}

mu <- mu[9001:length(mu)]
sig2  <-  sig2[9001:length(mu)]

#
# Time series
#
 par(mfrow=c(2,2))

 plot( 1:M, mu, type="l", xlab="Iteration", xlim=c(0, 50), ylim=c(0, 100),
       main= "Mu" )

 hist( mu, prob = T )
 x = seq( min(mu), max( mu ), len=200 )
 lines( x, dnorm( x, mean=mu.0, sd=sqrt(sig2.0) ), col=2, lwd=2)

 acf( mu )

 pacf( mu )

#++++++++++++++++++++++++++++++++++
par(new=TRUE)
 par(mfrow=c(2,2))

 plot( 1:M, sig2, type="l", xlab="Iteration", ylab="sig^2",xlim=c(0, 50), ylim=c(0,      100), main= "sig^2" )

 hist( sig2, prob = T )
 x = seq( 0, max( sig2 ), len=200 )
 lines( x, dinvgamma( x,  shape=a, rate=b ), col=2, lwd=2)

 acf( sig2 )

 pacf( sig2 )
 par(new=TRUE)
plot(mu, sig2, main="Scatterplot Example", xlim=c(0, 50), ylim=c(0, 100),xlab="mu ",     ylab="sig2 ", pch=19)

任何帮助都将非常感谢。我并不觉得我的代码有效甚至接近它,所以你认为必要的任何改变请随时告诉我

1 个答案:

答案 0 :(得分:1)

您的问题似乎来自重新定义这两个变量:

mu <- mu[9001:length(mu)]
sig2  <-  sig2[9001:length(mu)]

我对它们进行了评论,并且脚本运行良好,可以根据需要生成情节(大概)。也许看看你如何重新定义musig2