【问题标题】:Exporting Tensorflow probability's Hidden Markov Model导出 TensorFlow 概率的隐马尔可夫模型
【发布时间】:2020-09-20 05:20:41
【问题描述】:

我想导出 HMM 模型,因为每次训练它都需要时间。我的方法是将所有矩阵保存在文件中。我想知道有什么 tensorflow 方法可以做到吗?也可以通过api导出到其他语言,如C++。

【问题讨论】:

    标签: python tensorflow tensorflow-probability


    【解决方案1】:

    您可以通过调用tfp.distributions.HiddenMarkovModel()variables 属性来迭代并保存模型变量的权重

    【讨论】:

      【解决方案2】:

      tf.saved_model 是推荐的方法。比如:

      import tensorflow as tf
      import tensorflow_probability as tfp
      
      hmm = tfp.distributions.HiddenMarkovModel(
          initial_distribution=tfp.distributions.Categorical(logits=tf.Variable([0., 0])),
          transition_distribution=tfp.distributions.Categorical(logits=tf.Variable([[0., 0]] * 2)),
          observation_distribution=tfp.distributions.Normal(tf.Variable([0., 0]), 
                                                            tfp.util.TransformedVariable([1., 1], tfp.bijectors.Softplus(low=1e-3))),
          num_steps=10)
      
      x = hmm.sample(100)
      
      opt = tf.optimizers.Adam(0.01)
      
      @tf.function
      def one_step():
        with tf.GradientTape() as t:
          nll = -hmm.log_prob(x)
        grads = t.gradient(nll, hmm.trainable_variables)
        opt.apply_gradients(zip(grads, hmm.trainable_variables))
      
      for _ in range(10):
        one_step()
      
      class Foo(tf.Module):
        def __init__(self, hmm):
          self._hmm = hmm
        @tf.function(input_signature=[tf.TensorSpec.from_tensor(x)])
        def log_prob(self, x):
          return self._hmm.log_prob(x)
      
      tf.saved_model.save(Foo(hmm), '/tmp/tf.model')
      q = tf.saved_model.load('/tmp/tf.model')
      q.log_prob(x)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        • 2014-10-06
        • 1970-01-01
        • 2012-08-15
        • 2012-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多