Hey everyone––I’m having trouble fitting a Stan model using RStan. I feel like the issue is with a function called “weight” that I created in STAN that involves the Euclidian distance. Function that is applied to a random matrix ZZ generated from bivariate normal (function “weight” computes the Euclidian distance of ZZ rows and some other computation).
//Code of the model in STAN called "stancode"
functions{
//weight
matrix weight(matrix C, int nrows) {
matrix[nrows, nrows] dd;
matrix[nrows, nrows] W;
vector[nrows] Wf;
for(i in 1:nrows){
for(j in 1:nrows){
dd[i,j]=distance (to_vector (C[i,]), to_vector (C[j,])); // Euclidian distance
dd[i,j]=inv(dd[i,j]);// invers
}
dd[i,i] = 0;
for (k in 1:nrows){
Wf[k] = sum(dd[k,]);
}
for (l in 1:nrows){
W[l,]=dd[l,]/Wf[l];
}
}
return W;
}
}
data{
int<lower=1> n; // number of observations
vector[n] y; // dep_data
int x_p; // nr of covariates
matrix[n,x_p] x; //covariates
int<lower=1> J; // dimension of observations
vector[J] Zero; // a vector of Zeros (fixed means of observations)
corr_matrix[J] I;
}
parameters {
vector<lower=0>[J] tau;
real<lower=0> sigmasq;
matrix[n,J] ZZ; // latent-observations
vector[x_p+1] beta;// model parameter
}
transformed parameters{
cov_matrix[J] Tau;
Tau =quad_form_diag(I, tau);
}
model{
vector[n] mu;
matrix[n,n] W; // prepare data
W = weight(ZZ, n);//involve weight function
vector [n] E;
E=W *x[,2];
matrix [n,3] DD;
DD=append_col(x,E); // prepare data
mu = DD*beta; // model
for (i in 1:n){
ZZ[i,] ~ multi_normal(Zero, Tau); // generate ZZ
}
#prior
sigmasq ~ student_t(4,0,5)T[0, ]; //prior variance
tau ~ student_t(4,0,5)T[0, ]; ///prior variance
for (r in 1:x_p){
beta[r] ~ normal(0, 10); // prior regression parameters
}
#model
for(i in 1:n) y[i] ~ normal(mu[i],sigmasq); //run model
}
data
J<-2
I<-diag(2)
y<-vector[n,1]
x<-matrix[n,2]
x_p<- ncol(x)
fit ← stan(file=‘stancode.stan’,
data = list(n=n, n1=n1, x_p=x_p, y=y,x=x, J=J,Zero=rep(0, J),I=I), chains = 2, iter = 3000, warmup = 1000)
#Here’s what the error code reads:
Chain 1: Rejecting initial value:
Chain 1: Gradient evaluated at the initial value is not finite.
Chain 1: Stan can’t start sampling from this initial value.
Chain 1:
Chain 1: Initialization between (-2, 2) failed after 100 attempts.
Chain 1: Try specifying initial values, reducing ranges of constrained values, or reparameterizing the model.
[1] “Error : Initialization failed.”
[1] “error occurred during calling the sampler; sampling not done”
Also, I assigned some initial values but still got the same error.
Thanks