更新(2018 年 9 月):截至版本0.20.0
,有一个函数,sklearn.preprocessing.KBinsDiscretizer,它使用几种不同的策略提供连续特征的离散化:
- 统一大小的垃圾箱
- 内部装有“相同”数量样本的箱(尽可能多)
- 基于 K 均值聚类的 bin
不幸的是,目前该函数不接受自定义间隔(这对我来说很糟糕,因为这就是我想要的,也是我最终来到这里的原因)。如果你想达到同样的目的,你可以使用 Pandas 函数cut:
import numpy as np
import pandas as pd
n_samples = 10
a = np.random.randint(0, 10, n_samples)
# say you want to split at 1 and 3
boundaries = [1, 3]
# add min and max values of your data
boundaries = sorted({a.min(), a.max() + 1} | set(boundaries))
a_discretized_1 = pd.cut(a, bins=boundaries, right=False)
a_discretized_2 = pd.cut(a, bins=boundaries, labels=range(len(boundaries) - 1), right=False)
a_discretized_3 = pd.cut(a, bins=boundaries, labels=range(len(boundaries) - 1), right=False).astype(float)
print(a, '\n')
print(a_discretized_1, '\n', a_discretized_1.dtype, '\n')
print(a_discretized_2, '\n', a_discretized_2.dtype, '\n')
print(a_discretized_3, '\n', a_discretized_3.dtype, '\n')
其产生:
[2 2 9 7 2 9 3 0 4 0]
[[1, 3), [1, 3), [3, 10), [3, 10), [1, 3), [3, 10), [3, 10), [0, 1), [3, 10), [0, 1)]
Categories (3, interval[int64]): [[0, 1) < [1, 3) < [3, 10)]
category
[1, 1, 2, 2, 1, 2, 2, 0, 2, 0]
Categories (3, int64): [0 < 1 < 2]
category
[1. 1. 2. 2. 1. 2. 2. 0. 2. 0.]
float64
请注意,默认情况下,pd.cut
返回 dtype 的 pd.Series 对象Category
具有类型元素interval[int64]
。如果您指定自己的labels
,输出的 dtype 仍然是Category
,但元素的类型为int64
。如果您希望该系列具有数字 dtype,您可以使用.astype(np.int64)
.
我的示例使用整数数据,但它应该与浮点数一样工作。