有谁知道 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]。那么这样写对吗?
- bin:4.3 <= x < 5.5,
- bin:5.5 <= x < 6.7,
- 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)
default对于 np.digitize 是 right=False
,因此如果应用于此数据,您的分箱大多是正确的。您可以检查边界:
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.]])
它们分别分配给第一个和最后一个 bin。严格来说,垃圾箱是:
1. bin: x < 5.5,
2. bin: 5.5 <= x < 6.7,
3. bin: 6.7 <= x
关于python - KBinsDiscretizer bin 边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65968544/