Jensen-Shannon分歧

时间:2013-04-08 13:18:40

标签: python distance metrics

我有另一个问题,我希望有人可以帮助我。

我正在使用Jensen-Shannon-Divergence来测量两个概率分布之间的相似性。相似性得分似乎是正确的,因为它们在1和0之间,假设一个使用基数2对数,0表示分布相等。

但是,我不确定某个地方是否确实存在错误,并且想知道某人是否可以说“是的是正确的”或“不,你做错了什么”。

以下是代码:

from numpy import zeros, array
from math import sqrt, log


class JSD(object):
    def __init__(self):
        self.log2 = log(2)


    def KL_divergence(self, p, q):
        """ Compute KL divergence of two vectors, K(p || q)."""
        return sum(p[x] * log((p[x]) / (q[x])) for x in range(len(p)) if p[x] != 0.0 or p[x] != 0)

    def Jensen_Shannon_divergence(self, p, q):
        """ Returns the Jensen-Shannon divergence. """
        self.JSD = 0.0
        weight = 0.5
        average = zeros(len(p)) #Average
        for x in range(len(p)):
            average[x] = weight * p[x] + (1 - weight) * q[x]
            self.JSD = (weight * self.KL_divergence(array(p), average)) + ((1 - weight) * self.KL_divergence(array(q), average))
        return 1-(self.JSD/sqrt(2 * self.log2))

if __name__ == '__main__':
    J = JSD()
    p = [1.0/10, 9.0/10, 0]
    q = [0, 1.0/10, 9.0/10]
    print J.Jensen_Shannon_divergence(p, q)

问题在于,比较两个文本文档时,我觉得分数不够高。然而,这纯粹是一种主观感受。

任何帮助一如既往地受到赞赏。

5 个答案:

答案 0 :(得分:20)

请注意,下面的scipy熵调用是Kullback-Leibler分歧。

请参阅:http://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence

#!/usr/bin/env python
from scipy.stats import entropy
from numpy.linalg import norm
import numpy as np

def JSD(P, Q):
    _P = P / norm(P, ord=1)
    _Q = Q / norm(Q, ord=1)
    _M = 0.5 * (_P + _Q)
    return 0.5 * (entropy(_P, _M) + entropy(_Q, _M))

另请注意,问题中的测试用例看起来有误吗? p分布的总和不会增加到1.0。

请参阅:http://www.itl.nist.gov/div898/handbook/eda/section3/eda361.htm

答案 1 :(得分:7)

获取具有已知差异的分布的一些数据,并将结果与​​已知值进行比较。

BTW:KL_divergence中的总和可以使用zip built-in function重写,如下所示:

sum(_p * log(_p / _q) for _p, _q in zip(p, q) if _p != 0)

这消除了许多“噪音”,也更加“pythonic”。与0.00的双重比较不是必需的。

答案 2 :(得分:2)

用于n个概率分布的通用版本,在python中

import numpy as np
from scipy.stats import entropy as H


def JSD(prob_distributions, weights, logbase=2):
    # left term: entropy of misture
    wprobs = weights * prob_distributions
    mixture = wprobs.sum(axis=0)
    entropy_of_mixture = H(mixture, base=logbase)

    # right term: sum of entropies
    entropies = np.array([H(P_i, base=logbase) for P_i in prob_distributions])
    wentropies = weights * entropies
    sum_of_entropies = wentropies.sum()

    divergence = entropy_of_mixture - sum_of_entropies
    return(divergence)

# From the original example with three distributions:
P_1 = np.array([1/2, 1/2, 0])
P_2 = np.array([0, 1/10, 9/10])
P_3 = np.array([1/3, 1/3, 1/3])

prob_distributions = np.array([P_1, P_2, P_3])
n = len(prob_distributions)
weights = np.empty(n)
weights.fill(1/n)

print(JSD(prob_distributions, weights))
#0.546621319446

答案 3 :(得分:1)

由于 Jensen-Shannon 距离distance.jensenshannon)已包含在Scipy 1.2中,因此 Jensen-Shannon 散度可以作为詹森-香农距离的平方:

from scipy.spatial import distance

distance.jensenshannon([1.0/10, 9.0/10, 0], [0, 1.0/10, 9.0/10]) ** 2
# 0.5306056938642212

答案 4 :(得分:0)

明确跟随Wikipedia article中的数学:

def jsdiv(P, Q):
    """Compute the Jensen-Shannon divergence between two probability distributions.

    Input
    -----
    P, Q : array-like
        Probability distributions of equal length that sum to 1
    """

    def _kldiv(A, B):
        return np.sum([v for v in A * np.log2(A/B) if not np.isnan(v)])

    P = np.array(P)
    Q = np.array(Q)

    M = 0.5 * (P + Q)

    return 0.5 * (_kldiv(P, M) +_kldiv(Q, M))