首页 > 解决方案 > sklearn.KBinsDiscretizer 为所有 bin 返回 0

问题描述

我有一个形状数组(1,188)。尝试使用 KBinsDiscretizer 创建垃圾箱,但它只给我带零注释的垃圾箱。

 # transform the dataset with KBinsDiscretizer
    enc = KBinsDiscretizer(n_bins=18, encode='ordinal' ,strategy='uniform')#strategy='uniorm'

    test =(np.asarray(list_event_MES).astype(np.float)).reshape(1, -1)
    print(test)
    print(test.shape)

    enc.fit(test)
    test2 = enc.transform(test)
    print(test2.tolist())

将为所有 bin 返回零。

Matrice input : [[0.13614053 0.14069501 0.08270327 0.26015096 0.15958708 0.16834299 0.14913976 0.11897561 0.23232807 0.0892398 0.1637264 0.17120459 0.19350733 0.18131615 0.20117186 0.1586006 0.19068352 0.24293008 . .... 0.2112216 0.21829195 0.28169516 0.27585681 0.27317305 0.1849694 0.23402622 0.24994829 0.20873297 0.25534803 0.15556027 0.27226802 0 0.14180543 0.24001428]]

形状 : (1, 188)

188 列的警告:/miniconda3/lib/python3.7/site-packages/sklearn/preprocessing/_discretization.py:159: UserWarning: Feature 0 is constant and will be replace with 0. "replaced with 0." % jj) /miniconda3/lib/python3.7/site-packages/sklearn/preprocessing/_discretization.py:159: UserWarning: Feature 1 is constant and will be replace with 0. "replaced with 0." % jj) /miniconda3/lib/python3.7/site-packages/sklearn/preprocessing/_discretization.py:159: UserWarning: Feature 2 is constant and will be replace with 0. "replaced with 0." % jj)

标签: pythonscikit-learn

解决方案


从你的数组的形状(1,188),我们可以推断出只有1样本和188特征。根据 的文档KBinsDiscretizer它用于将连续数据分箱为间隔,并且发生在特征级别,即对于每个特征(或换句话说,对于数据的每一列)KBinsDiscretizer计算分箱间隔,然后对您的数据进行分箱,一个例子如下所示:

X = [[-2, 1, -4,   -1],
     [-1, 2, -3, -0.5],
     [ 0, 3, -2,  0.5],
     [ 1, 4, -1,    2]]
est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
est.fit(X)  

Xt = est.transform(X)
Xt  

array([[ 0., 0., 0., 0.],
      ​[ 1., 1., 1., 0.],
      ​[ 2., 2., 2., 1.],
      ​[ 2., 2., 2., 2.] 

在这里,离散化器为每一列计算 bin 间隔并将它们分类。在您的情况下,每个功能只有一个数据点,因此计算箱没有任何意义。相反,如果您的数据(188,1)具有188示例和1特征,那么它可以完美地工作,如下所示:

enc = KBinsDiscretizer(n_bins=18, encode='ordinal' ,strategy='uniform')
list_event_MES = np.random.normal(0,2,188).reshape(-1,1)
test =(np.asarray(list_event_MES))
print(test.shape)
(188,1)

enc.fit(test)
test2 = enc.transform(test)

print(test2[0:5])

array([[12.],
   [12.],
   [ 7.],
   [ 9.],
   [ 3.]])

希望这可以帮助!


推荐阅读