7-2基于Kmeans和DBSCAN算法的啤酒成分分析实战

beer数据集 聚类分析

import pandas as pd

beer = pd.read_csv('./data/data.txt', sep=' ')
print(beer)
                    name  calories  sodium  alcohol  cost
0              Budweiser       144      15      4.7  0.43
1                Schlitz       151      19      4.9  0.43
2              Lowenbrau       157      15      0.9  0.48
3            Kronenbourg       170       7      5.2  0.73
4               Heineken       152      11      5.0  0.77
5          Old_Milwaukee       145      23      4.6  0.28
6             Augsberger       175      24      5.5  0.40
7   Srohs_Bohemian_Style       149      27      4.7  0.42
8            Miller_Lite        99      10      4.3  0.43
9        Budweiser_Light       113       8      3.7  0.40
10                 Coors       140      18      4.6  0.44
11           Coors_Light       102      15      4.1  0.46
12        Michelob_Light       135      11      4.2  0.50
13                 Becks       150      19      4.7  0.76
14                 Kirin       149       6      5.0  0.79
15     Pabst_Extra_Light        68      15      2.3  0.38
16                 Hamms       139      19      4.4  0.43
17   Heilemans_Old_Style       144      24      4.9  0.43
18   Olympia_Goled_Light        72       6      2.9  0.46
19         Schlitz_Light        97       7      4.2  0.47
X = beer[['calories', 'sodium', 'alcohol', 'cost']]

K-means聚类算法

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, 2, 2, 0, 2, 0, 0, 0, 1, 0, 0, 1, 2])
beer['cluster'] = km.labels_
beer['cluster2'] = km2.labels_
beer.sort_values('cluster')
namecaloriessodiumalcoholcostclustercluster2
0Budweiser144154.70.4300
1Schlitz151194.90.4300
2Lowenbrau157150.90.4800
3Kronenbourg17075.20.7300
4Heineken152115.00.7700
5Old_Milwaukee145234.60.2800
6Augsberger175245.50.4000
7Srohs_Bohemian_Style149274.70.4200
17Heilemans_Old_Style144244.90.4300
10Coors140184.60.4400
16Hamms139194.40.4300
12Michelob_Light135114.20.5000
13Becks150194.70.7600
14Kirin14965.00.7900
18Olympia_Goled_Light7262.90.4611
15Pabst_Extra_Light68152.30.3811
9Budweiser_Light11383.70.4021
8Miller_Lite99104.30.4321
11Coors_Light102154.10.4621
19Schlitz_Light9774.20.4721
from pandas.tools.plotting import scatter_matrix
%matplotlib inline

cluster_centers = km.cluster_centers_
cluster2_centers = km2.cluster_centers_
beer.groupby('cluster').mean()
caloriessodiumalcoholcostcluster2
cluster
0150.0017.04.5214290.5207140
170.0010.52.6000000.4200001
2102.7510.04.0750000.4400001
beer.groupby('cluster2').mean()
caloriessodiumalcoholcostcluster
cluster2
0150.00000017.0000004.5214290.5207140.000000
191.83333310.1666673.5833330.4333331.666667
centers = beer.groupby('cluster').mean().reset_index()
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')
Text(0, 0.5, 'alcohol')

在这里插入图片描述

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:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
  """Entry point for launching an IPython kernel.





Text(0.5, 0.98, 'With 3 centroids initialized')

在这里插入图片描述

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:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
  """Entry point for launching an IPython kernel.





Text(0.5, 0.98, 'With 2 centroids initialized')

在这里插入图片描述

数据标准化或归一化

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py:625: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.
  return self.partial_fit(X, y)
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py:462: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by StandardScaler.
  return self.fit(X, **fit_params).transform(X)





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.43000
1Schlitz151194.90.43000
17Heilemans_Old_Style144244.90.43000
16Hamms139194.40.43000
5Old_Milwaukee145234.60.28000
6Augsberger175245.50.40000
7Srohs_Bohemian_Style149274.70.42000
10Coors140184.60.44000
15Pabst_Extra_Light68152.30.38111
12Michelob_Light135114.20.50001
11Coors_Light102154.10.46211
9Budweiser_Light11383.70.40211
8Miller_Lite99104.30.43211
2Lowenbrau157150.90.48001
18Olympia_Goled_Light7262.90.46111
19Schlitz_Light9774.20.47211
13Becks150194.70.76002
14Kirin14965.00.79002
4Heineken152115.00.77002
3Kronenbourg17075.20.73002
beer.groupby('scaled_cluster').mean()
caloriessodiumalcoholcostclustercluster2
scaled_cluster
0148.37521.1254.78750.40750.000.00
1105.37510.8753.32500.44751.250.75
2155.25010.7504.97500.76250.000.00
pd.scatter_matrix(X, c=colors[beer.scaled_cluster], alpha=1, figsize=(10,10), s=100)
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: pandas.scatter_matrix is deprecated, use pandas.plotting.scatter_matrix instead
  """Entry point for launching an IPython kernel.





array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000010717630>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000102F2668>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000FFDE8D0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000FFCFD68>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000000001072F208>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010729470>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000105FA6D8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010690DD8>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000000010690E10>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000106242B0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010330518>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000001033B780>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x00000000105A89E8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000102A0C50>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000102BEEB8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010574160>]],
      dtype=object)

在这里插入图片描述

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

FAO ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190318174226115.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjYwMDA3Mg==,size_16,color_FFFFFF,t_70) - 计算样本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 = metrics.silhouette_score(X,beer.cluster)
score_scaled = metrics.silhouette_score(X, beer.scaled_cluster)
print(score, score_scaled)
0.6731775046455796 0.1797806808940007
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.6917656034079486,
 0.6731775046455796,
 0.5857040721127795,
 0.4225487335172022,
 0.4559182167013378,
 0.43776116697963136,
 0.38946337473126,
 0.39746405172426014,
 0.3915697409245163,
 0.3413109618039333,
 0.3459775237127248,
 0.31221439248428434,
 0.30707782144770296,
 0.31834561839139497,
 0.2849514001174898,
 0.23498077333071996,
 0.1588091017496281,
 0.08423051380151177]
plt.plot(list(range(2,20)), scores)
plt.xlabel("Number of Clusters Initialized")
plt.ylabel("Sihouette Score")
Text(0, 0.5, 'Sihouette Score')

在这里插入图片描述

DBSCAN聚类

from sklearn.cluster import DBSCAN

db = DBSCAN(eps=10, min_samples=2).fit(X)  #半径为10,密度为2
labels = db.labels_
beer['cluster_db'] = labels
beer.sort_values('cluster_db')
namecaloriessodiumalcoholcostclustercluster2scaled_clustercluster_db
9Budweiser_Light11383.70.40211-1
3Kronenbourg17075.20.73002-1
6Augsberger175245.50.40000-1
17Heilemans_Old_Style144244.90.430000
16Hamms139194.40.430000
14Kirin14965.00.790020
13Becks150194.70.760020
12Michelob_Light135114.20.500010
10Coors140184.60.440000
0Budweiser144154.70.430000
7Srohs_Bohemian_Style149274.70.420000
5Old_Milwaukee145234.60.280000
4Heineken152115.00.770020
2Lowenbrau157150.90.480010
1Schlitz151194.90.430000
8Miller_Lite99104.30.432111
11Coors_Light102154.10.462111
19Schlitz_Light9774.20.472111
15Pabst_Extra_Light68152.30.381112
18Olympia_Goled_Light7262.90.461112
beer.groupby('cluster_db').mean()
caloriessodiumalcoholcostclustercluster2scaled_cluster
cluster_db
-1152.66666713.0000004.8000000.5100000.6666670.3333331.000000
0146.25000017.2500004.3833330.5133330.0000000.0000000.666667
199.33333310.6666674.2000000.4533332.0000001.0000001.000000
270.00000010.5000002.6000000.4200001.0000001.0000001.000000
pd.scatter_matrix(X, c=colors[beer.cluster_db], figsize=(10,10), s=100)
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: pandas.scatter_matrix is deprecated, use pandas.plotting.scatter_matrix instead
  """Entry point for launching an IPython kernel.





array([[<matplotlib.axes._subplots.AxesSubplot object at 0x00000000107B6F98>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010542C18>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000001042E278>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000107C0208>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x00000000109376D8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000010984940>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000012022BA8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000001206C438>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000000001206C470>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000011F848D0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000011F04B38>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000012093DA0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x00000000121A6048>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000000011F672B0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000120E5518>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x00000000107AA780>]],
      dtype=object)

在这里插入图片描述


  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用[2],KMeans算法DBSCAN算法都是聚类算法,但是它们的实现方式不同。KMeans算法需要预先指定聚类的数量K,然后通过计算样本之间的距离来将样本分为K个簇。而DBSCAN算法则是通过密度来判断样本是否属于同一个簇,不需要预先指定簇的数量。 下面是KMeans算法DBSCAN算法进行预测分析的步骤: 1. KMeans算法预测分析 首先,我们需要导入KMeans算法的库: ```python from sklearn.cluster import KMeans ``` 然后,我们需要准备好数据集,这里以iris数据集为例: ```python from sklearn.datasets import load_iris iris = load_iris() X = iris.data ``` 接着,我们可以使用KMeans算法进行聚类: ```python kmeans = KMeans(n_clusters=3, random_state=0).fit(X) ``` 其中,n_clusters表示聚类的数量,这里设为3。fit()方法用于拟合数据。 最后,我们可以输出聚类结果: ```python print(kmeans.labels_) ``` 2. DBSCAN算法预测分析 首先,我们需要导入DBSCAN算法的库: ```python from sklearn.cluster import DBSCAN ``` 然后,我们需要准备好数据集,这里以iris数据集为例: ```python from sklearn.datasets import load_iris iris = load_iris() X = iris.data ``` 接着,我们可以使用DBSCAN算法进行聚类: ```python dbscan = DBSCAN(eps=0.5, min_samples=5).fit(X) ``` 其中,eps表示邻域的半径,min_samples表示邻域中最少的样本数量。fit()方法用于拟合数据。 最后,我们可以输出聚类结果: ```python print(dbscan.labels_) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值