muo*_*uon 4 python cluster-analysis hierarchical-clustering scipy data-science
from scipy.cluster.hierarchy import dendrogram, linkage,fcluster
import numpy as np
import matplotlib.pyplot as plt
# data
np.random.seed(4711) # for repeatability of this tutorial
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a, b),)
plt.scatter(X[:,0], X[:,1])
Run Code Online (Sandbox Code Playgroud)
# fit clusters
Z = linkage(X, method='ward', metric='euclidean', preserve_input=True)
# plot dendrogram
Run Code Online (Sandbox Code Playgroud)
max_d = 50
clusters = fcluster(Z, max_d, criterion='distance')
# now if I have new data
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[10,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[5,])
X_test = np.concatenate((a, b),)
print(X_test.shape) # 150 samples with 2 dimensions
plt.scatter(X_test[:,0], X_test[:,1])
plt.show()
Run Code Online (Sandbox Code Playgroud)
如何计算新数据的距离并使用训练数据中的聚类分配聚类?
代码参考:joernhees.de
群集没有培训和测试阶段.这是一种探索性的方法.您可以浏览数据,还可以通过重新运行算法来浏览新数据.但是根据这种算法的本质,你不能有意义地将新数据"分配"给旧结构,因为这些数据可以完全改变发现的结构.
聚类算法不用于分类的替代品.如果要对新实例进行分类,请使用分类器,并使用此工作流程:
当然,有一些例外.在k-means和Ward中(但不是例如在单链路中),最近的质心分类器可以将发现的模型直接应用于新数据.但是,这意味着将聚类"转换"为静态分类器,结果可能不再是整个数据集的局部最优值(另请参见:概念漂移)