在工作中经常会有对连续数据进行分级的工作。我们可以构造一个这样的实例:
import numpy as np
from numpy.random import random
import matplotlib.pyplot as plt
%matplotlib inline
random()
0.7965577941827164
x = [a + 0.5*random() for i in range(20) for a in [1,2,2.5,3.5,4,5,6]]
y = [3*random() for j in range(140)]
plt.scatter(x,y,color = 'r')
df = pd.DataFrame({'x':x,'y':y})
原始数据
人工分级 Artificial Division
对于少量数据来说,最准确的方法当然是人工分级。
scales = [0,1.8,3.2,4.6,5.6,7]
colors = ['r','g','orange','b','pink']
for i in range(len(scales)-1):
plt.scatter(df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['x'],df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['y'],color = colors[i])
"plt.plot((1.8,1.8),(0,3.0),color = 'g')\nplt.plot((3.2,3.2),(0,3.0),color = 'g')\nplt.plot((4.6,4.6),(0,3.0),color = 'g')\nplt.plot((5.6,5.6),(0,3.0),color = 'g')"
人工分级
人工分级结果,各类数据分割清晰。
等间隔分级 Equal Interval Division
数据量增大之后,难以通过肉眼观察到分界点,可以采用等间隔分级的方式进行粗暴的分级,但是通常效果不好:
x_max = max(x)
x_min = min(x)
scale = (x_max - x_min)/5
scales = [x_min + n * scale for n in range(1,5)]
scales.insert(0,x_min)
scales.append(x_max)
for i in range(len(scales)-1):
plt.scatter(df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['x'],df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['y'],color = colors[i])
等间隔分级
等百分比分级 Equal Percentage Division
等间隔分级常常会导致各个级别中包含的数据量悬殊,为了避免这种情况,可以将绝对间隔改为相对间隔,即采用等百分比间隔分级
x = np.array(x)
scales = [np.percentile(x,20*i) for i in range(1,5)]
scales.insert(0,x_min)
scales.append(x_max)
for i in range(len(scales)-1):
plt.scatter(df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['x'],df[(df['x']>=scales[i])&(df['x']<=scales[i+1])]['y'],color = colors[i])
等百分比分级
K均值分级 K_Means Division
分级其实是一种聚类问题,自然可以使用聚类算法,我们可以尝试用最简单的聚类算法K均值聚类来进行分级实验:
from sklearn.cluster import KMeans
x = x.reshape(-1,1)
km = KMeans(n_clusters=5)
km.fit(x)
km.labels_
array([3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3,
1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1,
1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1,
2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2,
2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2,
4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4, 0, 3, 1, 1, 2, 2, 4,
0, 3, 1, 1, 2, 2, 4, 0])
import pandas as pd
# x = np.squeeze(x)
df['l'] = km.labels_
colors = ['r','g','orange','b','pink']
for i in range(5):
plt.scatter(df[df['l']==i]['x'],df[df['l']==i]['y'],color = colors[i])
K_means分级
如上图所示,K均值分级的效果堪比人工分级。
网友评论