Để vẽ dendrogram (cây phân cụm) và điều chỉnh nhánh, ta dùng scipy.cluster.hierarchy.dendrogram và linkage.
Các bước
- Thiết lập figure size và autolayout.
- Tạo 2 cụm dữ liệu đa biến нормаль bằng np.random.multivariate_normal.
- Gộp dữ liệu bằng np.concatenate.
- Tính linkage matrix bằng linkage(X).
- Tạo figure, axes và vẽ dendrogram(Z, ax=ax).
- Hiển thị bằng show().
Ví dụ
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
a = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[2, ])
b = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[3, ])
X = np.concatenate((a, b), )
Z = linkage(X)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
dendrogram(Z, ax=ax)
plt.show()
Kết quả
