凝聚聚类

1、凝聚算法

算法首先声明每个点是自己的簇,然后合并两个最相似的簇,直到满足某种停止准则为止。scikit-learn 中实现的停止准则是簇的个数,因此相似的簇合并,直到仅剩下指定个数的簇。

2、链接准则

规定如何度量“最相似的簇”,scikit-learn 中实现了三种选项:

  • ward,默认选项,挑选两个簇来合并,使得所有簇中的方差增加最小。通常会得到大小差不多相等的簇。
  • average,将簇中所有点之间平均距离最小的两个簇合并。
  • complete,将簇中点之间最大距离最小的两个簇合并。
    如果簇中的成员个数非常不同(比如其中一个比其他所有都大得多),那么average 或 complete 可能效果更好。

3、sklearn 实现

凝聚算法不能对新数据点做出预测,因此** AgglomerativeClustering **没有 predict 方法,可以使用 fit_predict 方法。

from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
from scipy.cluster.hierarchy import dendrogram,ward
import matplotlib.pyplot as plt

import mglearn

X,y=make_blobs(random_state=1)

agg=AgglomerativeClustering(n_clusters=3)
assignment=agg.fit_predict(X)

mglearn.discrete_scatter(X[:,0],X[:,1],assignment)
plt.xlabel('Feature 0')
plt.ylabel('Feature 1')
plt.legend()
plt.show()

plt.clf()
mglearn.plots.plot_agglomerative()
plt.show()

X,y=make_blobs(random_state=0,n_samples=12)
linkage_array=ward(X)
dendrogram(linkage_array)
ax=plt.gca()
bounds=ax.get_xbound()
ax.plot(bounds,[7.25,7.25],'--',c='k')
ax.plot(bounds,[4,4],'--',c='k')
ax.text(bounds[1],7.25,' two clusters',va='center',fontdict={'size':15})
ax.text(bounds[1],4,' three clusters',va='center',fontdict={'size':15})
plt.xlabel('Sample index')
plt.ylabel('Cluster distance')
plt.show()

你可能感兴趣的:(凝聚聚类)