【问题标题】:The sum of density function (based on histogram) is not equal to 1密度函数之和(基于直方图)不等于1
【发布时间】:2021-04-14 11:10:21
【问题描述】:

我正在尝试生成密度函数,但生成的直方图的分量之和似乎不接近 1。

这是什么原因,如何使密度函数之和接近(即使不完全等于)1?

小例子:

import numpy as np
x = np.random.normal(0, 0.5, 1000) # mu, sigma, num
bins = np.linspace(min(x), max(x), num=50) # lower and upper bounds
hist, hist_bins = np.histogram(x, bins=bins, density = True)

print(np.sum(hist))
>>> 10.4614

如果我没有指定 bin 边缘,则输出会更小但仍大于 1:

import numpy as np
x = np.random.normal(0, 0.5, 1000) # mu, sigma, num
hist, hist_bins = np.histogram(x, density = True)

print(np.sum(hist))
>>> 3.1332

【问题讨论】:

    标签: python numpy histogram


    【解决方案1】:

    这种行为的原因is stated in the docs

    密度:bool,可选

    如果为 False,结果将包含数字 每个 bin 中的样本数。如果为 True,则结果为 bin 处的概率密度函数,归一化使得 范围内的积分为 1。请注意,直方图的总和 除非选择了统一宽度的 bin,否则值将不等于 1; 它不是概率质量函数。

    另外,提供了一个样本,显示直方图之和不等于1.0:

    import numpy as np
    
    a = np.arange(5)
    hist, bin_edges = np.histogram(a, density=True)
    
    print(hist)
    # hist --> [0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]
    
    print(hist.sum())
    # --> 2.4999999999999996
    
    print(np.sum(hist * np.diff(bin_edges)))
    # --> 1.0
    

    所以我们可以将它应用到您的代码 sn-p:

    x = np.random.normal(0, 0.5, 1000) # mu, sigma, num
    bins = np.linspace(min(x), max(x), num=50) # lower and upper bounds
    hist, hist_bins = np.histogram(x, bins=bins, density=True)
    
    print(hist)
    
    print(np.sum(hist))
    
    print(np.sum(hist * np.diff(hist_bins)))
    # --> 1.0
    

    此外,您应该考虑如何选择垃圾箱并确保使用.linspace() 是一种合理的方式。

    【讨论】:

      猜你喜欢
      • 2014-04-10
      • 2014-02-27
      • 2022-01-21
      • 2013-02-02
      • 1970-01-01
      • 2021-06-03
      • 2021-06-09
      • 2017-12-19
      相关资源
      最近更新 更多