pbhc 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.
- pbhc-0.1.0/LICENSE +21 -0
- pbhc-0.1.0/PKG-INFO +94 -0
- pbhc-0.1.0/README.md +49 -0
- pbhc-0.1.0/pbhc/__init__.py +3 -0
- pbhc-0.1.0/pbhc/bhc.py +129 -0
- pbhc-0.1.0/pbhc/bhc_test.py +90 -0
- pbhc-0.1.0/pbhc.egg-info/PKG-INFO +94 -0
- pbhc-0.1.0/pbhc.egg-info/SOURCES.txt +11 -0
- pbhc-0.1.0/pbhc.egg-info/dependency_links.txt +1 -0
- pbhc-0.1.0/pbhc.egg-info/requires.txt +5 -0
- pbhc-0.1.0/pbhc.egg-info/top_level.txt +1 -0
- pbhc-0.1.0/pyproject.toml +34 -0
- pbhc-0.1.0/setup.cfg +4 -0
pbhc-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Albert Alonso
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pbhc-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pbhc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal parallel Bayesian hierarchical clustering on graphs in JAX.
|
|
5
|
+
Author-email: Albert Alonso <alonfnt@pm.me>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Albert Alonso
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/alonfnt/pbhc
|
|
29
|
+
Project-URL: Documentation, https://github.com/alonfnt/pbhc
|
|
30
|
+
Project-URL: Source, https://github.com/alonfnt/pbhc
|
|
31
|
+
Project-URL: Bug Tracker, https://github.com/alonfnt/pbhc/issues
|
|
32
|
+
Keywords: jax,clustering,bayesian,hierarchical-clustering,graph
|
|
33
|
+
Classifier: Development Status :: 3 - Alpha
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Requires-Python: >=3.10
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
License-File: LICENSE
|
|
40
|
+
Requires-Dist: jax
|
|
41
|
+
Provides-Extra: dev
|
|
42
|
+
Requires-Dist: pytest; extra == "dev"
|
|
43
|
+
Requires-Dist: scipy; extra == "dev"
|
|
44
|
+
Dynamic: license-file
|
|
45
|
+
|
|
46
|
+
[](https://github.com/alonfnt/pbhc/actions/workflows/pytest.yml)
|
|
47
|
+
[](https://pypi.org/project/pbhc/)
|
|
48
|
+
|
|
49
|
+
`pbhc` is a minimal parallel Bayesian hierarchical clustering (BHC) implementation in [JAX](https://github.com/jax-ml/jax) that runs on GPU/TPU/CPU.
|
|
50
|
+
Clustering is constrained to a graph: only clusters joined by an edge may merge, so on a pixel grid every cluster is spatially contiguous.
|
|
51
|
+
Instead of BHC's one-merge-at-a-time greedy loop, every cluster merges with its most probable neighbour in the same round (Borůvka-style), so the number of rounds grows roughly with the log of the number of points.
|
|
52
|
+
|
|
53
|
+
Each cluster follows a diagonal Normal-Normal model, `x ~ N(mu, sigma2)`, `mu ~ N(0, tau2)`, with a Dirichlet process prior of concentration `alpha` ([Heller & Ghahramani, 2005](https://doi.org/10.1145/1102351.1102389)).
|
|
54
|
+
Merges of several children at once use the product over children of [Bayesian rose trees](https://arxiv.org/abs/1203.3468), and merging stops when no merge has posterior probability above `threshold` (0.5 by default).
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
```python
|
|
58
|
+
import jax
|
|
59
|
+
import jax.numpy as jnp
|
|
60
|
+
import pbhc
|
|
61
|
+
|
|
62
|
+
jax.config.update("jax_enable_x64", True) # recommended for large inputs
|
|
63
|
+
|
|
64
|
+
# 100 points in a line: the first 50 around 0, the last 50 around 10
|
|
65
|
+
X = jax.random.normal(jax.random.key(0), (100, 3)).at[50:].add(10)
|
|
66
|
+
|
|
67
|
+
# edges between consecutive points (only connected clusters can merge)
|
|
68
|
+
i, j = jnp.arange(99), jnp.arange(1, 100)
|
|
69
|
+
|
|
70
|
+
# sigma2: spread inside a cluster, from differences between neighbours
|
|
71
|
+
# tau2: spread between clusters, from the variance of the whole data
|
|
72
|
+
sigma2 = 0.5 * jnp.mean((X[i] - X[j]) ** 2)
|
|
73
|
+
tau2 = jnp.var(X)
|
|
74
|
+
|
|
75
|
+
state = pbhc.fit(X, i, j, sigma2=sigma2, tau2=tau2)
|
|
76
|
+
print(state.labels) # [0 0 ... 0 1 1 ... 1]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Installation
|
|
80
|
+
`pbhc` can be installed from PyPI via `pip`
|
|
81
|
+
```
|
|
82
|
+
pip install pbhc
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Citation
|
|
86
|
+
If you use `pbhc` in your research and need to reference it, please cite it as follows:
|
|
87
|
+
```
|
|
88
|
+
@software{alonso_pbhc,
|
|
89
|
+
author = {Alonso, Albert},
|
|
90
|
+
title = {pbhc: Minimal Parallel Bayesian Hierarchical Clustering in JAX},
|
|
91
|
+
url = {https://github.com/alonfnt/pbhc},
|
|
92
|
+
version = {0.1.0}
|
|
93
|
+
}
|
|
94
|
+
```
|
pbhc-0.1.0/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[](https://github.com/alonfnt/pbhc/actions/workflows/pytest.yml)
|
|
2
|
+
[](https://pypi.org/project/pbhc/)
|
|
3
|
+
|
|
4
|
+
`pbhc` is a minimal parallel Bayesian hierarchical clustering (BHC) implementation in [JAX](https://github.com/jax-ml/jax) that runs on GPU/TPU/CPU.
|
|
5
|
+
Clustering is constrained to a graph: only clusters joined by an edge may merge, so on a pixel grid every cluster is spatially contiguous.
|
|
6
|
+
Instead of BHC's one-merge-at-a-time greedy loop, every cluster merges with its most probable neighbour in the same round (Borůvka-style), so the number of rounds grows roughly with the log of the number of points.
|
|
7
|
+
|
|
8
|
+
Each cluster follows a diagonal Normal-Normal model, `x ~ N(mu, sigma2)`, `mu ~ N(0, tau2)`, with a Dirichlet process prior of concentration `alpha` ([Heller & Ghahramani, 2005](https://doi.org/10.1145/1102351.1102389)).
|
|
9
|
+
Merges of several children at once use the product over children of [Bayesian rose trees](https://arxiv.org/abs/1203.3468), and merging stops when no merge has posterior probability above `threshold` (0.5 by default).
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
```python
|
|
13
|
+
import jax
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import pbhc
|
|
16
|
+
|
|
17
|
+
jax.config.update("jax_enable_x64", True) # recommended for large inputs
|
|
18
|
+
|
|
19
|
+
# 100 points in a line: the first 50 around 0, the last 50 around 10
|
|
20
|
+
X = jax.random.normal(jax.random.key(0), (100, 3)).at[50:].add(10)
|
|
21
|
+
|
|
22
|
+
# edges between consecutive points (only connected clusters can merge)
|
|
23
|
+
i, j = jnp.arange(99), jnp.arange(1, 100)
|
|
24
|
+
|
|
25
|
+
# sigma2: spread inside a cluster, from differences between neighbours
|
|
26
|
+
# tau2: spread between clusters, from the variance of the whole data
|
|
27
|
+
sigma2 = 0.5 * jnp.mean((X[i] - X[j]) ** 2)
|
|
28
|
+
tau2 = jnp.var(X)
|
|
29
|
+
|
|
30
|
+
state = pbhc.fit(X, i, j, sigma2=sigma2, tau2=tau2)
|
|
31
|
+
print(state.labels) # [0 0 ... 0 1 1 ... 1]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
`pbhc` can be installed from PyPI via `pip`
|
|
36
|
+
```
|
|
37
|
+
pip install pbhc
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Citation
|
|
41
|
+
If you use `pbhc` in your research and need to reference it, please cite it as follows:
|
|
42
|
+
```
|
|
43
|
+
@software{alonso_pbhc,
|
|
44
|
+
author = {Alonso, Albert},
|
|
45
|
+
title = {pbhc: Minimal Parallel Bayesian Hierarchical Clustering in JAX},
|
|
46
|
+
url = {https://github.com/alonfnt/pbhc},
|
|
47
|
+
version = {0.1.0}
|
|
48
|
+
}
|
|
49
|
+
```
|
pbhc-0.1.0/pbhc/bhc.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from typing import NamedTuple
|
|
2
|
+
|
|
3
|
+
import jax
|
|
4
|
+
import jax.numpy as jnp
|
|
5
|
+
from jax.scipy.special import gammaln
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PBHCState(NamedTuple):
|
|
9
|
+
"""Result of fit.
|
|
10
|
+
|
|
11
|
+
Attributes:
|
|
12
|
+
labels: Cluster of each point, 0..k-1.
|
|
13
|
+
size: Size of the point's cluster.
|
|
14
|
+
log_d: BHC's log d of the point's cluster.
|
|
15
|
+
log_p: Log evidence log p(D | T) of the point's cluster.
|
|
16
|
+
rounds: Number of merge rounds.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
labels: jax.Array
|
|
20
|
+
size: jax.Array
|
|
21
|
+
log_d: jax.Array
|
|
22
|
+
log_p: jax.Array
|
|
23
|
+
rounds: jax.Array
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def log_marginal(n: jax.Array, s: jax.Array, ss: jax.Array, sigma2, tau2) -> jax.Array:
|
|
27
|
+
"""
|
|
28
|
+
Log p(D | H1) of each cluster, with x ~ N(mu, sigma2) and mu ~ N(0, tau2).
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
n: Points per cluster, shape (k,).
|
|
32
|
+
s: Sum of the points, shape (k, n_features).
|
|
33
|
+
ss: Sum of squares of the points, shape (k, n_features).
|
|
34
|
+
sigma2: Variance of points around their cluster mean.
|
|
35
|
+
tau2: Variance of the cluster means.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Log marginal likelihood per cluster, shape (k,).
|
|
39
|
+
"""
|
|
40
|
+
n = n[:, None]
|
|
41
|
+
return jnp.sum(-0.5 * n * jnp.log(2 * jnp.pi * sigma2) - 0.5 * jnp.log1p(n * tau2 / sigma2)
|
|
42
|
+
- (ss - tau2 * s**2 / (sigma2 + n * tau2)) / (2 * sigma2), axis=1)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _join(m, s, ss, log_d_children, log_p_children, sigma2, tau2, log_alpha, beta):
|
|
46
|
+
"""Merge children into one node. Returns log d, log p(D | T) and the merge log-odds."""
|
|
47
|
+
log_d = jnp.logaddexp(log_alpha + gammaln(m), log_d_children)
|
|
48
|
+
log_pi = log_alpha + gammaln(m) - log_d
|
|
49
|
+
h1 = beta * log_marginal(m, s, ss, sigma2, tau2)
|
|
50
|
+
rest = log_d_children - log_d + log_p_children # log(1 - pi) = log(prod d_children / d), exact
|
|
51
|
+
return log_d, jnp.logaddexp(log_pi + h1, rest), log_pi + h1 - rest
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _step(state, sigma2, tau2, log_alpha, beta, min_log_odds):
|
|
55
|
+
"""One round: each cluster merges with its best neighbour if r > threshold."""
|
|
56
|
+
size, S, SS, log_d, log_p, ei, ej, label = state
|
|
57
|
+
n, ids = len(size), jnp.arange(len(size))
|
|
58
|
+
hyper = (sigma2, tau2, log_alpha, beta)
|
|
59
|
+
_, _, lo = _join(size[ei] + size[ej], S[ei] + S[ej], SS[ei] + SS[ej],
|
|
60
|
+
log_d[ei] + log_d[ej], log_p[ei] + log_p[ej], *hyper)
|
|
61
|
+
lo = jnp.where(ei != ej, lo, -jnp.inf)
|
|
62
|
+
|
|
63
|
+
# each cluster points to its best neighbour if r > threshold; 2-cycles keep the smaller id as root
|
|
64
|
+
ends, other = jnp.concatenate([ei, ej]), jnp.concatenate([ej, ei])
|
|
65
|
+
lo2 = jnp.concatenate([lo, lo])
|
|
66
|
+
best = jax.ops.segment_max(lo2, ends, n)
|
|
67
|
+
target = jax.ops.segment_min(jnp.where(lo2 == best[ends], other, n), ends, n)
|
|
68
|
+
target = jnp.where((best > min_log_odds) & (target < n), target, ids)
|
|
69
|
+
target = jnp.where((target[target] == ids) & (ids < target), ids, target)
|
|
70
|
+
root = jax.lax.fori_loop(0, n.bit_length(), lambda _, r: r[r], target) # pointer jumping
|
|
71
|
+
|
|
72
|
+
# merge every group that shares a root: sums of statistics, product over children in _join()
|
|
73
|
+
seg = lambda v: jax.ops.segment_sum(v, root, n) # noqa: E731
|
|
74
|
+
kids = seg(jnp.ones_like(size))
|
|
75
|
+
m, s, ss = seg(size), seg(S), seg(SS)
|
|
76
|
+
new_d, new_p, _ = _join(m, s, ss, seg(log_d), seg(log_p), *hyper)
|
|
77
|
+
grouped = kids > 1
|
|
78
|
+
size, S, SS = jnp.where(grouped, m, size), jnp.where(grouped[:, None], s, S), jnp.where(grouped[:, None], ss, SS)
|
|
79
|
+
log_d, log_p = jnp.where(grouped, new_d, log_d), jnp.where(grouped, new_p, log_p)
|
|
80
|
+
ei, ej, label = root[ei], root[ej], root[label]
|
|
81
|
+
return (size, S, SS, log_d, log_p, ei, ej, label), grouped.any()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@jax.jit
|
|
85
|
+
def fit(x: jax.Array, i: jax.Array, j: jax.Array, sigma2, tau2, alpha: float = 1.0,
|
|
86
|
+
beta: float = 1.0, threshold: float = 0.5) -> PBHCState:
|
|
87
|
+
"""
|
|
88
|
+
Bayesian hierarchical clustering of the rows of x, where only clusters joined by an edge can merge.
|
|
89
|
+
|
|
90
|
+
Each round, every cluster merges with its best neighbour if the merge probability is above threshold.
|
|
91
|
+
Enable float64 for large inputs.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
x: Data, shape (n_samples, n_features).
|
|
95
|
+
i: Edge sources, shape (n_edges,).
|
|
96
|
+
j: Edge targets, shape (n_edges,).
|
|
97
|
+
sigma2: Variance of points around their cluster mean.
|
|
98
|
+
tau2: Variance of the cluster means.
|
|
99
|
+
alpha: Dirichlet process concentration. Larger gives more clusters.
|
|
100
|
+
beta: Likelihood temperature. Smaller gives larger clusters.
|
|
101
|
+
threshold: Minimum merge probability.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
The fitted PBHCState.
|
|
105
|
+
|
|
106
|
+
Each new input size compiles again. To reuse one compile across sizes, pad x with extra rows and the
|
|
107
|
+
edges with self-loops (i == j), which never merge.
|
|
108
|
+
"""
|
|
109
|
+
x = jnp.asarray(x, float)
|
|
110
|
+
n = len(x)
|
|
111
|
+
size = jnp.ones(n, x.dtype)
|
|
112
|
+
log_d = jnp.full(n, jnp.log(alpha), x.dtype)
|
|
113
|
+
log_p = beta * log_marginal(size, x, x**2, sigma2, tau2)
|
|
114
|
+
state = (size, x, x**2, log_d, log_p, jnp.asarray(i, int), jnp.asarray(j, int), jnp.arange(n))
|
|
115
|
+
hyper = (sigma2, tau2, jnp.log(alpha), beta, jnp.log(threshold) - jnp.log1p(-threshold))
|
|
116
|
+
|
|
117
|
+
def body(carry):
|
|
118
|
+
state, _, rounds = carry
|
|
119
|
+
state, merged = _step(state, *hyper)
|
|
120
|
+
return state, merged, rounds + 1
|
|
121
|
+
|
|
122
|
+
state, _, rounds = jax.lax.while_loop(lambda c: c[1], body, (state, True, 0))
|
|
123
|
+
|
|
124
|
+
root = state[7]
|
|
125
|
+
is_root = jnp.zeros(n, int).at[root].set(1)
|
|
126
|
+
labels = (jnp.cumsum(is_root) - 1)[root]
|
|
127
|
+
return PBHCState(labels=labels, size=state[0][root], log_d=state[3][root], log_p=state[4][root],
|
|
128
|
+
rounds=rounds)
|
|
129
|
+
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import jax
|
|
2
|
+
import jax.numpy as jnp
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
jax.config.update("jax_enable_x64", True)
|
|
7
|
+
|
|
8
|
+
from pbhc import fit, log_marginal # noqa: E402
|
|
9
|
+
|
|
10
|
+
KEY = jax.random.key(42)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def path(n):
|
|
14
|
+
return jnp.arange(n - 1), jnp.arange(1, n)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def blobs(n, d=3, gap=10.0):
|
|
18
|
+
x = jax.random.normal(KEY, (2 * n, d))
|
|
19
|
+
return x.at[n:].add(gap)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_log_marginal_matches_scipy():
|
|
23
|
+
from scipy.stats import multivariate_normal
|
|
24
|
+
sigma2, tau2, n = 0.5, 2.0, 7
|
|
25
|
+
x = jax.random.normal(KEY, (n, 3))
|
|
26
|
+
lm = log_marginal(jnp.array([n]), x.sum(0)[None], (x**2).sum(0)[None], sigma2, tau2)[0]
|
|
27
|
+
cov = sigma2 * np.eye(n) + tau2 * np.ones((n, n))
|
|
28
|
+
ref = sum(multivariate_normal(np.zeros(n), cov).logpdf(np.asarray(x[:, k])) for k in range(3))
|
|
29
|
+
assert jnp.allclose(lm, ref, rtol=1e-10)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_two_blobs_on_path():
|
|
33
|
+
x = blobs(50)
|
|
34
|
+
state = fit(x, *path(100), sigma2=1.0, tau2=100.0)
|
|
35
|
+
labels = np.asarray(state.labels)
|
|
36
|
+
assert len(np.unique(labels)) == 2
|
|
37
|
+
assert np.all(labels[:50] == labels[0]) and np.all(labels[50:] == labels[50])
|
|
38
|
+
assert np.all(np.asarray(state.size) == 50)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_no_edges_no_merges():
|
|
42
|
+
x = jax.random.normal(KEY, (20, 2))
|
|
43
|
+
state = fit(x, jnp.zeros(0, int), jnp.zeros(0, int), sigma2=1.0, tau2=1.0)
|
|
44
|
+
assert len(np.unique(state.labels)) == 20
|
|
45
|
+
assert state.rounds == 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_disconnected_components_never_merge():
|
|
49
|
+
x = jnp.zeros((20, 2))
|
|
50
|
+
i, j = path(10)
|
|
51
|
+
state = fit(x, jnp.concatenate([i, i + 10]), jnp.concatenate([j, j + 10]), sigma2=1.0, tau2=1.0)
|
|
52
|
+
labels = np.asarray(state.labels)
|
|
53
|
+
assert len(np.unique(labels)) == 2
|
|
54
|
+
assert labels[0] != labels[10]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.mark.parametrize("n", [5, 17, 100, 333])
|
|
58
|
+
def test_labels_contiguous(n):
|
|
59
|
+
x = jax.random.normal(KEY, (n, 4)) * 3
|
|
60
|
+
state = fit(x, *path(n), sigma2=1.0, tau2=4.0)
|
|
61
|
+
labels = np.asarray(state.labels)
|
|
62
|
+
assert labels.shape == (n,)
|
|
63
|
+
assert set(np.unique(labels)) == set(range(labels.max() + 1))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_edge_order_invariant():
|
|
67
|
+
x = blobs(30)
|
|
68
|
+
i, j = path(60)
|
|
69
|
+
a = fit(x, i, j, sigma2=1.0, tau2=100.0).labels
|
|
70
|
+
b = fit(x, j[::-1], i[::-1], sigma2=1.0, tau2=100.0).labels
|
|
71
|
+
assert jnp.array_equal(a, b)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_alpha_controls_number_of_clusters():
|
|
75
|
+
x = jax.random.normal(KEY, (200, 2)) * 2
|
|
76
|
+
k = [len(np.unique(fit(x, *path(200), sigma2=1.0, tau2=4.0, alpha=a).labels)) for a in (1e-3, 1e3)]
|
|
77
|
+
assert k[0] <= k[1]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_threshold_controls_number_of_clusters():
|
|
81
|
+
x = jax.random.normal(KEY, (200, 2)) * 2
|
|
82
|
+
k = [len(np.unique(fit(x, *path(200), sigma2=1.0, tau2=4.0, threshold=t).labels)) for t in (0.01, 0.99)]
|
|
83
|
+
assert k[0] <= k[1]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_jit():
|
|
87
|
+
x = blobs(20)
|
|
88
|
+
a = fit(x, *path(40), sigma2=1.0, tau2=100.0)
|
|
89
|
+
b = jax.jit(fit)(x, *path(40), sigma2=1.0, tau2=100.0, alpha=1.0)
|
|
90
|
+
assert jnp.array_equal(a.labels, b.labels)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pbhc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal parallel Bayesian hierarchical clustering on graphs in JAX.
|
|
5
|
+
Author-email: Albert Alonso <alonfnt@pm.me>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Albert Alonso
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/alonfnt/pbhc
|
|
29
|
+
Project-URL: Documentation, https://github.com/alonfnt/pbhc
|
|
30
|
+
Project-URL: Source, https://github.com/alonfnt/pbhc
|
|
31
|
+
Project-URL: Bug Tracker, https://github.com/alonfnt/pbhc/issues
|
|
32
|
+
Keywords: jax,clustering,bayesian,hierarchical-clustering,graph
|
|
33
|
+
Classifier: Development Status :: 3 - Alpha
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Requires-Python: >=3.10
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
License-File: LICENSE
|
|
40
|
+
Requires-Dist: jax
|
|
41
|
+
Provides-Extra: dev
|
|
42
|
+
Requires-Dist: pytest; extra == "dev"
|
|
43
|
+
Requires-Dist: scipy; extra == "dev"
|
|
44
|
+
Dynamic: license-file
|
|
45
|
+
|
|
46
|
+
[](https://github.com/alonfnt/pbhc/actions/workflows/pytest.yml)
|
|
47
|
+
[](https://pypi.org/project/pbhc/)
|
|
48
|
+
|
|
49
|
+
`pbhc` is a minimal parallel Bayesian hierarchical clustering (BHC) implementation in [JAX](https://github.com/jax-ml/jax) that runs on GPU/TPU/CPU.
|
|
50
|
+
Clustering is constrained to a graph: only clusters joined by an edge may merge, so on a pixel grid every cluster is spatially contiguous.
|
|
51
|
+
Instead of BHC's one-merge-at-a-time greedy loop, every cluster merges with its most probable neighbour in the same round (Borůvka-style), so the number of rounds grows roughly with the log of the number of points.
|
|
52
|
+
|
|
53
|
+
Each cluster follows a diagonal Normal-Normal model, `x ~ N(mu, sigma2)`, `mu ~ N(0, tau2)`, with a Dirichlet process prior of concentration `alpha` ([Heller & Ghahramani, 2005](https://doi.org/10.1145/1102351.1102389)).
|
|
54
|
+
Merges of several children at once use the product over children of [Bayesian rose trees](https://arxiv.org/abs/1203.3468), and merging stops when no merge has posterior probability above `threshold` (0.5 by default).
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
```python
|
|
58
|
+
import jax
|
|
59
|
+
import jax.numpy as jnp
|
|
60
|
+
import pbhc
|
|
61
|
+
|
|
62
|
+
jax.config.update("jax_enable_x64", True) # recommended for large inputs
|
|
63
|
+
|
|
64
|
+
# 100 points in a line: the first 50 around 0, the last 50 around 10
|
|
65
|
+
X = jax.random.normal(jax.random.key(0), (100, 3)).at[50:].add(10)
|
|
66
|
+
|
|
67
|
+
# edges between consecutive points (only connected clusters can merge)
|
|
68
|
+
i, j = jnp.arange(99), jnp.arange(1, 100)
|
|
69
|
+
|
|
70
|
+
# sigma2: spread inside a cluster, from differences between neighbours
|
|
71
|
+
# tau2: spread between clusters, from the variance of the whole data
|
|
72
|
+
sigma2 = 0.5 * jnp.mean((X[i] - X[j]) ** 2)
|
|
73
|
+
tau2 = jnp.var(X)
|
|
74
|
+
|
|
75
|
+
state = pbhc.fit(X, i, j, sigma2=sigma2, tau2=tau2)
|
|
76
|
+
print(state.labels) # [0 0 ... 0 1 1 ... 1]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Installation
|
|
80
|
+
`pbhc` can be installed from PyPI via `pip`
|
|
81
|
+
```
|
|
82
|
+
pip install pbhc
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Citation
|
|
86
|
+
If you use `pbhc` in your research and need to reference it, please cite it as follows:
|
|
87
|
+
```
|
|
88
|
+
@software{alonso_pbhc,
|
|
89
|
+
author = {Alonso, Albert},
|
|
90
|
+
title = {pbhc: Minimal Parallel Bayesian Hierarchical Clustering in JAX},
|
|
91
|
+
url = {https://github.com/alonfnt/pbhc},
|
|
92
|
+
version = {0.1.0}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pbhc
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools", "wheel", "jax"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pbhc"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Minimal parallel Bayesian hierarchical clustering on graphs in JAX."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [
|
|
12
|
+
{name = "Albert Alonso", email = "alonfnt@pm.me"},
|
|
13
|
+
]
|
|
14
|
+
license = {file = "LICENSE"}
|
|
15
|
+
keywords = ["jax", "clustering", "bayesian", "hierarchical-clustering", "graph"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
]
|
|
22
|
+
dependencies = ["jax",]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
dev = ["pytest", "scipy"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.dynamic]
|
|
28
|
+
version = {attr = "pbhc.__version__"}
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
"Homepage" = "https://github.com/alonfnt/pbhc"
|
|
32
|
+
"Documentation" = "https://github.com/alonfnt/pbhc"
|
|
33
|
+
"Source" = "https://github.com/alonfnt/pbhc"
|
|
34
|
+
"Bug Tracker" = "https://github.com/alonfnt/pbhc/issues"
|
pbhc-0.1.0/setup.cfg
ADDED