【问题标题】:how can i fix entropy yielding nan?我如何解决熵产生的问题?
【发布时间】:2016-09-21 22:43:42
【问题描述】:

我正在尝试从 np.histogram 产生的数组中计算熵

mu1, sigma1 = 0, 1
s1 = np.random.normal(mu1, sigma1, 100000)
hist1 = np.histogram(s1, bins=100, range=(-20,20), density=True)
data1 = hist1[0]
ent1 = -(data1*np.log(np.abs(data1))).sum() 

但是,这个 ent1 会返回 nan。这里有什么问题?

【问题讨论】:

  • data1 里面的值为零,并且未定义 Log(0),因此它返回 nan。

标签: python numpy entropy


【解决方案1】:

要计算熵,您可以使用scipy.special.entr。例如,

In [147]: from scipy.special import entr

In [148]: x = np.array([3, 2, 1, 0, 0.5, 2.5, 5])

In [149]: entr(x).sum()
Out[149]: -14.673474028700136

为了检查这个结果,我们还可以使用scipy.special.xlogy 计算熵:

In [150]: from scipy.special import xlogy

In [151]: -xlogy(x, x).sum()
Out[151]: -14.673474028700136

最后,我们可以验证这与您期望的结果相同:

In [152]: xnz = x[x != 0]

In [153]: -(xnz*np.log(xnz)).sum()
Out[153]: -14.673474028700136

【讨论】:

    【解决方案2】:

    问题是直方图中的概率为零,这在应用香农熵公式时没有数值意义。一个解决方案是忽略零概率。

    mu1, sigma1 = 0, 1
    s1 = np.random.normal(mu1, sigma1, 100000)
    hist1 = np.histogram(s1, bins=100, range=(-20,20), density=True)
    data1 = hist1[0]
    non_zero_data = data1[data1 != 0]
    ent1 = -(non_zero_data*np.log(np.abs(non_zero_data))).sum() 
    

    【讨论】:

    • 非常感谢!终于搞定了。 : ) 我也尝试过使用辣味.stats.entropy,但我发现这些值是不同的?尽管公式相同?
    • 不用担心。使用spicy.stats.entropy 时要小心,因为它会将值标准化,对于元素熵使用scipy.special.entr,正如@watten-weckesser 解释的那样。
    • @MateusZitelli 实际上零概率对于香农熵是有意义的,但是您必须将 0*log(0) 解释为零。这是有道理的,因为p 变为零时p*log(p) 的限制为零,这是解释0*log(0) 的唯一合理方式。
    【解决方案3】:

    使用numpy.nansum

    https://numpy.org/doc/stable/reference/generated/numpy.nansum.html

    mu1, sigma1 = 0, 1
    s1 = np.random.normal(mu1, sigma1, 100000)
    hist1 = np.histogram(s1, bins=100, range=(-20,20), density=True)
    data1 = hist1[0]
    ent1 = -np.nansum(data1*np.log(np.abs(data1)))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2021-10-10
    • 2019-12-20
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多