【问题标题】:Computing KL divergence for many distributions计算许多分布的 KL 散度
【发布时间】:2018-08-09 15:02:05
【问题描述】:

我有一个测试概率分布矩阵:

qs = np.array([[0.1, 0.6], 
               [0.9, 0.4] ])

(每列总和为 1)和“真实”分布:

p = np.array([0.5, 0.5])

我想在 TensorFlow 中计算从 p 到 qs 每一列的 KL 散度。我知道有一个函数tf.distributions.kl_divergence,但它只需要两个分布...

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    你可以遍历列:

    sess = tf.InteractiveSession()
    A = tf.distributions.Categorical(probs=[0.5, 0.5])
    
    for i in range(2):
        B = tf.distributions.Categorical(probs=list(qs[:,i]))
        print(tf.distributions.kl_divergence(A, B).eval())
    

    【讨论】:

      【解决方案2】:

      此解决方案适用于任意多列并且仅使用 TensorFlow:

      qs = np.array([[0.9, 0.6, 0.4, 0.5],
                     [0.1, 0.4, 0.6, 0.5]])
      p = np.array([0.5, 0.5])
      # Format `p` to a column vector, for constistency reason
      p_t = p.reshape([-1, 1])
      
      # Convert to categorical distributions. Transpose part is important
      dist_qs = tf.distributions.Categorical(probs=tf.transpose(qs))
      dist_p = tf.distributions.Categorical(probs=tf.transpose(p))
      
      # Calculate KL divergences for qs and broadcasted p 
      tf.distributions.kl_divergence(dist_p, dist_qs).eval()
      

      这给出了:

      array([0.51082562, 0.020411  , 0.020411  , 0.])
      

      看起来很有希望的结果。

      【讨论】:

        【解决方案3】:

        这是怎么做的:

        sess = tf.InteractiveSession()
        A = tf.distributions.Categorical(probs=[0.1, 0.6])
        B = tf.distributions.Categorical(probs=[0.9, 0.4])
        print(tf.distributions.kl_divergence(A, B).eval())
        

        输出:0.7773577

        【讨论】:

        • 不确定这是 OP 所要求的:首先,OP 的发行版实际上是 [0.1, 0.9] 和 [0.6, 0.4](每个总和为 1);其次,OP 从[0.5, 0.5] 请求 both 这两个发行版的 KL
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 2017-11-02
        • 2017-10-03
        • 2018-09-27
        • 1970-01-01
        • 2018-08-10
        • 2020-01-01
        相关资源
        最近更新 更多