0


聚类算法(上):8个常见的无监督聚类方法介绍和比较

无监督聚类方法的评价指标必须依赖于数据和聚类结果的内在属性,例如聚类的紧凑性和分离性,与外部知识的一致性,以及同一算法不同运行结果的稳定性。

本文将全面概述Scikit-Learn库中用于的聚类技术以及各种评估方法。

本文将分为2个部分,1、常见算法比较 2、聚类技术的各种评估方法

本文作为第一部分将介绍和比较各种聚类算法:

  • K-Means
  • Affinity Propagation
  • Agglomerative Clustering
  • Mean Shift Clustering
  • Bisecting K-Means
  • DBSCAN
  • OPTICS
  • BIRCH

首先我们生成一些数据,后面将使用这些数据作为聚类技术的输入。

  1. importpandasaspd
  2. importnumpyasnp
  3. importseabornassns
  4. importmatplotlib.pyplotasplt
  5. #Set the number of samples and features
  6. n_samples=1000
  7. n_features=4
  8. #Create an empty array to store the data
  9. data=np.empty((n_samples, n_features))
  10. #Generate random data for each feature
  11. foriinrange(n_features):
  12. data[:, i] =np.random.normal(size=n_samples)
  13. #Create 5 clusters with different densities and centroids
  14. cluster1=data[:200, :] +np.random.normal(size=(200, n_features), scale=0.5)
  15. cluster2=data[200:400, :] +np.random.normal(size=(200, n_features), scale=1) +np.array([5,5,5,5])
  16. cluster3=data[400:600, :] +np.random.normal(size=(200, n_features), scale=1.5) +np.array([-5,-5,-5,-5])
  17. cluster4=data[600:800, :] +np.random.normal(size=(200, n_features), scale=2) +np.array([5,-5,5,-5])
  18. cluster5=data[800:, :] +np.random.normal(size=(200, n_features), scale=2.5) +np.array([-5,5,-5,5])
  19. #Combine the clusters into one dataset
  20. X=np.concatenate((cluster1, cluster2, cluster3, cluster4, cluster5))
  21. # Plot the data
  22. plt.scatter(X[:, 0], X[:, 1])
  23. plt.show()

结果如下:

我们将用特征值和簇ID创建一个DF。稍后在模型性能时将使用这些数据。

  1. df=pd.DataFrame(X, columns=["feature_1", "feature_2", "feature_3", "feature_4"])
  2. cluster_id=np.concatenate((np.zeros(200), np.ones(200), np.full(200, 2), np.full(200, 3), np.full(200, 4)))
  3. df["cluster_id"] =cluster_id
  4. df

现在我们将构建和可视化8个不同的聚类模型:

1、K-Means

K-Means聚类算法是一种常用的聚类算法,它将数据点分为K个簇,每个簇的中心点是其所有成员的平均值。K-Means算法的核心是迭代寻找最优的簇心位置,直到达到收敛状态。

K-Means算法的优点是简单易懂,计算速度较快,适用于大规模数据集。但是它也存在一些缺点,例如对于非球形簇的处理能力较差,容易受到初始簇心的选择影响,需要预先指定簇的数量K等。此外,当数据点之间存在噪声或者离群点时,K-Means算法可能会将它们分配到错误的簇中。

  1. #K-Means
  2. fromsklearn.clusterimportKMeans
  3. #Define function:
  4. kmeans=KMeans(n_clusters=5)
  5. #Fit the model:
  6. km=kmeans.fit(X)
  7. km_labels=km.labels_
  8. #Print results:
  9. #print(kmeans.labels_)
  10. #Visualise results:
  11. plt.scatter(X[:, 0], X[:, 1],
  12. c=kmeans.labels_,
  13. s=70, cmap='Paired')
  14. plt.scatter(kmeans.cluster_centers_[:, 0],
  15. kmeans.cluster_centers_[:, 1],
  16. marker='^', s=100, linewidth=2,
  17. c=[0, 1, 2, 3, 4])

2、Affinity Propagation

Affinity Propagation是一种基于图论的聚类算法,旨在识别数据中的"exemplars"(代表点)和"clusters"(簇)。与K-Means等传统聚类算法不同,Affinity Propagation不需要事先指定聚类数目,也不需要随机初始化簇心,而是通过计算数据点之间的相似性得出最终的聚类结果。

Affinity Propagation算法的优点是不需要预先指定聚类数目,且能够处理非凸形状的簇。但是该算法的计算复杂度较高,需要大量的存储空间和计算资源,并且对于噪声点和离群点的处理能力较弱。

  1. fromsklearn.clusterimportAffinityPropagation
  2. #Fit the model:
  3. af=AffinityPropagation(preference=-563, random_state=0).fit(X)
  4. cluster_centers_indices=af.cluster_centers_indices_
  5. af_labels=af.labels_
  6. n_clusters_=len(cluster_centers_indices)
  7. #Print number of clusters:
  8. print(n_clusters_)
  9. importmatplotlib.pyplotasplt
  10. fromitertoolsimportcycle
  11. plt.close("all")
  12. plt.figure(1)
  13. plt.clf()
  14. colors=cycle("bgrcmykbgrcmykbgrcmykbgrcmyk")
  15. fork, colinzip(range(n_clusters_), colors):
  16. class_members=af_labels==k
  17. cluster_center=X[cluster_centers_indices[k]]
  18. plt.plot(X[class_members, 0], X[class_members, 1], col+".")
  19. plt.plot(
  20. cluster_center[0],
  21. cluster_center[1],
  22. "o",
  23. markerfacecolor=col,
  24. markeredgecolor="k",
  25. markersize=14,
  26. )
  27. forxinX[class_members]:
  28. plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col)
  29. plt.title("Estimated number of clusters: %d"%n_clusters_)
  30. plt.show()

3、Agglomerative Clustering

凝聚层次聚类(Agglomerative Clustering)是一种自底向上的聚类算法,它将每个数据点视为一个初始簇,并将它们逐步合并成更大的簇,直到达到停止条件为止。在该算法中,每个数据点最初被视为一个单独的簇,然后逐步合并簇,直到所有数据点被合并为一个大簇。

Agglomerative Clustering算法的优点是适用于不同形状和大小的簇,且不需要事先指定聚类数目。此外,该算法也可以输出聚类层次结构,便于分析和可视化。缺点是计算复杂度较高,尤其是在处理大规模数据集时,需要消耗大量的计算资源和存储空间。此外,该算法对初始簇的选择也比较敏感,可能会导致不同的聚类结果。

  1. fromsklearn.clusterimportAgglomerativeClustering
  2. #Fit the model:
  3. clustering=AgglomerativeClustering(n_clusters=5).fit(X)
  4. AC_labels=clustering.labels_
  5. n_clusters=clustering.n_clusters_
  6. print("number of estimated clusters : %d"%clustering.n_clusters_)
  7. # Plot clustering results
  8. colors= ['purple', 'orange', 'green', 'blue', 'red']
  9. forindex, metricinenumerate([#"cosine",
  10. "euclidean",
  11. #"cityblock"
  12. ]):
  13. model=AgglomerativeClustering(
  14. n_clusters=5, linkage="ward", affinity=metric
  15. )
  16. model.fit(X)
  17. plt.figure()
  18. plt.axes([0, 0, 1, 1])
  19. forl, cinzip(np.arange(model.n_clusters), colors):
  20. plt.plot(X[model.labels_==l].T, c=c, alpha=0.5)
  21. plt.axis("tight")
  22. plt.axis("off")
  23. plt.suptitle("AgglomerativeClustering(affinity=%s)"%metric, size=20)
  24. plt.show()

4、Mean Shift Clustering

Mean Shift Clustering是一种基于密度的非参数聚类算法,其基本思想是通过寻找数据点密度最大的位置(称为"局部最大值"或"高峰"),来识别数据中的簇。算法的核心是通过对每个数据点进行局部密度估计,并将密度估计的结果用于计算数据点移动的方向和距离。算法的核心是通过对每个数据点进行局部密度估计,并将密度估计的结果用于计算数据点移动的方向和距离。

Mean Shift Clustering算法的优点是不需要指定簇的数目,且对于形状复杂的簇也有很好的效果。算法还能够有效地处理噪声数据。他的缺点也是计算复杂度较高,尤其是在处理大规模数据集时,需要消耗大量的计算资源和存储空间,该算法还对初始参数的选择比较敏感,需要进行参数调整和优化。

  1. fromsklearn.clusterimportMeanShift, estimate_bandwidth
  2. # The following bandwidth can be automatically detected using
  3. bandwidth=estimate_bandwidth(X, quantile=0.2, n_samples=100)
  4. #Fit the model:
  5. ms=MeanShift(bandwidth=bandwidth)
  6. ms.fit(X)
  7. MS_labels=ms.labels_
  8. cluster_centers=ms.cluster_centers_
  9. labels_unique=np.unique(labels)
  10. n_clusters_=len(labels_unique)
  11. print("number of estimated clusters : %d"%n_clusters_)
  12. fromitertoolsimportcycle
  13. plt.figure(1)
  14. plt.clf()
  15. colors=cycle("bgrcmykbgrcmykbgrcmykbgrcmyk")
  16. fork, colinzip(range(n_clusters_), colors):
  17. my_members=labels==k
  18. cluster_center=cluster_centers[k]
  19. plt.plot(X[my_members, 0], X[my_members, 1], col+".")
  20. plt.plot(
  21. cluster_center[0],
  22. cluster_center[1],
  23. "o",
  24. markerfacecolor=col,
  25. markeredgecolor="k",
  26. markersize=14,
  27. )
  28. plt.title("Estimated number of clusters: %d"%n_clusters_)
  29. plt.show()

5、Bisecting K-Means

Bisecting K-Means是一种基于K-Means算法的层次聚类算法,其基本思想是将所有数据点划分为一个簇,然后将该簇分成两个子簇,并对每个子簇分别应用K-Means算法,重复执行这个过程,直到达到预定的聚类数目为止。

算法首先将所有数据点视为一个初始簇,然后对该簇应用K-Means算法,将该簇分成两个子簇,并计算每个子簇的误差平方和(SSE)。然后,选择误差平方和最大的子簇,并将其再次分成两个子簇,重复执行这个过程,直到达到预定的聚类数目为止。

Bisecting K-Means算法的优点是具有较高的准确性和稳定性,能够有效地处理大规模数据集,并且不需要指定初始聚类数目。该算法还能够输出聚类层次结构,便于分析和可视化。缺点是计算复杂度较高,尤其是在处理大规模数据集时,需要消耗大量的计算资源和存储空间。此外该算法对初始簇的选择也比较敏感,可能会导致不同的聚类结果。

  1. fromsklearn.clusterimportBisectingKMeans
  2. #Build and fit model:
  3. bisect_means=BisectingKMeans(n_clusters=5).fit(X)
  4. BKM_labels=bisect_means.labels_
  5. #Print model attributes:
  6. #print('Labels: ', bisect_means.labels_)
  7. print('Number of clusters: ', bisect_means.n_clusters)
  8. #Define varaibles to be included in scatterdot:
  9. y=bisect_means.labels_
  10. #print(y)
  11. centers=bisect_means.cluster_centers_
  12. # Visualize the results using a scatter plot
  13. plt.scatter(X[:, 0], X[:, 1], c=y)
  14. plt.scatter(centers[:, 0], centers[:, 1], c='r', s=100)
  15. plt.show()

6、DBSCAN

DBSCAN (Density-Based Spatial Clustering of Applications with Noise)是一种基于密度的聚类算法,其可以有效地发现任意形状的簇,并能够处理噪声数据。DBSCAN算法的核心思想是:对于一个给定的数据点,如果它的密度达到一定的阈值,则它属于一个簇中;否则,它被视为噪声点。

DBSCAN算法的优点是能够自动识别簇的数目,并且对于任意形状的簇都有较好的效果。并且还能够有效地处理噪声数据,不需要预先指定簇的数目。缺点是对于密度差异较大的数据集,可能会导致聚类效果不佳,需要进行参数调整和优化。另外该算法对于高维数据集的效果也不如其他算法

  1. fromsklearn.clusterimportDBSCAN
  2. db=DBSCAN(eps=3, min_samples=10).fit(X)
  3. DBSCAN_labels=db.labels_
  4. # Number of clusters in labels, ignoring noise if present.
  5. n_clusters_=len(set(labels)) - (1if-1inlabelselse0)
  6. n_noise_=list(labels).count(-1)
  7. print("Estimated number of clusters: %d"%n_clusters_)
  8. print("Estimated number of noise points: %d"%n_noise_)
  9. unique_labels=set(labels)
  10. core_samples_mask=np.zeros_like(labels, dtype=bool)
  11. core_samples_mask[db.core_sample_indices_] =True
  12. colors= [plt.cm.Spectral(each) foreachinnp.linspace(0, 1, len(unique_labels))]
  13. fork, colinzip(unique_labels, colors):
  14. ifk==-1:
  15. # Black used for noise.
  16. col= [0, 0, 0, 1]
  17. class_member_mask=labels==k
  18. xy=X[class_member_mask&core_samples_mask]
  19. plt.plot(
  20. xy[:, 0],
  21. xy[:, 1],
  22. "o",
  23. markerfacecolor=tuple(col),
  24. markeredgecolor="k",
  25. markersize=14,
  26. )
  27. xy=X[class_member_mask&~core_samples_mask]
  28. plt.plot(
  29. xy[:, -1],
  30. xy[:, 1],
  31. "o",
  32. markerfacecolor=tuple(col),
  33. markeredgecolor="k",
  34. markersize=6,
  35. )
  36. plt.title(f"Estimated number of clusters: {n_clusters_}")
  37. plt.show()

7、OPTICS

OPTICS(Ordering Points To Identify the Clustering Structure)是一种基于密度的聚类算法,其能够自动确定簇的数量,同时也可以发现任意形状的簇,并能够处理噪声数据。OPTICS算法的核心思想是:对于一个给定的数据点,通过计算它到其它点的距离,确定其在密度上的可达性,从而构建一个基于密度的距离图。然后,通过扫描该距离图,自动确定簇的数量,并对每个簇进行划分。

OPTICS算法的优点是能够自动确定簇的数量,并能够处理任意形状的簇,并能够有效地处理噪声数据。该算法还能够输出聚类层次结构,便于分析和可视化。缺点是计算复杂度较高,尤其是在处理大规模数据集时,需要消耗大量的计算资源和存储空间。另外就是该算法对于密度差异较大的数据集,可能会导致聚类效果不佳。

  1. fromsklearn.clusterimportOPTICS
  2. importmatplotlib.gridspecasgridspec
  3. #Build OPTICS model:
  4. clust=OPTICS(min_samples=3, min_cluster_size=100, metric='euclidean')
  5. # Run the fit
  6. clust.fit(X)
  7. space=np.arange(len(X))
  8. reachability=clust.reachability_[clust.ordering_]
  9. OPTICS_labels=clust.labels_[clust.ordering_]
  10. labels=clust.labels_[clust.ordering_]
  11. plt.figure(figsize=(10, 7))
  12. G=gridspec.GridSpec(2, 3)
  13. ax1=plt.subplot(G[0, 0])
  14. ax2=plt.subplot(G[1, 0])
  15. # Reachability plot
  16. colors= ["g.", "r.", "b.", "y.", "c."]
  17. forklass, colorinzip(range(0, 5), colors):
  18. Xk=space[labels==klass]
  19. Rk=reachability[labels==klass]
  20. ax1.plot(Xk, Rk, color, alpha=0.3)
  21. ax1.plot(space[labels==-1], reachability[labels==-1], "k.", alpha=0.3)
  22. ax1.set_ylabel("Reachability (epsilon distance)")
  23. ax1.set_title("Reachability Plot")
  24. # OPTICS
  25. colors= ["g.", "r.", "b.", "y.", "c."]
  26. forklass, colorinzip(range(0, 5), colors):
  27. Xk=X[clust.labels_==klass]
  28. ax2.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)
  29. ax2.plot(X[clust.labels_==-1, 0], X[clust.labels_==-1, 1], "k+", alpha=0.1)
  30. ax2.set_title("Automatic Clustering\nOPTICS")
  31. plt.tight_layout()
  32. plt.show()

8、BIRCH

BIRCH(Balanced Iterative Reducing and Clustering using Hierarchies)是一种基于层次聚类的聚类算法,其可以快速地处理大规模数据集,并且对于任意形状的簇都有较好的效果。BIRCH算法的核心思想是:通过对数据集进行分级聚类,逐步减小数据规模,最终得到簇结构。BIRCH算法采用一种类似于B树的结构,称为CF树,它可以快速地插入和删除子簇,并且可以自动平衡,从而确保簇的质量和效率。

BIRCH算法的优点是能够快速处理大规模数据集,并且对于任意形状的簇都有较好的效果。该算法对于噪声数据和离群点也有较好的容错性。缺点是对于密度差异较大的数据集,可能会导致聚类效果不佳,对于高维数据集的效果也不如其他算法。

  1. importmatplotlib.colorsascolors
  2. fromsklearn.clusterimportBirch, MiniBatchKMeans
  3. fromtimeimporttime
  4. fromitertoolsimportcycle
  5. # Use all colors that matplotlib provides by default.
  6. colors_=cycle(colors.cnames.keys())
  7. fig=plt.figure(figsize=(12, 4))
  8. fig.subplots_adjust(left=0.04, right=0.98, bottom=0.1, top=0.9)
  9. # Compute clustering with BIRCH with and without the final clustering step
  10. # and plot.
  11. birch_models= [
  12. Birch(threshold=1.7, n_clusters=None),
  13. Birch(threshold=1.7, n_clusters=5),
  14. ]
  15. final_step= ["without global clustering", "with global clustering"]
  16. forind, (birch_model, info) inenumerate(zip(birch_models, final_step)):
  17. t=time()
  18. birch_model.fit(X)
  19. print("BIRCH %s as the final step took %0.2f seconds"% (info, (time() -t)))
  20. # Plot result
  21. labels=birch_model.labels_
  22. centroids=birch_model.subcluster_centers_
  23. n_clusters=np.unique(labels).size
  24. print("n_clusters : %d"%n_clusters)
  25. ax=fig.add_subplot(1, 3, ind+1)
  26. forthis_centroid, k, colinzip(centroids, range(n_clusters), colors_):
  27. mask=labels==k
  28. ax.scatter(X[mask, 0], X[mask, 1], c="w", edgecolor=col, marker=".", alpha=0.5)
  29. ifbirch_model.n_clustersisNone:
  30. ax.scatter(this_centroid[0], this_centroid[1], marker="+", c="k", s=25)
  31. ax.set_ylim([-12, 12])
  32. ax.set_xlim([-12, 12])
  33. ax.set_autoscaley_on(False)
  34. ax.set_title("BIRCH %s"%info)
  35. plt.show()

总结

上面就是我们常见的8个聚类算法,我们对他们进行了简单的说明和比较,并且用sklearn演示了如何使用,在下一篇文章中我们将介绍聚类模型评价方法。

“聚类算法(上):8个常见的无监督聚类方法介绍和比较”的评论:

还没有评论