Sie sind auf Seite 1von 5

File = E:\inet\p548\rjags.intro.

docm

John Miyamoto

rjags Introduction
Contents (Cntrl-left click on a link to jump to the corresponding section)
Section

Topic

Basic Steps in Running JAGS with rjags


2

Annotated code for a typical rjags run


3

Functions in the rjags package


4

Parameters: How to determine the parameters of a statistical model


5

Random seeds: Setting random number generators for JAGS


# End of Contents Table

* FOR MAC USERS: Go to this link,


<http://martynplummer.wordpress.com/2011/11/04/rjags-3-for-mac-os-x/>.
There is a discussion of how to install JAGS on a Mac.

1. Basic Steps in Running JAGS with rjags

TOC

The following are typical steps in running JAGS with rjags. There are ways to alter these steps
that won't be discussed here.
PRELIMINARIES TO THE JAGS RUN:
i.
Run R. Load rjags onto the search path by using the library or require function.
ii.

Create a model file. This is a text file written in the JAGS language that defines the statistical
model that is assumed to generate the data.
* This step is very important. The model file must define the model(s) that you are intending to study, i.e., you could
accidentally define a different model and draw incorrect conclusions if you did not notice your error.
* You must know the file name for the model file. You must know (keep a record of) the names of every data object
(vector, matrix, list) that you intend to pass from R to JAGS. You must know the names of every (keep a record of)
every parameter in your model.

iii.
iv.

In R, create a named list whose components are the data objects (vectors, matrices, lists) that you
intend to pass to JAGS1.
Create variables that will be used to tell rjags how the JAGS run should proceed. These
variables include things like the number of chains of samples to compute, how many burnin
samples to compute, how many samples to save to send back to R, etc.

THE ACTUAL rjags & JAGS run:


The following are rjags commands (issued in R) that run JAGS:
v.

vi.
vii.

jags.model function: This function tells JAGS what is the model that you are fitting, what are
the data, what are the initial values of parameters, how many chains, and how many adaptation
steps.
update function: This function is used to run the burnin samples without saving them.
jags.output = coda.samples( ... ): This function call tells JAGS to compute the
samples that you want to save and return to R. The samples are stored in an MCMC list called

Alternatively, you can create a named list whose components are the names of the data objects that you intend to pass to
JAGS. This has the same effect when you run JAGS.

File = E:\inet\p548\rjags.intro.docm

jags.output (you can choose any other name).


Alternative method:
jags.output = jags.samples( ... ): This function call tells JAGS to compute the
samples that you want to save and return to R.
* jags.samples and coda.samples perform the same computations, but they differ in how they structure the output.
jags.samples returns the output in the form of a special kind of array in the class mcarray. coda.samples
returns the output in the form of a special kind of list in the class mcmc.list. An mcmc.list object is structured to
serve as input to functions in the coda package which contains a variety of functions for MCMC convergence
diagnostics.
* Either type of output is satisfactory, and it is not difficult to transform an mcmc.list list to a mcarray array, or vice
versa.

viii.

Now you are ready to use R to analyze the results. They have been stored in jags.output (or
whatever you have named it).

2. Annotated code for a typical rjags run

TOC

Table 1. Variables in R that control the rjags run


# R Code

Explanation

# Set run parameters (settings that control the


run)

1:

# sw.bugs function is in jmfuns.rda.


sw.bugs("rjags")

2: Switch the search path to a rjags configuration.

model.file = "name of model file"

3: Include path to file if necessary

dataList = list( .... )

4: Make a named list of data objects that will be passed to JAGS.


Alternatively, you can simply make a list of the names of the data
objects.

parameters = ....

5: Vector of names of variables to be monitored (saved). These


names appear in the model file.

n.chains = ....

6: Set number of chains

# Method 1 for setting initial values


inits.lst = list(
chain1 = list( ... ),
....,
chainK = list( ... ) )

7: The list components do not have to have names, and do not


need the specific names "chain1", ..., "chainK".

# Method 2 for setting initial values


inits.fn = function() {
list( .... )
} #end def of 'inits.fn =' function

8: The initial values is set by a function that outputs a list. Each


list has named components setting initial values for every sampled
parameter in the model file.

# Method 3 for setting initial values


inits.fn = NULL

9: If you set the initial values to NULL (or if you totally omit any
specification of the initial values), then JAGS will choose initial
values at random from the permissible values of parameters. This
is the easiest way to deal with initial values.

n.adapt

10: Set the number of adaptation steps to tune the sampler.

= ....

n.burnin = ....

11: Set number of iterations for burnin.

n.iter

= ....

12: Set the number of samples to be kept after the burnin samples
are discarded.

n.thin

= ....

13: Set the thinning rate.


14:
15:

# Start of rjags control of an JAGS run.

16:

j.mod = jags.model(

17: jags.model is used to create an object representing a

File = E:\inet\p548\rjags.intro.docm

# R Code

Explanation

file
data
inits
n.chains
n.adapt

=
=
=
=
=

model.file,
dataList,
inits.lst,
n.chains,
n.adapt )

Bayesian graphical model, specified with a BUGS-language


description of the prior distribution, and a set of data. Note that
the output (j.mod in this case) is not the samples from the
posterior. It is a list whose components define the model.

You can omit inits and n.adapt;


JAGS will decide for itself how to set
these values.

update( object = j.mod ,


n.iter = n.burnin )

18: Compute burnin samples. They will not be saved.

j.out = coda.samples(
model
= j.mod,
variable.names = parameters,
n.iter
= n.iter,
thin
= n.thin )

19: coda.samples outputs the chains of samples in MCMC


list format. The output is a list of class "mcmc.list".

Comment 1: One can replace the call to coda.samples with a call to jags.samples - the latter
function outputs the chains as a list of arrays. For example, if the variable sigma is not indexed, i.e.,
there is no sigma[1], sigma[2], ..., then jags.samples will output an array of dimension
1 n.iter n.chains for the sigma variable. If the beta variable has 5 indices, beta[1], ...,
beta[5], then jags.samples will output a list that has a beta component with dimension 5
n.iter n.chains.
Comment 2: It may be useful to apply the jags.chains function to the output from coda.samples.
The syntax would be:
new.chains = jags.chains( sample = j.out, model = j.mod )

3. Functions in the rjags package

TOC

Table 2. Functions in the rjags package


jags Function Explanation
coda.samples

jags.model

jags.samples

This is a wrapper function for jags.samples which sets a trace monitor for all requested nodes,
updates the model, and coerces the output to a single mcmc.list object. jags.samples
extracts random samples from the posterior distribution of the parameters of a jags model.
o jags.samples and coda.samples perform the same computations, but
they differ in how they structure the output. jags.samples returns the output
in the form of a special kind of array in the class mcarray. coda.samples
returns the output in the form of a special kind of list in the class mcmc.list.
An mcmc.list object is structured to serve as input to functions in the coda
package which contains a variety of functions for MCMC convergence
diagnostics.
jags.model is used to create an object representing a Bayesian graphical model, specified with a
BUGS-language description of the prior distribution, and a set of data. Note: Its output is a
specification of the model; the output is not the actual samples from the posterior distribution. Use
jags.sample, coda.samples and update to compute samples.
jags.samples extracts random samples from the posterior distribution of the parameters of a
jags model.
o jags.samples and coda.samples perform the same computations, but
they differ in how they structure the output. jags.samples returns the output
in the form of a special kind of array in the class mcarray. coda.samples
returns the output in the form of a special kind of list in the class mcmc.list.
An mcmc.list object is structured to serve as input to functions in the coda

ord
1

File = E:\inet\p548\rjags.intro.docm

jags Function

Explanation

read.bugsdata

package which contains a variety of functions for MCMC convergence


diagnostics.
Read data for a JAGS model from a file.

read.jagsdata
update

------------adapt

ord

Read data for a JAGS model from a file.


This function is not part of the rjags package (it is part of the stats package, which is installed
by default along with the standard R installation). update can be used to sample from a posterior
without saving the samples. This is useful when drawing burnin samples.

Below: Technical functions, less important for the beginner

dic.samples

Run the adaptation iterations for tuning the sampler. This function is not normally called by the
user. It is called by the jags.model function when the model object is created.
Function to extract random samples of the penalized deviance from a jags model.

diffdic

Compare two models by the difference of two dic objects.

list.factories JAGS modules contain factory objects for samplers, monitors, and random number generators for a
JAGS model. These functions allow fine-grained control over which factories are active.
list.factories returns a data frame with two columns, the first column shows the names of
the factory objects in the currently loaded modules, and the second column is a logical vector
indicating whether the corresponding factory is active or not.
A JAGS module is a dynamically loaded library that extends the functionality of JAGS. These
list.modules
functions load and unload JAGS modules and show the names of the currently loaded modules. This
function lists the currently loaded modules.
list.samplers A jags object represents a Bayesian graphical model described using the BUGS language. The
output displays the algorithms that have been applied to each model parameter in the computation of
the MCMC chain.
A JAGS module is a dynamically loaded library that extends the functionality of JAGS. This
load.module
function loads JAGS modules and shows the names of the currently loaded modules.
parallel.seeds On a multi-processor system, you may wish to run parallel chains using multiple jags.model
objects, each running a single chain on a separate processor. This function returns a list of values
that may be used to initialize the random number generator of each chain.
OBSOLETE: This function is provided for compatibility with older versions of the rjags package
read.data
and will soon be defunct. This function has been replaced with the read.jagsdata function in
the current version of JAGS.
JAGS modules contain factory objects for samplers, monitors, and random number generators for a
set.factory
JAGS model. These functions allow fine-grained control over which factories are active.
set.factory is called to change the future behaviour of factory objects. If a factory is set to
inactive then it will be skipped.
unload.module A JAGS module is a dynamically loaded library that extends the functionality of JAGS. This
function unloads JAGS modules and show the names of the currently loaded modules.

4. Parameters: How to determine the parameters of a statistical model

TOC

Sometimes it is advantageous to set initial values for the various chains in a statistical model. To
do so, it is necessary to identify the parameters of the statistical model. How to do this?
A researcher should be able to look at a model file and determine what are the parameters of the
model. This is especially true if the researcher wrote the model file himself or herself. But
sometimes this is difficult.
An alternative is to run the jags.model function in rjags. Then apply the list.samplers
function to the output of the jags.model function - this will produce a list of the MCMC sampling
algorithm that has been applied to each parameter in the model, thereby identifying the model
parameters.

File = E:\inet\p548\rjags.intro.docm

The variable.names function in rjags lists all variables in the model file, including constants
and derived variables that do not have samplers assigned to them.

5. Random seeds: Setting random number generators for JAGS

TOC

See the documentation for jags.model.


Random number generators are set through the specification of initial values. You need to set initial
values for all model parameters. In addition, initial values are set for two additional components
names .RNG.name and .RNG.seed. .RNG.name is a string that names a random number generator
algorithm. See ?set.seed to see the names of random number generators that are available in R.
RNGkind() shows the default random number generator for R. The following is an example of initial
values for 3 chains that set initial values for the JAGS random number generators:
iniVals = list(
list( <initial
.RNG.name =
list( <initial
.RNG.name =
list( <initial
.RNG.name =

values for all model parameters>,


"base::Mersenne-Twister", .RNG.seed = 2 ),
values for all model parameters>,
"base::Mersenne-Twister", .RNG.seed = 4 ),
values for all model parameters>,
"base::Mersenne-Twister", .RNG.seed = 6) )

# You have to set initial values for all of the parameters because if you don't, JAGS will choose initial values at random, and
these choices will not be controlled by the .RNG.seed that you choose in the initial values.
jagsModel = jags.model( file = "testmod.txt", data = dataList,
inits = iniVals, n.chains = 3, n.adapt = adaptSteps )

************************************************************************

Das könnte Ihnen auch gefallen