1

我已经开发了使用 R 包 brms 估计模型的管道,现在我需要将其转换为 python。我知道我可以在 python 中最接近 brms 的是 pystan,我必须使用 Stan 语法编写我的模型。我想知道是否有一个 brms 函数可以生成 Stan 代码,该代码可以用作 python 中 pystan.StanModel 函数的 model_code 参数。我曾尝试使用 make_stancode 函数生成的代码,但没有奏效。

这是 make_stancode 生成的代码:

life_span_code = """
// generated with brms 2.10.0
functions {

  /* compute monotonic effects
   * Args:
   *   scale: a simplex parameter
   *   i: index to sum over the simplex
   * Returns:
   *   a scalar between 0 and 1
   */
  real mo(vector scale, int i) {
    if (i == 0) {
      return 0;
    } else {
      return rows(scale) * sum(scale[1:i]);
    }
  }
}
data {
  int<lower=1> N;  // number of observations
  vector[N] Y;  // response variable
  int<lower=1> Ksp;  // number of special effects terms
  int<lower=1> Imo;  // number of monotonic variables
  int<lower=2> Jmo[Imo];  // length of simplexes
  // monotonic variables
  int Xmo_1[N];
  // prior concentration of monotonic simplexes
  vector[Jmo[1]] con_simo_1;
  int prior_only;  // should the likelihood be ignored?
}
transformed data {
}
parameters {
  // temporary intercept for centered predictors
  real Intercept;
  // special effects coefficients
  vector[Ksp] bsp;
  // simplexes of monotonic effects
  simplex[Jmo[1]] simo_1;
  real<lower=0> sigma;  // residual SD
}
transformed parameters {
}
model {
  // initialize linear predictor term
  vector[N] mu = Intercept + rep_vector(0, N);
  for (n in 1:N) {
    // add more terms to the linear predictor
    mu[n] += (bsp[1]) * mo(simo_1, Xmo_1[n]);
  }
  // priors including all constants
  target += student_t_lpdf(Intercept | 3, 65, 12);
  target += dirichlet_lpdf(simo_1 | con_simo_1);
  target += student_t_lpdf(sigma | 3, 0, 12)
    - 1 * student_t_lccdf(0 | 3, 0, 12);
  // likelihood including all constants
  if (!prior_only) {
    target += normal_lpdf(Y | mu, sigma);
  }
}
generated quantities {
  // actual population-level intercept
  real b_Intercept = Intercept;
}
"""

这是我在 python 中使用的代码:

## Libraries
import pandas as pd
import pystan
import numpy as np
import random as rd

## Build data for life span example with ordenated factors

income_options =  ["below_20", "20_to_40", "40_to_100", "greater_100"]
income_mean = [30, 60, 70, 75]
income_factor = [0, 1, 2, 3]

dict_data = {'income_options' : income_options,
             'income_mean' : income_mean,
             'income_factor' :  income_factor}

map_df = pd.DataFrame(dict_data)

income_rep = rd.sample(income_factor*25, 100)

rand_inc = np.random.normal(loc = 0, scale = 1, size = 100).tolist()


data_df = pd.DataFrame({'income_factor': income_rep,
                        'rand_inc' : rand_inc})

data_df = pd.merge(data_df, map_df, on = 'income_factor')

data_df['ls'] = data_df['income_mean'] + data_df['rand_inc']

N = data_df.shape[0]
Y = data_df['ls'].tolist()
K = 1
X = [1]*N
Ksp = 1
Imo = 1
Xmo_1 = data_df['income_factor'].tolist()
Jmo = len(data_df['income_factor'].unique().tolist())-1
con_simo_1 = [1]*Jmo
prior_only = 0


life_span_data = {'N' : N,
                  'Y' : Y,
                  'K' : K,
                  'X' : X,
                  'Ksp' : Ksp,
                  'Imo' : Imo,
                  'Xmo_1' : Xmo_1,
                  'Jmo' : Jmo,
                  'con_simo_1' : con_simo_1,
                  'prior_only' : prior_only}

life_span_sm = pystan.StanModel(model_code = life_span_code)
life_span_fit = life_span_sm.sampling(data= life_span_data, iter=1000, chains=2)

这是我收到的错误:

“运行时错误:异常:在上下文中声明和发现的数字维度不匹配;处理阶段=数据初始化;变量名=Jmo;声明的暗淡=(1);发现暗淡=()(在第24行的'未知文件名'中)”

感谢所有的帮助

4

1 回答 1

0

原来问题不在于 brms 生成的模型代码,而在于我定义参数的方式。特别是,Jmo 必须是一个列表而不是一个 int。

N = data_df.shape[0]
Y = data_df['ls'].tolist()
K = 1
X = [1]*N
Ksp = 1
Imo = 1
Xmo_1 = data_df['income_factor'].tolist()

## The following two lines have changed
Jmo = [len(data_df['income_factor'].unique().tolist())-1]
con_simo_1 = [1, 1, 1]
## End of changes

prior_only = 0

其余代码相同。我仍然希望澄清为什么某些参数可以声明为整数,而其他参数只能声明为列表。

再次感谢

于 2020-04-13T21:39:50.250 回答