linkscluster 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,256 @@
1
+ Metadata-Version: 2.4
2
+ Name: linkscluster
3
+ Version: 0.1.0
4
+ Summary: Links: A High-Dimensional Online Clustering Method
5
+ Home-page: https://github.com/wq2012/LinksCluster
6
+ Author: Quan Wang
7
+ Author-email: quanw@google.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: scipy
15
+ Requires-Dist: scikit-learn
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license-file
23
+ Dynamic: requires-dist
24
+ Dynamic: summary
25
+
26
+ # Links: A High-Dimensional Online Clustering Method
27
+ [![Python application](https://github.com/wq2012/LinksCluster/workflows/Python%20application/badge.svg)](https://github.com/wq2012/LinksCluster/actions)
28
+ [![PyPI Version](https://img.shields.io/pypi/v/linkscluster.svg)](https://pypi.python.org/pypi/linkscluster)
29
+ [![Python Versions](https://img.shields.io/pypi/pyversions/linkscluster.svg)](https://pypi.org/project/linkscluster)
30
+ [![Downloads](https://static.pepy.tech/badge/linkscluster)](https://www.pepy.tech/projects/linkscluster)
31
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
32
+
33
+ Python implementation of the **Links** high-dimensional online clustering algorithm, designed for unit vectors on the hypersphere S^(N-1).
34
+
35
+ ## Overview
36
+
37
+ Links is an online clustering algorithm designed to cluster high-dimensional unit vectors efficiently in real time as data streams in. Unlike traditional batch clustering algorithms (such as [SpectralCluster](https://github.com/wq2012/SpectralCluster) or k-means) that require concurrent access to all data points, Links assigns each new datum to a cluster immediately upon arrival with no knowledge of future vectors and no backtracking.
38
+
39
+ ---
40
+
41
+ ## Disclaimer
42
+
43
+ **This is not an official Google product.**
44
+
45
+ ---
46
+
47
+ ## Installation
48
+
49
+ Install the package from PyPI:
50
+
51
+ ```bash
52
+ pip3 install linkscluster
53
+ ```
54
+
55
+ Or install from source:
56
+
57
+ ```bash
58
+ git clone https://github.com/wq2012/LinksCluster.git
59
+ cd LinksCluster
60
+ pip3 install .
61
+ ```
62
+
63
+ ---
64
+
65
+ ## Quick Start
66
+
67
+ ### 1. Standard scikit-learn API
68
+
69
+ `LinksClusterer` follows the standard scikit-learn estimator interface (`fit`, `predict`, `fit_predict`, `partial_fit`):
70
+
71
+ ```python
72
+ import numpy as np
73
+ from linkscluster import LinksClusterer
74
+
75
+ # Create synthetic unit embeddings (n_samples, n_features)
76
+ X = np.random.randn(500, 128)
77
+
78
+ # Initialize the clusterer
79
+ clusterer = LinksClusterer(
80
+ cluster_similarity_threshold=0.6, # Tc
81
+ subcluster_similarity_threshold=0.85, # Ts
82
+ pair_similarity_maximum=0.95, # Tp
83
+ )
84
+
85
+ # Fit and return cluster labels
86
+ labels = clusterer.fit_predict(X)
87
+ print(f"Number of clusters found: {clusterer.n_clusters_}")
88
+ print(f"Cluster labels: {labels}")
89
+ ```
90
+
91
+ ### 2. Online Streaming API
92
+
93
+ For real-time streaming applications (e.g. processing incoming audio frames or video embeddings datum-by-datum):
94
+
95
+ ```python
96
+ from linkscluster import LinksClusterer
97
+
98
+ clusterer = LinksClusterer(tc=0.6, ts=0.85, tp=0.95)
99
+
100
+ # Process vectors as they arrive in real time
101
+ for x in embedding_stream:
102
+ # Returns integer cluster ID immediately with zero backtracking
103
+ cluster_id = clusterer.predict_next(x)
104
+ print(f"Received vector assigned to cluster: {cluster_id}")
105
+ ```
106
+
107
+ You can also use Python generators via `predict_stream`:
108
+
109
+ ```python
110
+ for cluster_id in clusterer.predict_stream(embedding_stream):
111
+ handle_cluster_id(cluster_id)
112
+ ```
113
+
114
+ Or batch incremental updates via `partial_fit`:
115
+
116
+ ```python
117
+ clusterer.partial_fit(mini_batch)
118
+ ```
119
+
120
+ ### 3. Online Labels vs. Final Labels
121
+
122
+ In Links, each vector is assigned a cluster ID upon arrival. Over time, as additional data reveals cluster topology, the internal graph representation can split or merge clusters:
123
+
124
+ ```python
125
+ clusterer.fit(X)
126
+
127
+ # Labels assigned at arrival time (online mode)
128
+ online_labels = clusterer.online_labels_
129
+
130
+ # Revised cluster assignments reflecting subsequent splits and merges
131
+ final_labels = clusterer.final_labels_
132
+ ```
133
+
134
+ ### 4. Predefined Configurations
135
+
136
+ The package provides pre-tuned presets for common embedding domains:
137
+
138
+ ```python
139
+ from linkscluster import configs
140
+
141
+ # General high-dimensional embeddings (Tc=0.5, Ts=0.8, Tp=1.0)
142
+ clusterer = configs.default_links_clusterer
143
+
144
+ # 128-dim FaceNet CNN face embeddings (Tc=0.6, Ts=0.85, Tp=0.95)
145
+ clusterer = configs.facenet_clusterer
146
+
147
+ # 256-dim LSTM GE2E voice embeddings (Tc=0.55, Ts=0.8, Tp=0.9)
148
+ clusterer = configs.ge2e_voice_clusterer
149
+ ```
150
+
151
+ ---
152
+
153
+ ## How It Works
154
+
155
+ ### Two-Level Hierarchy
156
+
157
+ Links represents data using a two-level hierarchy:
158
+ - **Subclusters**: Indivisible nodes in a graph representing tight groups of vectors whose pairwise similarities exceed `Ts`.
159
+ - **Clusters**: Connected components in the graph of subclusters joined by edges.
160
+
161
+ This hierarchy scales with the number of *subclusters* rather than the number of vectors, enabling ultra-fast real-time operation.
162
+
163
+ ### Algorithm Steps
164
+
165
+ 1. **Cosine Similarity**: When a new vector `x` arrives, its cosine similarity to all active subcluster centroids is computed in a single vectorized matrix-vector multiplication:
166
+ ```
167
+ J = argmax_j (x · μ_j)
168
+ ```
169
+
170
+ 2. **Subcluster Addition vs. New Subcluster**:
171
+ - If `x · μ_J >= Ts`: `x` is added to subcluster `J`, and its centroid is updated.
172
+ - If `x · μ_J < Ts`: a new subcluster containing just `x` is created. It is linked to subcluster `J` if `x · μ_J >= s(kJ)` (or `s̃(kJ)` with anisotropy); otherwise, it starts a new cluster.
173
+
174
+ 3. **Subcluster Merging**: If updating subcluster `J` brings its centroid within `Ts` of an adjacent neighbor, the two subclusters merge recursively.
175
+
176
+ 4. **Edge Validity & Cluster Splitting**: Edges incident to affected nodes are checked against the threshold `s(ki, kj)` (or `s̃(ki, kj)`). If an edge falls below the threshold, it is removed. If the removal severs the cluster, Links attempts to re-join the two components via a valid partner node; if none exists, the cluster permanently splits.
177
+
178
+ ---
179
+
180
+ ## Hyperparameters & Tuning
181
+
182
+ Links has three intuitive hyperparameters:
183
+
184
+ | Parameter | Symbol | Range | Description |
185
+ | :--- | :--- | :--- | :--- |
186
+ | `cluster_similarity_threshold` (or `tc`) | `Tc = cos(θc)` | `(0, 1)` | Proximity threshold for vectors belonging to the same cluster. |
187
+ | `subcluster_similarity_threshold` (or `ts`) | `Ts` | `(0, 1)` | Threshold for grouping vectors into tight subclusters (`Ts >= Tc`). |
188
+ | `pair_similarity_maximum` (or `tp`) | `Tp` | `(Tc^2, 1]` | Asymptotic similarity ceiling accounting for intra-cluster correlation and anisotropy. Default is `1.0` (isotropic). |
189
+
190
+ ### Accuracy Evaluation
191
+
192
+ Clustering accuracy can be computed using the Hungarian algorithm bijection as described in Section 3.6 of the paper:
193
+
194
+ ```python
195
+ from linkscluster import compute_accuracy
196
+
197
+ acc = compute_accuracy(ground_truth_labels, predicted_labels)
198
+ print(f"Hungarian Clustering Accuracy: {acc * 100:.2f}%")
199
+ ```
200
+
201
+ ---
202
+
203
+ ## Performance & Efficiency
204
+
205
+ Links is designed to be **ultra fast and efficient**:
206
+ - **Vectorized Distance Calculations**: Subcluster centroids are kept in contiguous memory for BLAS level-2 matrix-vector dot products (`_centroids @ x`), bypassing Python loop overhead.
207
+ - **O(1) Dynamic Subcluster Management**: Subcluster additions and deletions (merging) utilize swap-and-pop in the contiguous centroid matrix.
208
+ - **High Throughput**: Capable of clustering **>50,000 - 100,000 vectors per second** on standard CPU hardware.
209
+
210
+ ---
211
+
212
+ ## Running Tests
213
+
214
+ Run the test suite with coverage:
215
+
216
+ ```bash
217
+ bash run_tests.sh
218
+ ```
219
+
220
+ Or run directly with `unittest`:
221
+
222
+ ```bash
223
+ python3 -m unittest discover -s tests -p "*_test.py"
224
+ ```
225
+
226
+ Check code style:
227
+
228
+ ```bash
229
+ flake8 --indent-size 2 --max-line-length 80 linkscluster tests
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Citations
235
+
236
+ If you use Links in your research, please cite:
237
+
238
+ ```bibtex
239
+ @inproceedings{mansfield2018links,
240
+ title={Links: A high-dimensional online clustering method},
241
+ author={Mansfield, Philip Andrew and Wang, Quan and Downey, Carlton and Wan, Li and Moreno, Ignacio Lopez},
242
+ booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
243
+ pages={2626--2630},
244
+ year={2018},
245
+ organization={IEEE}
246
+ }
247
+
248
+ @inproceedings{wang2018speaker,
249
+ title={Speaker diarization with LSTM},
250
+ author={Wang, Quan and Downey, Carlton and Wan, Li and Mansfield, Philip Andrew and Moreno, Ignacio Lopez},
251
+ booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
252
+ pages={5239--5243},
253
+ year={2018},
254
+ organization={IEEE}
255
+ }
256
+ ```
@@ -0,0 +1,231 @@
1
+ # Links: A High-Dimensional Online Clustering Method
2
+ [![Python application](https://github.com/wq2012/LinksCluster/workflows/Python%20application/badge.svg)](https://github.com/wq2012/LinksCluster/actions)
3
+ [![PyPI Version](https://img.shields.io/pypi/v/linkscluster.svg)](https://pypi.python.org/pypi/linkscluster)
4
+ [![Python Versions](https://img.shields.io/pypi/pyversions/linkscluster.svg)](https://pypi.org/project/linkscluster)
5
+ [![Downloads](https://static.pepy.tech/badge/linkscluster)](https://www.pepy.tech/projects/linkscluster)
6
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
+
8
+ Python implementation of the **Links** high-dimensional online clustering algorithm, designed for unit vectors on the hypersphere S^(N-1).
9
+
10
+ ## Overview
11
+
12
+ Links is an online clustering algorithm designed to cluster high-dimensional unit vectors efficiently in real time as data streams in. Unlike traditional batch clustering algorithms (such as [SpectralCluster](https://github.com/wq2012/SpectralCluster) or k-means) that require concurrent access to all data points, Links assigns each new datum to a cluster immediately upon arrival with no knowledge of future vectors and no backtracking.
13
+
14
+ ---
15
+
16
+ ## Disclaimer
17
+
18
+ **This is not an official Google product.**
19
+
20
+ ---
21
+
22
+ ## Installation
23
+
24
+ Install the package from PyPI:
25
+
26
+ ```bash
27
+ pip3 install linkscluster
28
+ ```
29
+
30
+ Or install from source:
31
+
32
+ ```bash
33
+ git clone https://github.com/wq2012/LinksCluster.git
34
+ cd LinksCluster
35
+ pip3 install .
36
+ ```
37
+
38
+ ---
39
+
40
+ ## Quick Start
41
+
42
+ ### 1. Standard scikit-learn API
43
+
44
+ `LinksClusterer` follows the standard scikit-learn estimator interface (`fit`, `predict`, `fit_predict`, `partial_fit`):
45
+
46
+ ```python
47
+ import numpy as np
48
+ from linkscluster import LinksClusterer
49
+
50
+ # Create synthetic unit embeddings (n_samples, n_features)
51
+ X = np.random.randn(500, 128)
52
+
53
+ # Initialize the clusterer
54
+ clusterer = LinksClusterer(
55
+ cluster_similarity_threshold=0.6, # Tc
56
+ subcluster_similarity_threshold=0.85, # Ts
57
+ pair_similarity_maximum=0.95, # Tp
58
+ )
59
+
60
+ # Fit and return cluster labels
61
+ labels = clusterer.fit_predict(X)
62
+ print(f"Number of clusters found: {clusterer.n_clusters_}")
63
+ print(f"Cluster labels: {labels}")
64
+ ```
65
+
66
+ ### 2. Online Streaming API
67
+
68
+ For real-time streaming applications (e.g. processing incoming audio frames or video embeddings datum-by-datum):
69
+
70
+ ```python
71
+ from linkscluster import LinksClusterer
72
+
73
+ clusterer = LinksClusterer(tc=0.6, ts=0.85, tp=0.95)
74
+
75
+ # Process vectors as they arrive in real time
76
+ for x in embedding_stream:
77
+ # Returns integer cluster ID immediately with zero backtracking
78
+ cluster_id = clusterer.predict_next(x)
79
+ print(f"Received vector assigned to cluster: {cluster_id}")
80
+ ```
81
+
82
+ You can also use Python generators via `predict_stream`:
83
+
84
+ ```python
85
+ for cluster_id in clusterer.predict_stream(embedding_stream):
86
+ handle_cluster_id(cluster_id)
87
+ ```
88
+
89
+ Or batch incremental updates via `partial_fit`:
90
+
91
+ ```python
92
+ clusterer.partial_fit(mini_batch)
93
+ ```
94
+
95
+ ### 3. Online Labels vs. Final Labels
96
+
97
+ In Links, each vector is assigned a cluster ID upon arrival. Over time, as additional data reveals cluster topology, the internal graph representation can split or merge clusters:
98
+
99
+ ```python
100
+ clusterer.fit(X)
101
+
102
+ # Labels assigned at arrival time (online mode)
103
+ online_labels = clusterer.online_labels_
104
+
105
+ # Revised cluster assignments reflecting subsequent splits and merges
106
+ final_labels = clusterer.final_labels_
107
+ ```
108
+
109
+ ### 4. Predefined Configurations
110
+
111
+ The package provides pre-tuned presets for common embedding domains:
112
+
113
+ ```python
114
+ from linkscluster import configs
115
+
116
+ # General high-dimensional embeddings (Tc=0.5, Ts=0.8, Tp=1.0)
117
+ clusterer = configs.default_links_clusterer
118
+
119
+ # 128-dim FaceNet CNN face embeddings (Tc=0.6, Ts=0.85, Tp=0.95)
120
+ clusterer = configs.facenet_clusterer
121
+
122
+ # 256-dim LSTM GE2E voice embeddings (Tc=0.55, Ts=0.8, Tp=0.9)
123
+ clusterer = configs.ge2e_voice_clusterer
124
+ ```
125
+
126
+ ---
127
+
128
+ ## How It Works
129
+
130
+ ### Two-Level Hierarchy
131
+
132
+ Links represents data using a two-level hierarchy:
133
+ - **Subclusters**: Indivisible nodes in a graph representing tight groups of vectors whose pairwise similarities exceed `Ts`.
134
+ - **Clusters**: Connected components in the graph of subclusters joined by edges.
135
+
136
+ This hierarchy scales with the number of *subclusters* rather than the number of vectors, enabling ultra-fast real-time operation.
137
+
138
+ ### Algorithm Steps
139
+
140
+ 1. **Cosine Similarity**: When a new vector `x` arrives, its cosine similarity to all active subcluster centroids is computed in a single vectorized matrix-vector multiplication:
141
+ ```
142
+ J = argmax_j (x · μ_j)
143
+ ```
144
+
145
+ 2. **Subcluster Addition vs. New Subcluster**:
146
+ - If `x · μ_J >= Ts`: `x` is added to subcluster `J`, and its centroid is updated.
147
+ - If `x · μ_J < Ts`: a new subcluster containing just `x` is created. It is linked to subcluster `J` if `x · μ_J >= s(kJ)` (or `s̃(kJ)` with anisotropy); otherwise, it starts a new cluster.
148
+
149
+ 3. **Subcluster Merging**: If updating subcluster `J` brings its centroid within `Ts` of an adjacent neighbor, the two subclusters merge recursively.
150
+
151
+ 4. **Edge Validity & Cluster Splitting**: Edges incident to affected nodes are checked against the threshold `s(ki, kj)` (or `s̃(ki, kj)`). If an edge falls below the threshold, it is removed. If the removal severs the cluster, Links attempts to re-join the two components via a valid partner node; if none exists, the cluster permanently splits.
152
+
153
+ ---
154
+
155
+ ## Hyperparameters & Tuning
156
+
157
+ Links has three intuitive hyperparameters:
158
+
159
+ | Parameter | Symbol | Range | Description |
160
+ | :--- | :--- | :--- | :--- |
161
+ | `cluster_similarity_threshold` (or `tc`) | `Tc = cos(θc)` | `(0, 1)` | Proximity threshold for vectors belonging to the same cluster. |
162
+ | `subcluster_similarity_threshold` (or `ts`) | `Ts` | `(0, 1)` | Threshold for grouping vectors into tight subclusters (`Ts >= Tc`). |
163
+ | `pair_similarity_maximum` (or `tp`) | `Tp` | `(Tc^2, 1]` | Asymptotic similarity ceiling accounting for intra-cluster correlation and anisotropy. Default is `1.0` (isotropic). |
164
+
165
+ ### Accuracy Evaluation
166
+
167
+ Clustering accuracy can be computed using the Hungarian algorithm bijection as described in Section 3.6 of the paper:
168
+
169
+ ```python
170
+ from linkscluster import compute_accuracy
171
+
172
+ acc = compute_accuracy(ground_truth_labels, predicted_labels)
173
+ print(f"Hungarian Clustering Accuracy: {acc * 100:.2f}%")
174
+ ```
175
+
176
+ ---
177
+
178
+ ## Performance & Efficiency
179
+
180
+ Links is designed to be **ultra fast and efficient**:
181
+ - **Vectorized Distance Calculations**: Subcluster centroids are kept in contiguous memory for BLAS level-2 matrix-vector dot products (`_centroids @ x`), bypassing Python loop overhead.
182
+ - **O(1) Dynamic Subcluster Management**: Subcluster additions and deletions (merging) utilize swap-and-pop in the contiguous centroid matrix.
183
+ - **High Throughput**: Capable of clustering **>50,000 - 100,000 vectors per second** on standard CPU hardware.
184
+
185
+ ---
186
+
187
+ ## Running Tests
188
+
189
+ Run the test suite with coverage:
190
+
191
+ ```bash
192
+ bash run_tests.sh
193
+ ```
194
+
195
+ Or run directly with `unittest`:
196
+
197
+ ```bash
198
+ python3 -m unittest discover -s tests -p "*_test.py"
199
+ ```
200
+
201
+ Check code style:
202
+
203
+ ```bash
204
+ flake8 --indent-size 2 --max-line-length 80 linkscluster tests
205
+ ```
206
+
207
+ ---
208
+
209
+ ## Citations
210
+
211
+ If you use Links in your research, please cite:
212
+
213
+ ```bibtex
214
+ @inproceedings{mansfield2018links,
215
+ title={Links: A high-dimensional online clustering method},
216
+ author={Mansfield, Philip Andrew and Wang, Quan and Downey, Carlton and Wan, Li and Moreno, Ignacio Lopez},
217
+ booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
218
+ pages={2626--2630},
219
+ year={2018},
220
+ organization={IEEE}
221
+ }
222
+
223
+ @inproceedings{wang2018speaker,
224
+ title={Speaker diarization with LSTM},
225
+ author={Wang, Quan and Downey, Carlton and Wan, Li and Mansfield, Philip Andrew and Moreno, Ignacio Lopez},
226
+ booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
227
+ pages={5239--5243},
228
+ year={2018},
229
+ organization={IEEE}
230
+ }
231
+ ```
@@ -0,0 +1,26 @@
1
+ """__init__ file for linkscluster."""
2
+
3
+ from linkscluster import configs
4
+ from linkscluster import graph
5
+ from linkscluster import links_clusterer
6
+ from linkscluster import subcluster
7
+ from linkscluster import utils
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ LinksClusterer = links_clusterer.LinksClusterer
12
+ Subcluster = subcluster.Subcluster
13
+ SubclusterGraph = graph.SubclusterGraph
14
+
15
+ single_threshold = utils.single_threshold
16
+ multi_threshold = utils.multi_threshold
17
+ anisotropic_threshold = utils.anisotropic_threshold
18
+ s = utils.s
19
+ s_tilde = utils.s_tilde
20
+ compute_accuracy = utils.compute_accuracy
21
+ enforce_ordered_labels = utils.enforce_ordered_labels
22
+ l2_normalize = utils.l2_normalize
23
+
24
+ default_links_clusterer = configs.default_links_clusterer
25
+ facenet_clusterer = configs.facenet_clusterer
26
+ ge2e_voice_clusterer = configs.ge2e_voice_clusterer