The summary function returns the describe of all model variables. Anyway, it takes a long time and I only need the summary of model parameter variables rather than latent variables and generated quantities variables. However , I’ve searched the manual paper but dont get the wanted API function。
Here is the example
// Bayesian Normal Linear Regression Model (IMOD)
data {
int<lower=0> N; // Number of observations
vector[N] w; // Regressor
vector[N] y; // Response variable
}
parameters {
real alpha; // Intercept
real beta; // Slope
real<lower=0> scaled_h; // Scale parameter
}
transformed parameters {
real<lower=0> h = 1/3 * scaled_h; // 进行缩放
}
model {
// Priors
alpha ~ normal(0, 10); // Normal prior for alpha
beta ~ normal(0, 10); // Normal prior for beta
scaled_h ~ chi_square(3); // Chi-square prior for h
// Likelihood method 1
//for (i in 1:N) {
// y[i] ~ normal(alpha + beta * w[i], 1 / sqrt(scaled_h)); // y_i given w_i
// }
// Likelihood method 2
y ~ normal(alpha + beta * w, 1 / sqrt(scaled_h)); // y_i given w_i
}
generated quantities {
vector[N] log_like; // 初始化 log_like 数组
vector[N] st_alpha; // 关于 alpha 的导数
vector[N] st_beta; // 关于 beta 的导数
vector[N] st_h; // 关于 h 的导数
for (i in 1:N) {
real mu = alpha + beta * w[i]; // 预测值
real scale = 1 / sqrt(h); // 标准差
log_like[i] = normal_lpdf(y[i] | mu, scale); // 计算每个观察值的对数似然
// 计算导数
st_alpha[i] = - (y[i] - mu) * scale; // 关于 alpha 的导数
st_beta[i] = - (y[i] - mu) * w[i] * scale; // 关于 beta 的导数
st_h[i] = -0.5 * (y[i] - mu) * (y[i] - mu) - 0.5 / h; // 关于 h 的导数
}
// 将导数拼接到一个变量中
matrix[N, 3] st;
for (i in 1:N) {
st[i, 1] = st_alpha[i];
st[i, 2] = st_beta[i];
st[i, 3] = st_h[i];
}
}
编译模型
model = cmdstanpy.CmdStanModel(stan_file='bayes_normal.stan')
运行采样
fit = model.sample(data = data_1,chains=4)
# 查看拟合结果的摘要信息
# print(fit.summary())
print(fit.summary(fit.stan_variable('beta','h'))
The last sentence is my purpose but it doesnot follow the rule. And I wonder how to tackle it.
Moreover, is there any group in any apps we can chat about the questions of cmdstan with each other.
[edit: escaped code]