简体   繁体   English

从mcmc对象重构变量

[英]Reconstructing variables from mcmc objects

I am using rjags as a sampler. 我正在使用rjags作为采样器。 The model has 3 matrices defined. 该模型定义了3个矩阵。 The coda.samples function returns a list of samples. coda.samples函数返回样本列表。 If I take the first sample list the column names look something like this: 如果我选择第一个示例列表,则列名看起来像这样:

> colnames(output[[1]])
"A[1,1]"  "A[2,1]"  "A[1,2]"  "A[2,2]" ... 
"B[1,1]"  "B[2,1]"  "B[3,1]"  "B[4,1]" ... 
"C[1,1]"  "C[2,1]"

Obviously, A, B and C are matrices in my model. 显然,A,B和C是我模型中的矩阵。 I want to reconstruct them based on the mean of these samples. 我想根据这些样本的平均值重建它们。 I can easily get the means with colMeans(output[[1]]) but I have no idea how to easily reconstruct the matrices from this vector. 我可以使用colMeans(output[[1]])轻松获得均值,但我不知道如何轻松地从该向量中重构矩阵。

A good way for reconstruction would be the relist() function. 重构的一个好方法是relist()函数。 So If I had matrices A, B and C in a list L = list(A=A,B=B,C=C) then I could transform this list to a vector with unlist() and convert back with relist() . 所以如果我有矩阵A,B和C在列表L = list(A=A,B=B,C=C)然后,我可以转换该列表与一个矢量unlist()并与转换回relist() I am looking for something similar/readymade for mcmc objects, but without avail so far - I can't believe I am the first one needing this. 我正在为mcmc对象寻找类似/现成的东西,但到目前为止无济于事-我不敢相信我是第一个需要此东西的人。 Obviously, relist(colMeans(output[[1]])) doesn't work. 显然, relist(colMeans(output[[1]]))不起作用。

Anyone can help me with reconstructing? 有人可以帮助我进行重建吗?

Edit: note also that the relist() function only needs a skeleton, so extracting the skeleton from colnames(output[[1]]) would also do the trick. 编辑:还请注意, relist()函数仅需要一个框架,因此从colnames(output[[1]])提取框架也可以解决问题。 Or am I complicating? 还是我很复杂?

I don't think relist() will do the trick... 我认为relist()不会成功。

I assume your object output is an object of class mcmc.list , as defined in the R package coda , and output[[1]] is an object of class mcmc representing the sample for the first MCMC chain. 我假设您的对象output是R包coda定义的mcmc.list类的对象,而output[[1]]mcmc类的对象,代表第一个MCMC链的样本。

I'm pretty sure coda does not have any understanding that eg "A[1,1]" is a JAGS matrix, it just handles it as a variable name. 我很确定, coda没有任何理解,例如"A[1,1]"是一个JAGS矩阵,它只是将其作为变量名来处理。 So you'll have to iterate over the relevant variables and impose the structure yourself. 因此,您必须遍历相关变量并自己强加该结构。

Ideally you'd wrap this in a function like the following: 理想情况下,将其包装在如下函数中:

getMatrix <- function(output, varname, rows, cols) {
  unname(
    sapply(1:cols, function(j)
      sapply(1:rows, function(i)
        summary(output[,sprintf("%s[%s,%s]", varname, i, j)])[[1]][1]
      )
    )
  )
}

Thus, for example, if your matrix B stored in output[[1]] has 3 rows and 4 columns you'd write: 因此,例如,如果存储在output[[1]]矩阵B具有3行4列,则您应该编写:

getMatrix(output[[1]], "B", 3, 4)

to get the means as a matrix object in R. 获得均值作为R中的矩阵对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM