| from __future__ import annotations | |
| from typing import Dict, Sequence | |
| import numpy as np | |
| from sklearn.cluster import AgglomerativeClustering | |
| def hypercluster_representatives( | |
| cluster_vectors: Dict[int, np.ndarray], | |
| n_hyperclusters: int | None = None, | |
| ) -> Dict[int, int]: | |
| """Agglomerative clustering over cluster representative vectors.""" | |
| if not cluster_vectors: | |
| return {} | |
| cluster_ids = sorted(cluster_vectors) | |
| x = np.vstack([cluster_vectors[cid] for cid in cluster_ids]) | |
| if len(cluster_ids) == 1: | |
| return {cluster_ids[0]: 0} | |
| n_clusters = n_hyperclusters or max(2, int(np.sqrt(len(cluster_ids)))) | |
| n_clusters = min(n_clusters, len(cluster_ids)) | |
| model = AgglomerativeClustering(n_clusters=n_clusters) | |
| labels = model.fit_predict(x) | |
| return {cluster_id: int(label) for cluster_id, label in zip(cluster_ids, labels)} | |