python - KBinsDiscretizer bin 边缘

标签 python scikit-learn binning

有谁知道 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)

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/

相关文章:

python - 如何检查python脚本是否正在通过ssh远程调用

python - 有没有更快的方法在 python 中创建配对元素列表?

scikit-learn - 具有仅正样本和未标记数据集的二元半监督分类

python - 支持向量-/Logistic-回归 : do you have benchmark results for the boston housing data?

R - hist(XX, plot=FALSE)$count 的更快替代品

python - PyCharm 替换文档字符串中的字符

python - 使用 Python Pandas 读取列名

python - 如何仅标准化 sklearn 管道中的数字变量?

python - 具有预定义箱和闭/开区间的箱变量

python - 在 python 中对列表进行分箱