AI day11(2020 8/13) 聚类

聚类



聚类模型可视化展示:https://www.naftaliharris.com/blog/

k-means 初始值k不好判断,可以做多次模型进行对比





PCA降维





# beer dataset
import pandas as pd
beer = pd.read_csv('data.txt', sep=' ')
beer
namecaloriessodiumalcoholcost
0Budweiser144154.70.43
1Schlitz151194.90.43
2Lowenbrau157150.90.48
3Kronenbourg17075.20.73
4Heineken152115.00.77
5Old_Milwaukee145234.60.28
6Augsberger175245.50.40
7Srohs_Bohemian_Style149274.70.42
8Miller_Lite99104.30.43
9Budweiser_Light11383.70.40
10Coors140184.60.44
11Coors_Light102154.10.46
12Michelob_Light135114.20.50
13Becks150194.70.76
14Kirin14965.00.79
15Pabst_Extra_Light68152.30.38
16Hamms139194.40.43
17Heilemans_Old_Style144244.90.43
18Olympia_Goled_Light7262.90.46
19Schlitz_Light9774.20.47
X = beer[["calories","sodium","alcohol","cost"]]

K-means clustering

from sklearn.cluster import KMeans

km = KMeans(n_clusters=3).fit(X)
km2 = KMeans(n_clusters=2).fit(X)
km.labels_
array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 2, 0, 0, 2, 1])
beer['cluster'] = km.labels_
beer['cluster2'] = km2.labels_
beer.sort_values('cluster')
namecaloriessodiumalcoholcostclustercluster2
0Budweiser144154.70.4301
1Schlitz151194.90.4301
2Lowenbrau157150.90.4801
3Kronenbourg17075.20.7301
4Heineken152115.00.7701
5Old_Milwaukee145234.60.2801
6Augsberger175245.50.4001
7Srohs_Bohemian_Style149274.70.4201
17Heilemans_Old_Style144244.90.4301
16Hamms139194.40.4301
10Coors140184.60.4401
14Kirin14965.00.7901
12Michelob_Light135114.20.5001
13Becks150194.70.7601
9Budweiser_Light11383.70.4010
8Miller_Lite99104.30.4310
11Coors_Light102154.10.4610
19Schlitz_Light9774.20.4710
15Pabst_Extra_Light68152.30.3820
18Olympia_Goled_Light7262.90.4620
from pandas.tools.plotting import scatter_matrix
%matplotlib inline

cluster_centers = km.cluster_centers_

cluster_centers_2 = km2.cluster_centers_
beer.groupby("cluster").mean()
caloriessodiumalcoholcostcluster2
cluster
0150.0017.04.5214290.5207141
1102.7510.04.0750000.4400000
270.0010.52.6000000.4200000
beer.groupby("cluster2").mean()
caloriessodiumalcoholcostcluster
cluster2
091.83333310.1666673.5833330.4333331.333333
1150.00000017.0000004.5214290.5207140.000000
centers = beer.groupby("cluster").mean().reset_index()
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 14
import numpy as np
colors = np.array(['red', 'green', 'blue', 'yellow'])
plt.scatter(beer["calories"], beer["alcohol"],c=colors[beer["cluster"]])

plt.scatter(centers.calories, centers.alcohol, linewidths=3, marker='+', s=300, c='black')

plt.xlabel("Calories")
plt.ylabel("Alcohol")
<matplotlib.text.Text at 0x18a25af4ac8>

在这里插入图片描述

scatter_matrix(beer[["calories","sodium","alcohol","cost"]],s=100, alpha=1, c=colors[beer["cluster"]], figsize=(10,10))
plt.suptitle("With 3 centroids initialized")
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
  if __name__ == '__main__':





<matplotlib.text.Text at 0x18a25b67e80>

在这里插入图片描述

scatter_matrix(beer[["calories","sodium","alcohol","cost"]],s=100, alpha=1, c=colors[beer["cluster2"]], figsize=(10,10))
plt.suptitle("With 2 centroids initialized")
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
  if __name__ == '__main__':





<matplotlib.text.Text at 0x18a2613c710>

在这里插入图片描述

Scaled data

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled
array([[ 0.38791334,  0.00779468,  0.43380786, -0.45682969],
       [ 0.6250656 ,  0.63136906,  0.62241997, -0.45682969],
       [ 0.82833896,  0.00779468, -3.14982226, -0.10269815],
       [ 1.26876459, -1.23935408,  0.90533814,  1.66795955],
       [ 0.65894449, -0.6157797 ,  0.71672602,  1.95126478],
       [ 0.42179223,  1.25494344,  0.3395018 , -1.5192243 ],
       [ 1.43815906,  1.41083704,  1.1882563 , -0.66930861],
       [ 0.55730781,  1.87851782,  0.43380786, -0.52765599],
       [-1.1366369 , -0.7716733 ,  0.05658363, -0.45682969],
       [-0.66233238, -1.08346049, -0.5092527 , -0.66930861],
       [ 0.25239776,  0.47547547,  0.3395018 , -0.38600338],
       [-1.03500022,  0.00779468, -0.13202848, -0.24435076],
       [ 0.08300329, -0.6157797 , -0.03772242,  0.03895447],
       [ 0.59118671,  0.63136906,  0.43380786,  1.88043848],
       [ 0.55730781, -1.39524768,  0.71672602,  2.0929174 ],
       [-2.18688263,  0.00779468, -1.82953748, -0.81096123],
       [ 0.21851887,  0.63136906,  0.15088969, -0.45682969],
       [ 0.38791334,  1.41083704,  0.62241997, -0.45682969],
       [-2.05136705, -1.39524768, -1.26370115, -0.24435076],
       [-1.20439469, -1.23935408, -0.03772242, -0.17352445]])
km = KMeans(n_clusters=3).fit(X_scaled)

beer["scaled_cluster"] = km.labels_
beer.sort_values("scaled_cluster")
namecaloriessodiumalcoholcostclustercluster2scaled_cluster
0Budweiser144154.70.43010
1Schlitz151194.90.43010
17Heilemans_Old_Style144244.90.43010
16Hamms139194.40.43010
5Old_Milwaukee145234.60.28010
6Augsberger175245.50.40010
7Srohs_Bohemian_Style149274.70.42010
10Coors140184.60.44010
15Pabst_Extra_Light68152.30.38201
12Michelob_Light135114.20.50011
11Coors_Light102154.10.46101
9Budweiser_Light11383.70.40101
8Miller_Lite99104.30.43101
2Lowenbrau157150.90.48011
18Olympia_Goled_Light7262.90.46201
19Schlitz_Light9774.20.47101
13Becks150194.70.76012
14Kirin14965.00.79012
4Heineken152115.00.77012
3Kronenbourg17075.20.73012

What are the “characteristics” of each cluster?

beer.groupby("scaled_cluster").mean()
caloriessodiumalcoholcostclustercluster2
scaled_cluster
0148.37521.1254.78750.40750.01.00
1105.37510.8753.32500.44751.00.25
2155.25010.7504.97500.76250.01.00
pd.scatter_matrix(X, c=colors[beer.scaled_cluster], alpha=1, figsize=(10,10), s=100)
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: pandas.scatter_matrix is deprecated. Use pandas.plotting.scatter_matrix instead
  if __name__ == '__main__':





array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A279F8F28>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A282989B0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27B5E2E8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27B94F60>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27BE41D0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27C19F28>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27C61F60>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27C71C88>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27CF1860>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27D3B7B8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27D7C5C0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27DC6F98>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27E02748>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27E4FEB8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27E8D588>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A27ED47B8>]], dtype=object)

在这里插入图片描述

聚类评估:轮廓系数(Silhouette Coefficient )

FAO
  • 计算样本i到同簇其他样本的平均距离ai。ai 越小,说明样本i越应该被聚类到该簇。将ai 称为样本i的簇内不相似度。
  • 计算样本i到其他某簇Cj 的所有样本的平均距离bij,称为样本i与簇Cj 的不相似度。定义为样本i的簇间不相似度:bi =min{bi1, bi2, …, bik}
  • si接近1,则说明样本i聚类合理
  • si接近-1,则说明样本i更应该分类到另外的簇
  • 若si 近似为0,则说明样本i在两个簇的边界上。
from sklearn import metrics
score_scaled = metrics.silhouette_score(X,beer.scaled_cluster)
score = metrics.silhouette_score(X,beer.cluster)
print(score_scaled, score)
0.179780680894 0.673177504646
scores = []
for k in range(2,20):
    labels = KMeans(n_clusters=k).fit(X).labels_
    score = metrics.silhouette_score(X, labels)
    scores.append(score)

scores
[0.69176560340794857,
 0.67317750464557957,
 0.58570407211277953,
 0.42254873351720201,
 0.4559182167013377,
 0.43776116697963124,
 0.38946337473125997,
 0.39746405172426014,
 0.33061511213823314,
 0.34131096180393328,
 0.34597752371272478,
 0.31221439248428434,
 0.30707782144770296,
 0.31834561839139497,
 0.28495140011748982,
 0.23498077333071996,
 0.15880910174962809,
 0.084230513801511767]
plt.plot(list(range(2,20)), scores)
plt.xlabel("Number of Clusters Initialized")
plt.ylabel("Sihouette Score")
<matplotlib.text.Text at 0x18a288239e8>

在这里插入图片描述

DBSCAN clustering

from sklearn.cluster import DBSCAN
db = DBSCAN(eps=10, min_samples=2).fit(X)
labels = db.labels_
beer['cluster_db'] = labels
beer.sort_values('cluster_db')
namecaloriessodiumalcoholcostclustercluster2scaled_clustercluster_db
9Budweiser_Light11383.70.40101-1
3Kronenbourg17075.20.73012-1
6Augsberger175245.50.40010-1
17Heilemans_Old_Style144244.90.430100
16Hamms139194.40.430100
14Kirin14965.00.790120
13Becks150194.70.760120
12Michelob_Light135114.20.500110
10Coors140184.60.440100
0Budweiser144154.70.430100
7Srohs_Bohemian_Style149274.70.420100
5Old_Milwaukee145234.60.280100
4Heineken152115.00.770120
2Lowenbrau157150.90.480110
1Schlitz151194.90.430100
8Miller_Lite99104.30.431011
11Coors_Light102154.10.461011
19Schlitz_Light9774.20.471011
15Pabst_Extra_Light68152.30.382012
18Olympia_Goled_Light7262.90.462012
beer.groupby('cluster_db').mean()
caloriessodiumalcoholcostclustercluster2scaled_cluster
cluster_db
-1152.66666713.0000004.8000000.5100000.3333330.6666671.000000
0146.25000017.2500004.3833330.5133330.0000001.0000000.666667
199.33333310.6666674.2000000.4533331.0000000.0000001.000000
270.00000010.5000002.6000000.4200002.0000000.0000001.000000
pd.scatter_matrix(X, c=colors[beer.cluster_db], figsize=(10,10), s=100)
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: pandas.scatter_matrix is deprecated. Use pandas.plotting.scatter_matrix instead
  if __name__ == '__main__':





array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A278A3940>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A284C56D8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A28501CF8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A28550080>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A2856C588>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A285D1F60>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A286211D0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A2865AF98>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A286AABA8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A286E7278>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A2872E390>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A287396A0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000018A287BC358>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A28B356A0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A28B71240>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000018A28BBC470>]], dtype=object)

在这里插入图片描述



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值