数据分箱(英语:Data binning)是一种数据预处理方法,用于最大限度地减少小观测误差的影响。原始数据值被划分为称为bin的小区间,然后用为该bin计算的一般值替换它们。这对输入数据具有平滑效果,并且在小数据集的情况下还可以减少过拟合的机会。
有两种常见方法可以将数据划分到箱中:
等频分箱
Input:[5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215]
Output:
[5, 10, 11, 13]
[15, 35, 50, 55]
[72, 92, 204, 215]
等宽分箱
Input: [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215]
Output:
[5, 10, 11, 13, 15, 35, 50, 55, 72]
[92]
[204, 215]
# equal frequency
def equifreq(arr1, m):
a = len(arr1)
n = int(a / m)
for i in range(0, m):
arr = []
for j in range(i * n, (i + 1) * n):
if j >= a:
break
arr = arr + [arr1[j]]
print(arr)
# equal width
def equiwidth(arr1, m):
a = len(arr1)
w = int((max(arr1) - min(arr1)) / m)
min1 = min(arr1)
arr = []
for i in range(0, m + 1):
arr = arr + [min1 + w * i]
arri=[]
for i in range(0, m):
temp = []
for j in arr1:
if j >= arr[i] and j <= arr[i+1]:
temp += [j]
arri += [temp]
print(arri)
# data to be binned
data = [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215]
# no of bins
m = 3
print("equal frequency binning")
equifreq(data, m)
print("\n\nequal width binning")
equiwidth(data, 3)
输出
equal frequency binning
[5, 10, 11, 13]
[15, 35, 50, 55]
[72, 92, 204, 215]
equal width binning
[[5, 10, 11, 13, 15, 35, 50, 55, 72], [92], [204, 215]]
等频分箱
优点:
缺点:
等宽分箱
优点:
缺点:
总的来说,选择等频分箱还是等宽分箱,需要根据实际的数据分布和业务需求来决定。