Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor local variables in STAN?

Tags:

stan

mcmc

I'm currently trying to port some JAGS models to STAN. I get some strange errors "stan::prob::exponential_log(N4stan5agrad3varE): Random variable is nan:0, but must not be nan!" and to debug those I would like to know the the values of some local parameters.

In JAGS I can set up monitors for any variable. STAN only monitors parameters. But parameter cannot have assignments (if I understand it correctly).

So how do I monitor intermediate variables?

I also paste the model code, in case someone sees a stupid mistake I make. Note, however, that I'm aware that the same model can be formulated as the CDF of a double exponential (with two rates). This is a simplified form of what I plan.

Model:

data {
    int y[11]; // 
    int reps[11];
    real soas[11]; 

}
parameters {
    real<lower=0.001,upper=0.200> v1;
    real<lower=0.001,upper=0.200> v2;

}


model {
    int dif[11,96];
    real cf[11];

    real p[11];

    real t1[11,96];
    real t2[11,96];

    for (i in 1:11){
        for (r in 1:reps[i]){     
            t1[i,r]  ~ exponential(v1);
            t2[i,r]  ~ exponential(v2);
            dif[i,r] <-  (t1[i,r]+soas[i]<=(t2[i,r]));

            }
        cf[i] <- sum(dif[i]);
        p[i]  <-cf[i]/reps[i];
        y[i] ~ binomial(reps[i],p[i]); 
    }

}

Here is some dummy data:

psy_dat = { 
         'soas' :  numpy.array(range(-100,101,20)),
            'y' :  [47, 46, 62, 50, 59, 47, 36, 13, 7, 2, 1],
         'reps' :  [48, 48, 64, 64, 92, 92, 92, 64, 64, 48, 48]
          }
like image 463
Jan Tünnermann Avatar asked Mar 18 '23 09:03

Jan Tünnermann


1 Answers

In this particular case, the problem is that t1 (and t2 for that matter) are initialized to NaN and not changed to anything before you utilize the exponential likelihood. My guess is that t1 and t2 need to be in a generated quantities block if you intend to draw them from their posterior predictive distribution.

To answer your question as stated, you can use a print() statement within the model block to debug a problematic Stan program. And if you really want to store intermediates, then you need to declare and define them within a transformed parameters block of the Stan program.

like image 175
Ben Goodrich Avatar answered May 16 '23 07:05

Ben Goodrich