首页 > 解决方案 > Tensorflow 概率错误:OperatorNotAllowedInGraphError:不允许迭代 `tf.Tensor`

问题描述

我正在尝试通过为其提供似然函数来使用 NUTS 估计张量流中的模型。我检查了似然函数是否返回了合理的值。我正在按照此处的设置来设置 NUTS: https ://rlhick.people.wm.edu/posts/custom-likes-tensorflow.html

以及此处用于设置先验等的一些示例: https ://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Multilevel_Modeling_Primer.ipynb

我的代码在 colab 笔记本中: https ://drive.google.com/file/d/1L9JQPLO57g3OhxaRCB29do2m808ZUeex/view?usp=sharing

我收到错误:OperatorNotAllowedInGraphError: iterating overtf.Tensoris not allowed: AutoGraph did not convert this function. Try decorating it directly with @tf.function.这是我第一次使用 tensorflow,我对这个错误的解释很迷茫。如果我可以将起始参数值作为单个输入传递也将是理想的(我正在处理的示例没有这样做,但我认为这是可能的)。

更新 看起来我不得不改变 @tf.function 装饰器的位置。采样器现在运行,但它为每个参数的所有样本提供了相同的值。我是否需要通过 log_prob() 函数传递联合分布?我显然错过了一些东西。我可以通过 bfgs 优化运行可能性并获得合理的结果(我已经通过其他软件中具有固定参数的最大似然估计模型)。看起来我需要定义函数来返回联合分布并调用 log_prob()。如果我将其设置为逻辑回归(logit 选择模型在逻辑上分布在差异中),我可以做到这一点。但是,我失去了标准的封闭形式。

我的功能如下:

 @tf.function
def mmnl_log_prob(init_mu_b_time,init_sigma_b_time,init_a_car,init_a_train,init_b_cost,init_scale):

    # Create priors for hyperparameters
    mu_b_time = tfd.Sample(tfd.Normal(loc=init_mu_b_time, scale=init_scale),sample_shape=1).sample()
    # HalfCauchy distributions are too wide for logit discrete choice

    sigma_b_time = tfd.Sample(tfd.Normal(loc=init_sigma_b_time, scale=init_scale),sample_shape=1).sample()


    # Create priors for parameters
    a_car = tfd.Sample(tfd.Normal(loc=init_a_car, scale=init_scale),sample_shape=1).sample()
    a_train = tfd.Sample(tfd.Normal(loc=init_a_train, scale=init_scale),sample_shape=1).sample()

    # a_sm = tfd.Sample(tfd.Normal(loc=init_a_sm, scale=init_scale),sample_shape=1).sample()

    b_cost = tfd.Sample(tfd.Normal(loc=init_b_cost, scale=init_scale),sample_shape=1).sample()
    # Define a heterogeneous random parameter model with MultivariateNormalDiag()
    # Use MultivariateNormalDiagPlusLowRank() to define nests, etc.

    b_time = tfd.Sample(tfd.MultivariateNormalDiag(  # b_time
          loc=mu_b_time,
          scale_diag=sigma_b_time),sample_shape=num_idx).sample()


    # Definition of the utility functions

    V1 = a_train + tfm.multiply(b_time,TRAIN_TT_SCALED) + b_cost * TRAIN_COST_SCALED
    V2 = tfm.multiply(b_time,SM_TT_SCALED) + b_cost * SM_COST_SCALED
    V3 = a_car + tfm.multiply(b_time,CAR_TT_SCALED) + b_cost * CAR_CO_SCALED
    print("Vs",V1,V2,V3)

    # Definition of loglikelihood
    eV1 = tfm.multiply(tfm.exp(V1),TRAIN_AV_SP)
    eV2 = tfm.multiply(tfm.exp(V2),SM_AV_SP)
    eV3 = tfm.multiply(tfm.exp(V3),CAR_AV_SP)
    eVD = eV1 + eV2 +
 eV3
    print("eVs",eV1,eV2,eV3,eVD)

    l1 = tfm.multiply(tfm.truediv(eV1,eVD),tf.cast(tfm.equal(CHOICE,1),tf.float32))
    l2 = tfm.multiply(tfm.truediv(eV2,eVD),tf.cast(tfm.equal(CHOICE,2),tf.float32))
    l3 = tfm.multiply(tfm.truediv(eV3,eVD),tf.cast(tfm.equal(CHOICE,3),tf.float32))
    ll = tfm.reduce_sum(tfm.log(l1+l2+l3))

    print("ll",ll)

    return ll

该函数调用如下:

    nuts_samples = 1000
nuts_burnin = 500
chains = 4
## Initial step size
init_step_size=.3
init = [0.,0.,0.,0.,0.,.5]

##
## NUTS (using inner step size averaging step)
##
@tf.function
def nuts_sampler(init):
    nuts_kernel = tfp.mcmc.NoUTurnSampler(
      target_log_prob_fn=mmnl_log_prob, 
      step_size=init_step_size,
      )
    adapt_nuts_kernel = tfp.mcmc.DualAveragingStepSizeAdaptation(
  inner_kernel=nuts_kernel,
  num_adaptation_steps=nuts_burnin,
  step_size_getter_fn=lambda pkr: pkr.step_size,
  log_accept_prob_getter_fn=lambda pkr: pkr.log_accept_ratio,
  step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(step_size=new_step_size)
       )

    samples_nuts_, stats_nuts_ = tfp.mcmc.sample_chain(
  num_results=nuts_samples,
  current_state=init,
  kernel=adapt_nuts_kernel,
  num_burnin_steps=100,
  parallel_iterations=5)
    return samples_nuts_, stats_nuts_

samples_nuts, stats_nuts = nuts_sampler(init)

标签: pythontensorflowtensorflow-probability

解决方案


我的问题有答案了!这只是不同命名法的问题。我需要将我的模型定义为 softmax 函数,我知道这就是我所说的“logit 模型”,但它对我来说并没有点击。以下博客文章让我顿悟: http: //khakieconomics.github.io/2019/03/17/Putting-it-all-together.html


推荐阅读