Generated quantities block in stan model

1.7k views Asked by At

i'm building a standard linear regression model and i want to include the generated quantities block and i want to use the dot_self() function. The problem is I canĀ“t get simulation samples. The error is: Stan model 'LinearRegression' does not contain samples. . I think the the function dot_self() is not being recognized as a function. I show stan code and R code here. Thanks in advance.

Note: I am sure that the data entered is correct because the model without the generated quantities block works perfectly.

Stan Code:

data {          
  int<lower=1> N;           
  int<lower=1> K;           
  matrix[N, K] X;           
  vector[N] y;              
}
parameters {                
  vector[K] beta;           
  real<lower=0> sigma;      
}
model{                     
  vector[N] mu;             
  mu = X * beta;             

  beta ~ normal(0, 10);
  sigma ~ cauchy(0, 5);                                     
  y ~ normal(mu, sigma);    
}

generated quantities {
  real rss;                
  real totalss;
  real<lower=0, upper=1> R2;                 
  vector[N] mu;
  mu=X * beta;
  rss=dot_self(y-mu);
  totalss=dot_self(y-mean(y));
  R2=1 - rss/totalss;
}

R Code to run Stan model:

library(rstan)
library(coda)
library(ggplot2)
rstan_options(auto_write=T)
options(mc.cores=parallel::detectCores())

dat=list(N=N, K=ncol(X), y=y, X=X)
fit3 = stan(file = "C:.... LinearRegression.stan", data = dat, iter = 100,chains = 4)

print(fit3, digits=3, prob=c(.025,.5,.975))
1

There are 1 answers

0
Jayyu On

The error is due to the bounds on R2. I believe there is no need to impose bounds on generated quantities.

Here I used simulated X and y:

X = matrix(runif(N*K), N, K)
y = rowSums(X)

The results after removing the bounds are:

enter image description here