numpy histogram2d产生奇怪的结果

时间:2018-02-20 14:25:05

标签: python numpy histogram

我正在尝试使用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之间。我有自己的主机图功能,可产生如下所需的结果:

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)生成非零值。此外,对角线上也会出现一些零,它不应该出现。

1 个答案:

答案 0 :(得分:0)

我明白了。我需要指定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]