使用 round() 对连续值进行分箱会创建工件

Binning continuous values with round() creates artifacts

在 Python 中,假设我有连续变量 xy,它们的值介于 0 和 1 之间(为了更容易)。我的假设一直是,如果我想将这些变量转换为有序值,并且 bin 为 0,0.01,0.02,...,0.98,0.99,1,可以简单地将原始值四舍五入到第二位数字。出于某种原因,当我这样做时,它会留下伪影。

让我来说明这个问题(但是请注意,我的问题不是如何获得正确的图,而是如何进行正确的装箱)。首先,这些是重现问题所需的唯一模块:

import numpy as np
import matplotlib.pyplot as plt

现在,假设我们连续生成如下数据(其他数据生成过程也会出现同样的问题):

# number of points drawn from Gaussian dists.:
n = 100000
x = np.random.normal(0, 2, n)
y = np.random.normal(4, 5, n)

# normalizing x and y to bound them between 0 and 1
# (it's way easier to illustrate the problem this way)
x = (x - min(x))/(max(x) - min(x))
y = (y - min(y))/(max(y) - min(y))

然后,让我们将 xy 转换为上述区间中的序数,只需应用一些舍入即可。然后,让我们将结果存储到 x by y 矩阵中,以便绘制其热图 用于说明目的:

# matrix that will represent the bins. Notice that the
# desired bins are every 0.01, from 0 to 1, so 100 bins:
mtx = np.zeros([100,100])
for i in range(n):
    # my idea was that I could roughly get the bins by
    # simply rounding to the 2nd decimal point:
    posX = round(x[i], 2)
    posY = round(y[i], 2)
    mtx[int(posX*100)-1, int(posY*100)-1] += 1

我希望上面的方法有效,但是当我绘制矩阵 mtx 的内容时,我实际上得到了奇怪的伪影。代码:

# notice, however, the weird close-to-empty lines at
# 0.30 and 0.59 of both x and y. This happens regardless
# of how I generate x and y. Regardless of distributions
# or of number of points (even if it obviously becomes
# impossible to see if there are too few points):
plt.matshow(mtx, cmap=plt.cm.jet)
plt.show(block=False)

给我:

最奇怪的是,无论我使用哪个分布生成 xy 或者我使用哪个种子生成 RNG,我总是得到相同的水平和垂直近空线在 xy 的 0.30 和 0.59 处,这些线通常与显示点集中的线直接平行(如图所示)。

当我从那个矩阵按值打印到控制台时,我实际上可以确认对应于那些近空行的那些确实是零或非常接近零 - 与它们的相邻点不同。

我的问题可以更恰当地分为两部分:

  1. 为什么会出现以上情况?我真的很想知道在那个简单的代码中到底是什么导致了这样的问题。

  2. 通过 y 矩阵 生成 x 的更好方法是什么,该矩阵根据切割点 0 对值进行分箱, 0.01,0.02,...,0.98,0.99,1 没有留下上面的工件?

如果想轻松地直接将上面使用的整个示例代码集中在一块,这里是 link: https://www.codepile.net/pile/VLAq4kLp

注意:我不想找到正确的绘图方式。我想找到 myeself 生成所代表的 "binned values matrix" 的正确方法是上面的图。我知道还有其他方法可以在没有工件的情况下完成热图绘制,例如使用 plt.matshow(mtx, cmap=plt.cm.jet); plt.show(block=False)plt.hist2d(x, y, bins=100)。我要问的是我的矩阵生成本身的问题在哪里,它创建了那些接近零的元素。

目前我只能正确回答你的第二个问题,因为我还在寻找第一部分的错误。

这里是您可以根据需要选择的 binnig 标准解决方案(假设您之前提到的 xy):

h = plt.hist2d(x, y, bins=100)

给予

这是一个 100x100 的网格。

变量 h 现在包含您想要的矩阵以及 matplotlib 找到的 bin。 plt.matshow(h[0]) 显示的矩阵和图中看到的一样,是matplotlib返回的。如评论中所述:您可以通过调用

获得相同的结果(但没有自动绘图)
h = np.histogram2d(x, y, bins=100)

尽管如此,您的算法不可能正确,因为您实际上是在计算 边上的项目数,而不是 之间它们,所以你在每个方向上得到 101 个项目。您可以看到问题,例如 posX==0 时: Then int(posX*100)-1 yields -1.

我不知道如何准确回答你的第一个问题。但是对于装箱项目我也使用 pandas.cut。对于您的解决方案,您可以这样做

import pandas as pd
bins = [v / 100. for v in range(100)
bucketed = pd.cut(x, bins)

bucketed 将指示每个数据点属于哪个区间

这里有一个不错的教程供参考http://benalexkeen.com/bucketing-continuous-variables-in-pandas/

使用np.histogram2d(x,y, bins=100)即可轻松解决问题。

此答案的其余部分是为了说明手动算法失败的地方:

从数字上考虑

0.56*100 == 56.00000000000001    -> int(0.56*100) == 56
0.57*100 == 56.99999999999999    -> int(0.57*100) == 56
0.58*100 == 57.99999999999999    -> int(0.58*100) == 57
0.59*100 == 59.00000000000000    -> int(0.59*100) == 59

这样数字 58 就不会出现在您的索引中,而数字 56 会出现两倍的频率(为了均匀分布)。

您可以先相乘,然后截断为整数。另请注意,最后一个 bin 需要关闭,以便将值 1 添加到索引为 99 的 bin。

mtx = np.zeros([100,100])
for i in range(n):
    posX = int(x[i]*100)
    posY = int(y[i]*100)
    if posX == 100:
        posX = 99
    if posY == 100:
        posY = 99
    mtx[posX, posY] += 1

这将通过边缘定义 bin,即第一个 bin 的范围从 0 到 1 等。在对 imshow/matshow 的调用中,您需要通过设置范围来考虑这一点。

plt.matshow(mtx, cmap=plt.cm.jet, extent=(0,100,0,100))

您的方法存在的问题是浮点错误。当您尝试将四舍五入的数字变成整数时,这一点就很明显了。考虑以下函数(本质上就是您对每个随机数所做的操作):

def int_round(a):
     r = round(a, 2)
     rh = r*100
     i = int(rh)
     print(r, rh, i)


int_round(0.27)
#prints: 0.27 27.0 27

int_round(0.28)
#prints: 0.28 28.000000000000004 28

int_round(0.29)
#prints: 0.29 28.999999999999996 28

int_round(0.30)
#prints: 0.3 30.0 30

如您所见,由于 0.28 和 0.29 舍入并乘以 100 后的浮点误差,0.280.29 最终都得到整数 28。 (这是因为 int() 总是向下舍入,所以 28.99999999999 变成 28)。

一个解决方案可能是将乘以 100 后的值四舍五入:

def round_int(a):
    ah = a*100
    rh = round(ah, 2)
    i = int(rh)
    print(ah, rh, i)

round_int(0.27)
#prints: 27.0 27.0 27

round_int(0.28)
#prints: 28.000000000000004 28.0 28

round_int(0.29)
#prints: 28.999999999999996 29.0 29

round_int(0.30)
#prints: 30.0 30.0 30

请注意,在这种情况下 0.29 已更正为 29

将此逻辑应用于您的代码:我们可以将 for 循环更改为:

mtx = np.zeros([101, 101])

for i in range(n):
    # my idea was that I could roughly get the bins by
    # simply rounding to the 2nd decimal point:
    posX = np.round(100*x[i], 2)
    posY = np.round(100*y[i], 2)
    mtx[int(posX), int(posY)] += 1

请注意,当 x=1 或 y=1 时,将 bin 的数量增加到 101 以说明最终的 bin。此外,在这里您可以看到,当我们在四舍五入之前将 x[i]y[i] 乘以 100 时,分箱是正确的: