Hello all,
I am trying to fit a varying slope model. I have 5 predictors.
Usually, when I am estimating a simple fixed effects model, I declare independent variables to be a matrix in the data section of Stan as matrix[N, K] X; where K is the number of predictors and N is the number of observations.
Then in the parameters section coefficients to be estimated is declared as vector[K] beta;
Finally in the model section, I usually set up likelihood as :
for (i in 1:N) {
Y[i]~ student_t(nu, grand_mean + X[i]*beta, sigma);
}
However, I do not know how to put all the coefficients in vector form when estimating a varying slope model. I have quite a lot of predictors, so I really need it to be vectorized for efficiency.
Here is my code for not so efficient varying slopes model.
If someone could just help me with a more efficient declaration of the model, I would be very grateful.
Thanks.
data {
int<lower=0> N; // Number of data items
int<lower=0> J; // Number of units
int<lower=0> K; // Number of predictors
vector[N] Y; // dependent variable
vector[N] X_IP; /// Independent variables
vector[N] X_OP;
vector[N] X_OTH;
vector[N] X_CLIN;
vector[N] X_OUT;
int<lower=1,upper=J> dhb_id[N]; // unit id's
}
parameters {
vector[5] beta;
real grand_mean;
real<lower=0> sigma;
vector[J] DHB_specific_intercept;
real<lower=0> sigma_DHB_specific_intercept;
matrix[5,J] DHB_re; // DHB specific slope
vector<lower=0> [5] sigma_DHB_re;
real nu;
}
transformed parameters {
}
// The model to be estimated.
model {
beta ~ normal(0,5);
grand_mean ~ normal(0,5);
sigma_DHB_specific_intercept~ inv_gamma(2,0.5);
DHB_specific_intercept ~ normal(0,sigma_DHB_specific_intercept);
for(k in 1:K) {
sigma_DHB_re[k] ~ inv_gamma(2,0.5);
DHB_re[k] ~ normal(0, sigma_DHB_re[k]);
}
sigma ~ inv_gamma(2,0.5);
nu ~ gamma(2,0.05);
for(i in 1:N) {
Y[i] ~ student_t(nu, grand_mean + DHB_specific_intercept[dhb_id[i]]
+ (beta[1] + DHB_re[1,dhb_id[i]])*X_IP[i]
+ (beta[2] + DHB_re[2,dhb_id[i]])*X_OP[i]
+ (beta[3] + DHB_re[3,dhb_id[i]])*X_OTH[i]
+ (beta[4] + DHB_re[4,dhb_id[i]])*X_CLIN[i]
+ (beta[5] + DHB_re[5,dhb_id[i]])*X_OUT[i], sigma);
}
}
generated quantities {
}