10 Agglomerative Clustering
In [1]:
import numpy as np
np.random.seed(123)
from sklearn.datasets import make_blobs
x, y = make_blobs(n_samples=300, centers=5, cluster_std=.8)In [2]:
import matplotlib.pyplot as plt
plt.scatter(x[:,0], x[:,1])
plt.show()In [3]:
from sklearn.cluster import AgglomerativeClustering
agg = AgglomerativeClustering(n_clusters=5).fit(x)In [4]:
labels = agg.labels_array([2, 4, 1, 1, 3, 1, 1, 3, 1, 4, 2, 0, 0, 0, 0, 0, 2, 1, 1, 3, 0, 2,
4, 1, 3, 3, 1, 1, 0, 3, 2, 2, 0, 0, 1, 3, 0, 3, 2, 4, 2, 4, 3, 2,
4, 1, 4, 2, 2, 2, 4, 4, 3, 2, 3, 1, 0, 4, 3, 3, 1, 1, 1, 0, 0, 3,
1, 3, 0, 2, 1, 4, 1, 4, 3, 2, 0, 2, 1, 1, 2, 0, 3, 0, 4, 0, 0, 3,
3, 0, 3, 4, 2, 2, 1, 1, 2, 1, 1, 1, 3, 1, 4, 0, 3, 0, 2, 4, 3, 3,
2, 1, 0, 0, 2, 1, 2, 0, 4, 2, 1, 3, 3, 3, 2, 2, 1, 2, 3, 1, 1, 3,
0, 1, 4, 1, 4, 3, 3, 4, 3, 4, 1, 3, 2, 4, 0, 4, 0, 3, 4, 1, 1, 4,
2, 3, 1, 2, 2, 0, 1, 1, 1, 1, 2, 0, 4, 2, 2, 3, 3, 2, 2, 4, 1, 0,
1, 4, 4, 3, 3, 4, 2, 4, 3, 3, 4, 4, 3, 0, 2, 3, 2, 1, 0, 4, 1, 1,
3, 4, 0, 3, 3, 1, 0, 4, 0, 0, 0, 1, 3, 4, 3, 2, 4, 3, 2, 2, 4, 0,
1, 2, 0, 0, 2, 3, 0, 4, 4, 4, 0, 0, 4, 4, 4, 3, 0, 0, 4, 1, 2, 2,
3, 4, 2, 0, 2, 3, 3, 2, 0, 0, 1, 2, 0, 1, 4, 0, 3, 4, 4, 2, 2, 3,
1, 0, 4, 1, 0, 4, 4, 2, 4, 0, 0,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