KBinsDiscretizer bin 边缘

KBinsDiscretizer bin edges

有谁知道是否必须解释 KBinsDiscretizer 提供的 bin 边缘? 由于它使用 numpy linspace 进行统一分箱,默认值为 endpoint=True,分箱应包括最右边的边缘。那么如何用大于号和小于号来写呢?

这是一个例子:

from sklearn.datasets import load_iris
from sklearn.preprocessing import KBinsDiscretizer
iris_data = load_iris()
x = iris_data.data
# binning of first feature
est = KBinsDiscretizer(n_bins=3, encode='onehot-dense', strategy='uniform')
x1 = est.fit_transform(x[:,0].reshape(-1, 1))
bin_edges = est.bin_edges_ 

bin 边缘为 [4.3, 5.5, 6.7, 7.9]。那么这样写对吗?

  1. bin: 4.3 <= x < 5.5,
  2. bin: 5.5 <= x < 6.7,
  3. bin: 6.7 <= x <= 7.9

边缘是使用 np.linspace 定义的,但是分配是使用 np.digitize 完成的,然后是 np.clip 以控制最右边的垃圾箱,如果您查看 source code 第 303 行:

for jj in range(Xt.shape[1]):
   rtol = 1.e-5
   atol = 1.e-8
   eps = atol + rtol * np.abs(Xt[:, jj])
   Xt[:, jj] = np.digitize(Xt[:, jj] + eps, bin_edges[jj][1:])
np.clip(Xt, 0, self.n_bins_ - 1, out=Xt)

np.digitize 的 defaultright=False ,因此如果应用于此数据,您的 bin 大部分是正确的。您可以检查边界:

test = np.array([4.3,5.5,6.7,7.9]).reshape(-1,1)

est.transform(test)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 1.]])

您应该注意,如果您有超出 bin 边缘的值,它们会自动分配给边界 bin,请参阅 np.digitize。所以这意味着,我们尝试使用越界值 4.1 和 8.1:

test = np.array([4.1,4.3,7.9,8.1]).reshape(-1,1)
est.transform(test)

array([[1., 0., 0.],
       [1., 0., 0.],
       [0., 0., 1.],
       [0., 0., 1.]])

它们分别被分配到第一个和最后一个垃圾箱。所以严格来说,垃圾箱是:

1. bin: x < 5.5,
2. bin: 5.5 <= x < 6.7,
3. bin: 6.7 <= x