【问题标题】:numpy histogram2d produces strange resultnumpy histogram2d 产生奇怪的结果
【发布时间】:2018-02-20 14:25:05
【问题描述】:

我正在尝试使用 numpy histogram2d 函数。我正在生成一些随机数据,如下所示:

import numpy as np

np.random.seed(0)
img = np.random.uniform(low=2.0, high=65.0, size=(400, 400))

因此,数据介于 0 和 65 之间。我有自己的 hostogram 函数,它产生如下所需的结果:

def compute_histogram2d(r, w, bins):
    jh = np.zeros(bins)
    jh_flat = jh.ravel(order='K')

    ref_data = r.ravel(order='K')
    war_data = w.ravel(order='K')

    num_nodes = r.shape[0] * r.shape[1]

    for i in range(num_nodes):
        index = (int(ref_data[i]) + (int)(war_data[i]) * bins[0])
        jh_flat[index] += 1.0

    return jh

所以,我将值转换为整数,然后增加直方图中的值。

我可以称之为计算对角直方图。

jh = compute_histogram2d(img, img, (68, 68))

我正在尝试使用 numpy histogram2D 获得相同的结果。所以,我做了以下事情:

jh2 = np.histogram2d(np.trunc(img.ravel(order='K')).astype(np.int32),
                 np.trunc(img.ravel(order='K')).astype(np.int32),
                 bins=(bins, bins))[0]

这是这两个直方图中的前几个条目(第一列是我自己的函数,第二列是 numpy)。这些打印为:

for i in range(68):
    print (jh[i, i], jh2[i, i])


0.0      2522.0
0.0      2507.0
2522.0   2558.0
2507.0   2615.0
2558.0   2555.0
2615.0   2519.0
2555.0   2627.0
2519.0   2551.0
2627.0   2585.0
2551.0   2490.0
2585.0   2531.0
2490.0   0.0    <---- Some zeros appear
2531.0   2528.0
2528.0   2557.0
2557.0   2493.0
2493.0   2509.0
2509.0   2608.0
2608.0   2516.0

如您所见,numpy 列似乎发生了变化。值范围在 2 到 65 之间。所以在我自己的实现中,前两个值是 0.0,这是正确的,但 numpy 实现会为 (0, 0)(1, 1) 生成非零值。此外,对角线上也会出现一些不应该出现的零。

【问题讨论】:

    标签: python numpy histogram


    【解决方案1】:

    我想通了。我需要指定 range 参数,否则会被截断为异常值。

    所以用作:

    jh2 = np.histogram2d(np.trunc(img.ravel(order='K')).astype(np.int32),
                         np.trunc(img.ravel(order='K')).astype(np.int32),
                         bins=(bins, bins),
                         range=[[0, bins], [0, bins]])[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多