File size: 882 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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)}