On Jun 23, 2014, at 7:15 PM, Sam Weiss <
samc...@gmail.com> wrote:
> Hi again. I'm running the code below (same data) but its taking over 24 hours to complete... I'd like to do this with more than 2 time series as well. Is the code misspecified or inefficiently writen?
>
> Thanks,
>
>
> library(rstan)
> set_cppo("fast")
>
>
> code1=
> "data {
> int<lower=0> N;
> int<lower=1> K;
> vector[K] y[N];
>
> }
> parameters {
> corr_matrix[K] OmegaV;
> vector<lower=0>[K] tauV;
> corr_matrix[K] OmegaW;
> vector<lower=0>[K] tauW;
> vector[K] theta[N];
>
> }
> transformed parameters{
> matrix[K,K] SigmaV;
> matrix[K,K] SigmaW;
> cov_matrix[2] Sigmavprior;
>
>
> SigmaV <- diag_matrix(tauV) * OmegaV * diag_matrix(tauV);
>
> SigmaW <- diag_matrix(tauW) * OmegaW * diag_matrix(tauW);
There are more efficient scaling operations. diag_pre_multiply()
and diag_post_multiply() in Stan 2.2. In Stan 2.3 (out any
minute, really), there will also be a direct quadratic form that
will do this all at once.
>
>
> Sigmavprior[1,1] <- 100;
> Sigmavprior[2,2]<- 100;
> Sigmavprior[1,2] <- 0;
> Sigmavprior[2,1] <- 0;
>
> }
If you have anything constant like Sigmavprior, it's much
more efficient to define it as transformed data. All variables
should basically be declared in the earliest block that's feasible.
Also, no point making a diagonal covariance matrix. You can just
sample the components independently with a vectorized univariate
normal, replacing
> theta[1]~multi_normal(y[1], Sigmavprior);
with
theta[1] ~ multi_normal(y[1],100);
Now having said all this, you probably want to work directly
with Cholesky factors. You can do this one of two ways. Either
declare the Cholesky factors as variables (more efficient), or
Cholesky factorize a covariance matrix in the model itself and reuse
it with multi_normal_cholesky(). Alas, the Cholesky factor for
covariance matrix type is broken due to a misspelled error check in
2.2 (Ben --- this is why we try to be thorough in our signature
tests --- this one obviously didn't have enough testing); that's fixed
in 2.3 and there's also a Cholesky factor for correlation matrices type
and some explicit advice on how to use it in the manual.
> model{
> //prior
> theta[1]~multi_normal(y[1], Sigmavprior);
> //likelihood
> for(n in 2:N){
> theta[n]~multi_normal(theta[n-1],SigmaW);
> y[n]~multi_normal(theta[n],SigmaV);
>
> }
>
The implicit prior on covariances is improper, which can slow
down sampling --- are you seeing big excursions?
I like the first line written the other way around as
the equivalent
y[1] ~ multi_normal(theta[1], Sigmavprior);
to make it clear it's really part of the likelihood and to
make it clear you don't really have a prior here for theta[1].
Then you can add
theta[1] ~ normal(0,100);
if you want, but that prior's probably so weak as to have almost
no effect if your data are on a standardized scale.
- Bob