Why Stan is so slow in this model?It takes over 10 minutes to run.What i must change?
# M U L T I N O M I A L
# R E G R E S S I 0 N
library(MASS)
data(birthwt)
head(birthwt)
birthwt$race
birthwt$smoke
birthwt$bwt
# Format categorical variables
birthwt$race = factor(birthwt$race)
birthwt$smoke = factor(birthwt$smoke)
# Set the reference group for prog to be 1
birthwt$race = relevel(birthwt$race, ref=1)
# Load the package
library(nnet)
# Run the model
model <- multinom(race ~ smoke + bwt, data=birthwt)
summary(model)
exp(coef(model))
coefs <- exp(coef(model));(1-coefs)*100
summary(model)$standard.errors
# Calculate z-values
zvalues <- summary(model)$coefficients / summary(model)$standard.errors
# Show z-values
zvalues
pnorm(abs(zvalues), lower.tail=FALSE)*2
X = model.matrix(model);X
y = birthwt$race
order(y)
X = X[order(y),]
y = y[order(y)]
# N = sample size, x is the model matrix, y integer version of class outcome, k=
# number of classes, D is dimension of model matrix
datalist = list(N=nrow(X), x = X, y=as.integer(y), K=n_distinct(y), D=ncol(X))
multinomial = "
data {
int<lower=1> K; // number of classes
int<lower=1> N; // nrow of x
int<lower=1> D; // ncol of x
int<lower=1, upper=K> y[N]; // target as integer
vector[D] x[N]; // array of D
}
transformed data {
row_vector[D] zeros; // create reference level coefs of zero
zeros = rep_row_vector(0, D);
}
parameters {
matrix[K-1,D] beta_raw; // estimated coefs
}
transformed parameters{
matrix[K, D] beta;
beta = append_row(zeros, beta_raw);
}
model {
to_vector(beta_raw) ~ normal(0, 10); // prior
for (n in 1:N)
y[n] ~ categorical_logit(beta * x[n]); // likelihood
}"
# categorical based on K-1,
# with prior for Betas Normal(0,10)
bayes_multinom = stan(model_code = multinomial,
data = datalist,
cores = 4,
chains = 4,
iter = 4000,
warmup = 500,
thin = 1,
seed = 23432,
control = list(adapt_delta=0.9))
print(bayes_multinom)
plot(bayes_multinom)