graphclust 1.0__py3-none-any.whl
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.
- graphclust/__init__.py +102 -0
- graphclust/_utils.py +86 -0
- graphclust/cluster.py +971 -0
- graphclust/data/__init__.py +1 -0
- graphclust/data/boxlinecircle.txt +7100 -0
- graphclust/datasets.py +173 -0
- graphclust/fuzzy.py +152 -0
- graphclust/graphs.py +311 -0
- graphclust/manifold.py +1135 -0
- graphclust/metrics.py +213 -0
- graphclust/plotting.py +185 -0
- graphclust/validity.py +184 -0
- graphclust/vat.py +71 -0
- graphclust/vq.py +707 -0
- graphclust-1.0.dist-info/METADATA +168 -0
- graphclust-1.0.dist-info/RECORD +18 -0
- graphclust-1.0.dist-info/WHEEL +4 -0
- graphclust-1.0.dist-info/licenses/LICENSE +21 -0
graphclust/cluster.py
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Graph-based clustering.
|
|
4
|
+
|
|
5
|
+
Tree-based methods
|
|
6
|
+
:class:`MSTClustering` (Zahn's inconsistent edges), :class:`HybridMSTGG`
|
|
7
|
+
(Vathy-Fogarassy, Feil and Abonyi: hypervolume splitting plus Gath--Geva)
|
|
8
|
+
and :class:`HDBSCANStar` (Campello, Moulavi and Sander: hierarchy of the
|
|
9
|
+
mutual reachability MST with cluster stability).
|
|
10
|
+
Neighborhood-based methods
|
|
11
|
+
:class:`JarvisPatrick`, :func:`fuzzy_neighborhood_similarity` and
|
|
12
|
+
:class:`FuzzyNeighborhoodClustering` (Vathy-Fogarassy, Kiss and Abonyi),
|
|
13
|
+
:class:`SharedNearestNeighborClustering` (Ertöz, Steinbach and Kumar) and
|
|
14
|
+
:class:`DensityPeaks` (Rodriguez and Laio).
|
|
15
|
+
Global graph methods
|
|
16
|
+
:class:`SpectralGraphClustering` (normalized cuts with self-tuning
|
|
17
|
+
affinities) and :class:`GraphCommunityClustering` (modularity communities
|
|
18
|
+
of a neighborhood graph: Louvain, Leiden, label propagation).
|
|
19
|
+
|
|
20
|
+
Every estimator follows scikit-learn: ``fit(X)`` sets ``labels_`` (``-1`` marks
|
|
21
|
+
noise where the method has such a notion) and ``fit_predict`` is available.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections import deque
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
from scipy.cluster.hierarchy import fcluster, linkage
|
|
30
|
+
from scipy.sparse import coo_matrix, csr_matrix
|
|
31
|
+
from scipy.sparse.csgraph import connected_components
|
|
32
|
+
from scipy.spatial.distance import squareform
|
|
33
|
+
from sklearn.base import BaseEstimator, ClusterMixin
|
|
34
|
+
from sklearn.cluster import KMeans
|
|
35
|
+
|
|
36
|
+
from ._utils import EPS, as_data, check_random_state, minmax_scale, pairwise_distances
|
|
37
|
+
from .fuzzy import GathGeva, labels_to_membership
|
|
38
|
+
from .graphs import edges_of, knn_indices, minimum_spanning_tree, shared_neighbor_counts, to_networkx
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"DensityPeaks",
|
|
42
|
+
"FuzzyNeighborhoodClustering",
|
|
43
|
+
"GraphCommunityClustering",
|
|
44
|
+
"HDBSCANStar",
|
|
45
|
+
"HybridMSTGG",
|
|
46
|
+
"JarvisPatrick",
|
|
47
|
+
"MSTClustering",
|
|
48
|
+
"SharedNearestNeighborClustering",
|
|
49
|
+
"SpectralGraphClustering",
|
|
50
|
+
"fuzzy_neighborhood_similarity",
|
|
51
|
+
"jaccard_knn_graph",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# =========================================================================== tree helpers
|
|
56
|
+
def _components(n, edges):
|
|
57
|
+
if len(edges) == 0:
|
|
58
|
+
return np.arange(n)
|
|
59
|
+
e = np.asarray(edges)
|
|
60
|
+
A = coo_matrix((np.ones(len(e)), (e[:, 0], e[:, 1])), shape=(n, n))
|
|
61
|
+
return connected_components(A, directed=False)[1]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _adjacency_lists(n, edges):
|
|
65
|
+
adj = [[] for _ in range(n)]
|
|
66
|
+
for idx, (a, b) in enumerate(edges):
|
|
67
|
+
adj[a].append((b, idx))
|
|
68
|
+
adj[b].append((a, idx))
|
|
69
|
+
return adj
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _nearby_mean(adj, weights, a, b, eid, depth):
|
|
73
|
+
"""Mean length of the tree edges within ``depth`` steps of edge (a, b), the edge itself excluded."""
|
|
74
|
+
seen = {eid}
|
|
75
|
+
vals = []
|
|
76
|
+
for start, block in ((a, b), (b, a)):
|
|
77
|
+
frontier = [start]
|
|
78
|
+
visited = {start, block}
|
|
79
|
+
for _ in range(depth):
|
|
80
|
+
nxt = []
|
|
81
|
+
for u in frontier:
|
|
82
|
+
for v, e in adj[u]:
|
|
83
|
+
if e in seen or v in visited:
|
|
84
|
+
continue
|
|
85
|
+
seen.add(e)
|
|
86
|
+
vals.append(weights[e])
|
|
87
|
+
visited.add(v)
|
|
88
|
+
nxt.append(v)
|
|
89
|
+
frontier = nxt
|
|
90
|
+
return float(np.mean(vals)) if vals else np.inf
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# =========================================================================== Zahn
|
|
94
|
+
class MSTClustering(ClusterMixin, BaseEstimator):
|
|
95
|
+
r"""Minimal spanning tree clustering with Zahn's inconsistent-edge criteria.
|
|
96
|
+
|
|
97
|
+
The Euclidean MST of the data is built and edges are removed in order of
|
|
98
|
+
decreasing length while they are *inconsistent*:
|
|
99
|
+
|
|
100
|
+
* ``criterion="global"`` (Zahn's first criterion): the edge is longer than
|
|
101
|
+
``lambda_`` times the mean length of all tree edges;
|
|
102
|
+
* ``criterion="local"`` (second criterion): the edge is longer than
|
|
103
|
+
``lambda_`` times the mean length of the tree edges within ``depth``
|
|
104
|
+
steps of its end points, which also separates clusters of different
|
|
105
|
+
density;
|
|
106
|
+
* ``criterion="both"``: either of the two.
|
|
107
|
+
|
|
108
|
+
If ``n_clusters`` is given, removal stops when that many components exist;
|
|
109
|
+
with ``criterion=None`` the ``n_clusters - 1`` longest edges are removed,
|
|
110
|
+
which reproduces single-linkage clustering.
|
|
111
|
+
|
|
112
|
+
Attributes
|
|
113
|
+
----------
|
|
114
|
+
mst_ : sparse matrix, the tree; ``removed_edges_`` : list of removed (i, j);
|
|
115
|
+
labels_ : connected components after the removal.
|
|
116
|
+
|
|
117
|
+
Examples
|
|
118
|
+
--------
|
|
119
|
+
>>> import numpy as np
|
|
120
|
+
>>> X = np.r_[np.random.default_rng(0).normal(0, .1, (30, 2)), np.random.default_rng(1).normal(3, .1, (30, 2))]
|
|
121
|
+
>>> int(MSTClustering(lambda_=3, criterion="global").fit(X).labels_.max())
|
|
122
|
+
1
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(self, n_clusters=None, *, lambda_=2.0, criterion="both", depth=2, min_cluster_size=1):
|
|
126
|
+
self.n_clusters = n_clusters
|
|
127
|
+
self.lambda_ = lambda_
|
|
128
|
+
self.criterion = criterion
|
|
129
|
+
self.depth = depth
|
|
130
|
+
self.min_cluster_size = min_cluster_size
|
|
131
|
+
|
|
132
|
+
def fit(self, X, y=None):
|
|
133
|
+
X = as_data(X, min_samples=2)
|
|
134
|
+
N = len(X)
|
|
135
|
+
T = minimum_spanning_tree(X)
|
|
136
|
+
edges, w = edges_of(T)
|
|
137
|
+
adj = _adjacency_lists(N, edges)
|
|
138
|
+
mean_all = w.mean()
|
|
139
|
+
order = np.argsort(-w)
|
|
140
|
+
keep = np.ones(len(edges), bool)
|
|
141
|
+
removed = []
|
|
142
|
+
target = self.n_clusters or N
|
|
143
|
+
for e in order:
|
|
144
|
+
if len(removed) + 1 >= target:
|
|
145
|
+
break
|
|
146
|
+
a, b = edges[e]
|
|
147
|
+
if self.criterion is None:
|
|
148
|
+
incons = True
|
|
149
|
+
else:
|
|
150
|
+
g = w[e] > self.lambda_ * mean_all
|
|
151
|
+
loc = w[e] > self.lambda_ * _nearby_mean(adj, w, a, b, e, self.depth)
|
|
152
|
+
incons = {"global": g, "local": loc, "both": g or loc}[self.criterion]
|
|
153
|
+
if not incons:
|
|
154
|
+
continue
|
|
155
|
+
keep[e] = False
|
|
156
|
+
lab = _components(N, edges[keep])
|
|
157
|
+
sizes = np.bincount(lab)
|
|
158
|
+
if sizes.min() < self.min_cluster_size:
|
|
159
|
+
keep[e] = True
|
|
160
|
+
continue
|
|
161
|
+
removed.append((int(a), int(b)))
|
|
162
|
+
self.mst_ = T
|
|
163
|
+
self.removed_edges_ = removed
|
|
164
|
+
self.labels_ = _components(N, edges[keep])
|
|
165
|
+
self.n_clusters_ = int(self.labels_.max() + 1)
|
|
166
|
+
return self
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# =========================================================================== hybrid MST-GG
|
|
170
|
+
def _split_volumes(X, nodes, edges_local, D):
|
|
171
|
+
"""For every edge of a tree (local indices), the hypervolumes of the two parts after cutting it.
|
|
172
|
+
|
|
173
|
+
Uses subtree sums of x and x x^T so that all cuts cost O(n D^2) together.
|
|
174
|
+
"""
|
|
175
|
+
n = len(nodes)
|
|
176
|
+
adj = [[] for _ in range(n)]
|
|
177
|
+
for idx, (a, b) in enumerate(edges_local):
|
|
178
|
+
adj[a].append((b, idx))
|
|
179
|
+
adj[b].append((a, idx))
|
|
180
|
+
parent = -np.ones(n, int)
|
|
181
|
+
pedge = -np.ones(n, int)
|
|
182
|
+
order = [0]
|
|
183
|
+
seen = np.zeros(n, bool)
|
|
184
|
+
seen[0] = True
|
|
185
|
+
q = deque([0])
|
|
186
|
+
while q:
|
|
187
|
+
u = q.popleft()
|
|
188
|
+
for v, e in adj[u]:
|
|
189
|
+
if not seen[v]:
|
|
190
|
+
seen[v] = True
|
|
191
|
+
parent[v] = u
|
|
192
|
+
pedge[v] = e
|
|
193
|
+
order.append(v)
|
|
194
|
+
q.append(v)
|
|
195
|
+
Xs = X[nodes]
|
|
196
|
+
cnt = np.ones(n)
|
|
197
|
+
s1 = Xs.copy()
|
|
198
|
+
s2 = np.einsum("ki,kj->kij", Xs, Xs)
|
|
199
|
+
for v in reversed(order[1:]):
|
|
200
|
+
p = parent[v]
|
|
201
|
+
cnt[p] += cnt[v]
|
|
202
|
+
s1[p] += s1[v]
|
|
203
|
+
s2[p] += s2[v]
|
|
204
|
+
tot_n, tot_1, tot_2 = cnt[0], s1[0], s2[0]
|
|
205
|
+
|
|
206
|
+
def vol(nn, a1, a2):
|
|
207
|
+
mu = a1 / nn[:, None]
|
|
208
|
+
cov = a2 / nn[:, None, None] - np.einsum("ki,kj->kij", mu, mu)
|
|
209
|
+
return np.sqrt(np.maximum(np.linalg.det(cov), 0.0))
|
|
210
|
+
|
|
211
|
+
vs = np.array(order[1:])
|
|
212
|
+
nA = cnt[vs]
|
|
213
|
+
nB = tot_n - nA
|
|
214
|
+
vA = vol(nA, s1[vs], s2[vs])
|
|
215
|
+
vB = vol(nB, tot_1 - s1[vs], tot_2 - s2[vs])
|
|
216
|
+
res = np.full((len(edges_local), 4), np.nan)
|
|
217
|
+
res[pedge[vs]] = np.column_stack([vA, vB, nA, nB])
|
|
218
|
+
return res
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class HybridMSTGG(ClusterMixin, BaseEstimator):
|
|
222
|
+
r"""Hybrid minimal spanning tree -- Gath--Geva clustering (Vathy-Fogarassy, Feil and Abonyi 2005).
|
|
223
|
+
|
|
224
|
+
1. The data are scaled to the unit hypercube and their MST is built.
|
|
225
|
+
2. The cluster (subtree) with the largest hypervolume
|
|
226
|
+
:math:`V_i=\sqrt{\det\mathbf{F}_i}` is selected and split in two by
|
|
227
|
+
|
|
228
|
+
* Zahn's global criterion (edge longer than ``lambda_`` times the mean
|
|
229
|
+
edge of the subtree), else
|
|
230
|
+
* Zahn's local criterion (edge longer than ``lambda_`` times the mean of
|
|
231
|
+
the edges within ``depth`` steps), else
|
|
232
|
+
* the hypervolume criterion: the edge whose removal minimizes the total
|
|
233
|
+
fuzzy hypervolume :math:`\mathrm{FHV}=\sum_i V_i` of the partition.
|
|
234
|
+
|
|
235
|
+
The volume criterion cuts chains and bends that no length criterion
|
|
236
|
+
detects. Cuts that would leave fewer than ``min_cluster_size`` samples
|
|
237
|
+
on either side are not considered.
|
|
238
|
+
3. Step 2 is repeated until ``max_clusters`` clusters exist.
|
|
239
|
+
4. With ``gath_geva=True`` the crisp partition initializes
|
|
240
|
+
:class:`graphclust.fuzzy.GathGeva`, which returns memberships, centers
|
|
241
|
+
and covariance matrices (a mixture of Gaussians).
|
|
242
|
+
|
|
243
|
+
Attributes
|
|
244
|
+
----------
|
|
245
|
+
tree_labels_ : crisp labels after the MST cutting
|
|
246
|
+
labels_ : final labels (Gath--Geva argmax if used)
|
|
247
|
+
membership_, cluster_centers_, covariances_ : from Gath--Geva
|
|
248
|
+
split_history_ : list of dicts (cluster, edge, criterion, volumes)
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
def __init__(
|
|
252
|
+
self,
|
|
253
|
+
max_clusters=4,
|
|
254
|
+
*,
|
|
255
|
+
lambda_=2.0,
|
|
256
|
+
depth=2,
|
|
257
|
+
min_cluster_size=None,
|
|
258
|
+
gath_geva=True,
|
|
259
|
+
m=2.0,
|
|
260
|
+
tol=1e-4,
|
|
261
|
+
normalize=True,
|
|
262
|
+
):
|
|
263
|
+
self.max_clusters = max_clusters
|
|
264
|
+
self.lambda_ = lambda_
|
|
265
|
+
self.depth = depth
|
|
266
|
+
self.min_cluster_size = min_cluster_size
|
|
267
|
+
self.gath_geva = gath_geva
|
|
268
|
+
self.m = m
|
|
269
|
+
self.tol = tol
|
|
270
|
+
self.normalize = normalize
|
|
271
|
+
|
|
272
|
+
def fit(self, X, y=None):
|
|
273
|
+
X0 = as_data(X, min_samples=3)
|
|
274
|
+
X = minmax_scale(X0) if self.normalize else X0
|
|
275
|
+
N, D = X.shape
|
|
276
|
+
mcs = int(self.min_cluster_size or D + 1)
|
|
277
|
+
T = minimum_spanning_tree(X)
|
|
278
|
+
edges, w = edges_of(T)
|
|
279
|
+
keep = np.ones(len(edges), bool)
|
|
280
|
+
labels = np.zeros(N, int)
|
|
281
|
+
frozen = set()
|
|
282
|
+
history = []
|
|
283
|
+
while labels.max() + 1 < self.max_clusters:
|
|
284
|
+
c = labels.max() + 1
|
|
285
|
+
vols = np.array(
|
|
286
|
+
[
|
|
287
|
+
np.sqrt(max(np.linalg.det(np.atleast_2d(np.cov(X[labels == i].T, bias=True))), 0.0))
|
|
288
|
+
if (labels == i).sum() > D
|
|
289
|
+
else 0.0
|
|
290
|
+
for i in range(c)
|
|
291
|
+
]
|
|
292
|
+
)
|
|
293
|
+
cand = [i for i in np.argsort(-vols) if i not in frozen and (labels == i).sum() >= 2 * mcs]
|
|
294
|
+
if not cand:
|
|
295
|
+
break
|
|
296
|
+
done = False
|
|
297
|
+
for ci in cand:
|
|
298
|
+
nodes = np.flatnonzero(labels == ci)
|
|
299
|
+
loc = -np.ones(N, int)
|
|
300
|
+
loc[nodes] = np.arange(len(nodes))
|
|
301
|
+
eidx = np.flatnonzero(keep & (labels[edges[:, 0]] == ci))
|
|
302
|
+
el = loc[edges[eidx]]
|
|
303
|
+
parts = _split_volumes(X, nodes, el, D)
|
|
304
|
+
feasible = (parts[:, 2] >= mcs) & (parts[:, 3] >= mcs)
|
|
305
|
+
if not feasible.any():
|
|
306
|
+
frozen.add(ci)
|
|
307
|
+
continue
|
|
308
|
+
we = w[eidx]
|
|
309
|
+
adj = _adjacency_lists(len(nodes), el)
|
|
310
|
+
choice, crit = None, None
|
|
311
|
+
g = feasible & (we > self.lambda_ * we.mean())
|
|
312
|
+
if g.any():
|
|
313
|
+
choice, crit = np.flatnonzero(g)[np.argmax(we[g])], "global"
|
|
314
|
+
else:
|
|
315
|
+
locm = np.array([_nearby_mean(adj, we, a, b, k, self.depth) for k, (a, b) in enumerate(el)])
|
|
316
|
+
lmask = feasible & (we > self.lambda_ * locm)
|
|
317
|
+
if lmask.any():
|
|
318
|
+
choice, crit = np.flatnonzero(lmask)[np.argmax(we[lmask])], "local"
|
|
319
|
+
else:
|
|
320
|
+
tot = np.where(feasible, parts[:, 0] + parts[:, 1], np.inf)
|
|
321
|
+
choice, crit = int(np.argmin(tot)), "volume"
|
|
322
|
+
e = eidx[choice]
|
|
323
|
+
keep[e] = False
|
|
324
|
+
new = _components(N, edges[keep])
|
|
325
|
+
# keep existing label numbers; the split-off part gets a new label
|
|
326
|
+
part = new[edges[e, 1]]
|
|
327
|
+
moved = (labels == ci) & (new == part)
|
|
328
|
+
labels[moved] = c
|
|
329
|
+
history.append(
|
|
330
|
+
{
|
|
331
|
+
"cluster": int(ci),
|
|
332
|
+
"new_cluster": int(c),
|
|
333
|
+
"edge": tuple(int(v) for v in edges[e]),
|
|
334
|
+
"length": float(w[e]),
|
|
335
|
+
"criterion": crit,
|
|
336
|
+
"volumes": (float(parts[choice, 0]), float(parts[choice, 1])),
|
|
337
|
+
}
|
|
338
|
+
)
|
|
339
|
+
done = True
|
|
340
|
+
break
|
|
341
|
+
if not done:
|
|
342
|
+
break
|
|
343
|
+
self.mst_ = T
|
|
344
|
+
self.tree_labels_ = labels.copy()
|
|
345
|
+
self.split_history_ = history
|
|
346
|
+
self.n_clusters_ = int(labels.max() + 1)
|
|
347
|
+
if self.gath_geva and self.n_clusters_ > 1:
|
|
348
|
+
gg = GathGeva(self.n_clusters_, m=self.m, tol=self.tol, init=labels_to_membership(labels)).fit(X)
|
|
349
|
+
self.membership_ = gg.membership_
|
|
350
|
+
self.cluster_centers_ = gg.cluster_centers_
|
|
351
|
+
self.covariances_ = gg.covariances_
|
|
352
|
+
self.priors_ = gg.priors_
|
|
353
|
+
self.gath_geva_ = gg
|
|
354
|
+
self.labels_ = gg.labels_
|
|
355
|
+
else:
|
|
356
|
+
self.membership_ = labels_to_membership(labels)
|
|
357
|
+
self.labels_ = labels
|
|
358
|
+
self.n_features_in_ = D
|
|
359
|
+
return self
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# =========================================================================== HDBSCAN*
|
|
363
|
+
def _mst_linkage(n, edges, w):
|
|
364
|
+
"""Single-linkage merge matrix (SciPy format) from the edges of a spanning tree."""
|
|
365
|
+
order = np.argsort(w, kind="stable")
|
|
366
|
+
parent = np.arange(2 * n - 1)
|
|
367
|
+
size = np.ones(2 * n - 1)
|
|
368
|
+
|
|
369
|
+
def find(a):
|
|
370
|
+
while parent[a] != a:
|
|
371
|
+
parent[a] = parent[parent[a]]
|
|
372
|
+
a = parent[a]
|
|
373
|
+
return a
|
|
374
|
+
|
|
375
|
+
Z = np.zeros((n - 1, 4))
|
|
376
|
+
nxt = n
|
|
377
|
+
for r, e in enumerate(order):
|
|
378
|
+
a, b = find(edges[e, 0]), find(edges[e, 1])
|
|
379
|
+
Z[r] = [a, b, w[e], size[a] + size[b]]
|
|
380
|
+
parent[a] = parent[b] = nxt
|
|
381
|
+
size[nxt] = size[a] + size[b]
|
|
382
|
+
nxt += 1
|
|
383
|
+
return Z
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _condense(Z, n, mcs):
|
|
387
|
+
root = 2 * n - 2
|
|
388
|
+
relabel = {root: n}
|
|
389
|
+
next_label = n + 1
|
|
390
|
+
rows = []
|
|
391
|
+
ignore = set()
|
|
392
|
+
|
|
393
|
+
def size(node):
|
|
394
|
+
return 1 if node < n else int(Z[node - n, 3])
|
|
395
|
+
|
|
396
|
+
def leaves(node):
|
|
397
|
+
out, st = [], [node]
|
|
398
|
+
while st:
|
|
399
|
+
u = st.pop()
|
|
400
|
+
if u < n:
|
|
401
|
+
out.append(u)
|
|
402
|
+
else:
|
|
403
|
+
ignore.add(u)
|
|
404
|
+
st.extend([int(Z[u - n, 0]), int(Z[u - n, 1])])
|
|
405
|
+
return out
|
|
406
|
+
|
|
407
|
+
q = deque([root])
|
|
408
|
+
while q:
|
|
409
|
+
node = q.popleft()
|
|
410
|
+
if node < n or node in ignore:
|
|
411
|
+
continue
|
|
412
|
+
a, b, dist = int(Z[node - n, 0]), int(Z[node - n, 1]), Z[node - n, 2]
|
|
413
|
+
lam = 1.0 / dist if dist > 0 else np.inf
|
|
414
|
+
sa, sb = size(a), size(b)
|
|
415
|
+
p = relabel[node]
|
|
416
|
+
if sa >= mcs and sb >= mcs:
|
|
417
|
+
for ch, s in ((a, sa), (b, sb)):
|
|
418
|
+
relabel[ch] = next_label
|
|
419
|
+
rows.append((p, next_label, lam, s))
|
|
420
|
+
next_label += 1
|
|
421
|
+
q.append(ch)
|
|
422
|
+
elif sa < mcs and sb < mcs:
|
|
423
|
+
for ch in (a, b):
|
|
424
|
+
for leaf in leaves(ch):
|
|
425
|
+
rows.append((p, leaf, lam, 1))
|
|
426
|
+
else:
|
|
427
|
+
big, small = (a, b) if sa >= mcs else (b, a)
|
|
428
|
+
relabel[big] = p
|
|
429
|
+
q.append(big)
|
|
430
|
+
for leaf in leaves(small):
|
|
431
|
+
rows.append((p, leaf, lam, 1))
|
|
432
|
+
return np.array(rows, dtype=[("parent", int), ("child", int), ("lam", float), ("size", int)])
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class HDBSCANStar(ClusterMixin, BaseEstimator):
|
|
436
|
+
r"""HDBSCAN* (Campello, Moulavi and Sander 2013; 2015): density clustering from a spanning tree.
|
|
437
|
+
|
|
438
|
+
The core distance of a sample is the distance of its ``min_samples``-th
|
|
439
|
+
nearest neighbor (the sample itself counted), the mutual reachability
|
|
440
|
+
distance is :math:`d_{mr}(a,b)=\max\{c(a),c(b),d(a,b)\}`, and the MST of
|
|
441
|
+
the complete mutual reachability graph encodes the whole single-linkage
|
|
442
|
+
hierarchy of density levels. The hierarchy is condensed (splits that cut
|
|
443
|
+
off fewer than ``min_cluster_size`` samples are treated as samples leaving
|
|
444
|
+
a cluster) and the clusters with the largest total *stability*
|
|
445
|
+
:math:`\sum_{x}(\lambda_x-\lambda_{\mathrm{birth}})` are selected (excess of
|
|
446
|
+
mass). Samples outside the selected clusters are noise (label ``-1``).
|
|
447
|
+
|
|
448
|
+
HDBSCAN* is the density-based heir of the MST clustering of Zahn: the
|
|
449
|
+
tree is the same object, but the edge weights are density-corrected and
|
|
450
|
+
the cut is chosen by stability instead of a length threshold.
|
|
451
|
+
|
|
452
|
+
Attributes
|
|
453
|
+
----------
|
|
454
|
+
labels_, probabilities_ (membership strength in [0, 1]), core_distances_,
|
|
455
|
+
mst_ (mutual reachability tree), condensed_tree_ (structured array),
|
|
456
|
+
cluster_persistence_ (stability of the selected clusters).
|
|
457
|
+
"""
|
|
458
|
+
|
|
459
|
+
def __init__(self, min_cluster_size=5, *, min_samples=None, allow_single_cluster=False):
|
|
460
|
+
self.min_cluster_size = min_cluster_size
|
|
461
|
+
self.min_samples = min_samples
|
|
462
|
+
self.allow_single_cluster = allow_single_cluster
|
|
463
|
+
|
|
464
|
+
def fit(self, X, y=None):
|
|
465
|
+
X = as_data(X, min_samples=2)
|
|
466
|
+
N = len(X)
|
|
467
|
+
ms = int(self.min_samples or self.min_cluster_size)
|
|
468
|
+
D = pairwise_distances(X)
|
|
469
|
+
core = np.sort(D, axis=1)[:, min(ms, N) - 1]
|
|
470
|
+
M = np.maximum(D, np.maximum(core[:, None], core[None, :]))
|
|
471
|
+
np.fill_diagonal(M, 0.0)
|
|
472
|
+
M[M == 0] = 1e-12
|
|
473
|
+
np.fill_diagonal(M, 0.0)
|
|
474
|
+
T = minimum_spanning_tree(graph=csr_matrix(np.triu(M)))
|
|
475
|
+
edges, w = edges_of(T)
|
|
476
|
+
Z = _mst_linkage(N, edges, w)
|
|
477
|
+
ct = _condense(Z, N, int(self.min_cluster_size))
|
|
478
|
+
clusters = np.unique(ct["parent"])
|
|
479
|
+
root = N
|
|
480
|
+
birth = {root: 0.0}
|
|
481
|
+
for r in ct[ct["size"] > 1]:
|
|
482
|
+
birth[int(r["child"])] = float(r["lam"])
|
|
483
|
+
stab = {int(c): 0.0 for c in clusters}
|
|
484
|
+
for c in ct[ct["size"] > 1]["child"]:
|
|
485
|
+
stab.setdefault(int(c), 0.0)
|
|
486
|
+
for r in ct:
|
|
487
|
+
lam = r["lam"] if np.isfinite(r["lam"]) else 0.0
|
|
488
|
+
stab[int(r["parent"])] += (lam - birth[int(r["parent"])]) * r["size"]
|
|
489
|
+
children = {}
|
|
490
|
+
for r in ct[ct["size"] > 1]:
|
|
491
|
+
children.setdefault(int(r["parent"]), []).append(int(r["child"]))
|
|
492
|
+
nodes = sorted(stab, reverse=True)
|
|
493
|
+
if not self.allow_single_cluster:
|
|
494
|
+
nodes = [c for c in nodes if c != root]
|
|
495
|
+
selected = {c: True for c in nodes}
|
|
496
|
+
|
|
497
|
+
def descendants(c):
|
|
498
|
+
out, st = [], list(children.get(c, []))
|
|
499
|
+
while st:
|
|
500
|
+
u = st.pop()
|
|
501
|
+
out.append(u)
|
|
502
|
+
st.extend(children.get(u, []))
|
|
503
|
+
return out
|
|
504
|
+
|
|
505
|
+
for c in nodes:
|
|
506
|
+
sub = sum(stab[ch] for ch in children.get(c, []))
|
|
507
|
+
if children.get(c) and sub > stab[c]:
|
|
508
|
+
selected[c] = False
|
|
509
|
+
stab[c] = sub
|
|
510
|
+
else:
|
|
511
|
+
for d in descendants(c):
|
|
512
|
+
selected[d] = False
|
|
513
|
+
chosen = sorted(c for c, s in selected.items() if s)
|
|
514
|
+
if self.allow_single_cluster and len(chosen) > 1 and root in chosen:
|
|
515
|
+
chosen.remove(root)
|
|
516
|
+
up = {int(r["child"]): int(r["parent"]) for r in ct[ct["size"] > 1]}
|
|
517
|
+
label_of = {c: i for i, c in enumerate(chosen)}
|
|
518
|
+
|
|
519
|
+
def owner(c):
|
|
520
|
+
while c not in label_of and c in up:
|
|
521
|
+
c = up[c]
|
|
522
|
+
return label_of.get(c, -1)
|
|
523
|
+
|
|
524
|
+
labels = -np.ones(N, int)
|
|
525
|
+
prob = np.zeros(N)
|
|
526
|
+
maxlam = {}
|
|
527
|
+
leaf_rows = ct[ct["size"] == 1]
|
|
528
|
+
for r in leaf_rows:
|
|
529
|
+
lab = owner(int(r["parent"]))
|
|
530
|
+
labels[r["child"]] = lab
|
|
531
|
+
for r in leaf_rows:
|
|
532
|
+
lab = labels[r["child"]]
|
|
533
|
+
if lab >= 0:
|
|
534
|
+
lam = r["lam"] if np.isfinite(r["lam"]) else 0.0
|
|
535
|
+
maxlam[lab] = max(maxlam.get(lab, 0.0), lam)
|
|
536
|
+
for r in leaf_rows:
|
|
537
|
+
lab = labels[r["child"]]
|
|
538
|
+
if lab >= 0:
|
|
539
|
+
lam = r["lam"] if np.isfinite(r["lam"]) else maxlam[lab]
|
|
540
|
+
prob[r["child"]] = min(lam, maxlam[lab]) / maxlam[lab] if maxlam[lab] > 0 else 1.0
|
|
541
|
+
self.labels_ = labels
|
|
542
|
+
self.probabilities_ = prob
|
|
543
|
+
self.core_distances_ = core
|
|
544
|
+
self.mst_ = T
|
|
545
|
+
self.single_linkage_tree_ = Z
|
|
546
|
+
self.condensed_tree_ = ct
|
|
547
|
+
self.cluster_persistence_ = np.array([stab[c] for c in chosen])
|
|
548
|
+
self.n_clusters_ = len(chosen)
|
|
549
|
+
return self
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
# =========================================================================== neighborhood similarity
|
|
553
|
+
def fuzzy_neighborhood_similarity(X, k=6, r_max=3, alpha=0.2) -> np.ndarray:
|
|
554
|
+
r"""Transitive fuzzy neighborhood similarity (Vathy-Fogarassy, Kiss and Abonyi 2007).
|
|
555
|
+
|
|
556
|
+
With :math:`A_i^{(r)}` the :math:`r`-order neighborhood of sample
|
|
557
|
+
:math:`i` (its :math:`k` nearest neighbors and itself for :math:`r=1`; the
|
|
558
|
+
union of the neighborhoods of all members of :math:`A_i^{(r-1)}`
|
|
559
|
+
otherwise), the similarity is the first-order filtered sequence of Jaccard
|
|
560
|
+
indices
|
|
561
|
+
|
|
562
|
+
.. math:: s_{ij}^{(r)} = (1-\alpha)\,s_{ij}^{(r-1)} + \alpha\,
|
|
563
|
+
\frac{|A_i^{(r)}\cap A_j^{(r)}|}{|A_i^{(r)}\cup A_j^{(r)}|},
|
|
564
|
+
\qquad s_{ij}^{(0)}=0,\; r=1,\dots,r_{\max}.
|
|
565
|
+
|
|
566
|
+
For :math:`r_{\max}=1,\ \alpha=1` it is the Jaccard index of the
|
|
567
|
+
neighbor sets, :math:`m_{ij}/(2(k+1)-m_{ij})`, a fuzzification of the
|
|
568
|
+
Jarvis--Patrick threshold; the same quantity later became the edge weight
|
|
569
|
+
of PhenoGraph-type community detection. The result is a dense symmetric
|
|
570
|
+
matrix with ones on the diagonal; :math:`1-\mathbf{S}` is a dissimilarity
|
|
571
|
+
usable by hierarchical clustering, MDS or VAT.
|
|
572
|
+
|
|
573
|
+
Examples
|
|
574
|
+
--------
|
|
575
|
+
>>> import numpy as np
|
|
576
|
+
>>> S = fuzzy_neighborhood_similarity(np.random.default_rng(0).normal(size=(40, 2)), k=5)
|
|
577
|
+
>>> S.shape, bool(np.allclose(S, S.T))
|
|
578
|
+
((40, 40), True)
|
|
579
|
+
"""
|
|
580
|
+
idx, _ = knn_indices(X, k)
|
|
581
|
+
N = idx.shape[0]
|
|
582
|
+
K = np.zeros((N, N), bool)
|
|
583
|
+
K[np.repeat(np.arange(N), idx.shape[1]), idx.ravel()] = True
|
|
584
|
+
np.fill_diagonal(K, True)
|
|
585
|
+
Kf = K.astype(float)
|
|
586
|
+
A = K.copy()
|
|
587
|
+
S = np.zeros((N, N))
|
|
588
|
+
for r in range(1, int(r_max) + 1):
|
|
589
|
+
if r > 1:
|
|
590
|
+
A = (A.astype(float) @ Kf) > 0
|
|
591
|
+
Af = A.astype(float)
|
|
592
|
+
inter = Af @ Af.T
|
|
593
|
+
sizes = Af.sum(1)
|
|
594
|
+
union = sizes[:, None] + sizes[None, :] - inter
|
|
595
|
+
S = (1 - alpha) * S + alpha * inter / np.maximum(union, 1)
|
|
596
|
+
S = np.maximum(S, S.T)
|
|
597
|
+
np.fill_diagonal(S, 1.0)
|
|
598
|
+
return S
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def jaccard_knn_graph(X, k=15) -> csr_matrix:
|
|
602
|
+
r"""kNN graph re-weighted by the Jaccard index of the neighbor sets (PhenoGraph-style, Levine et al. 2015).
|
|
603
|
+
|
|
604
|
+
Only pairs that are linked in the symmetric :math:`k`-NN graph keep an
|
|
605
|
+
edge; its weight is :math:`|A_i\cap A_j|/|A_i\cup A_j|` (similarities, not
|
|
606
|
+
lengths), the first-order fuzzy neighborhood similarity.
|
|
607
|
+
"""
|
|
608
|
+
M, idx = shared_neighbor_counts(X, k, include_self=True)
|
|
609
|
+
N = len(M)
|
|
610
|
+
kk = idx.shape[1]
|
|
611
|
+
rows = np.repeat(np.arange(N), kk - 1)
|
|
612
|
+
cols = idx[:, 1:].ravel()
|
|
613
|
+
inter = M[rows, cols].astype(float)
|
|
614
|
+
wgt = inter / (2 * kk - inter)
|
|
615
|
+
A = coo_matrix((wgt, (rows, cols)), shape=(N, N)).tocsr()
|
|
616
|
+
A = A.maximum(A.T)
|
|
617
|
+
A.eliminate_zeros()
|
|
618
|
+
return A
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
class JarvisPatrick(ClusterMixin, BaseEstimator):
|
|
622
|
+
r"""Jarvis--Patrick shared nearest neighbor clustering (1973).
|
|
623
|
+
|
|
624
|
+
Two samples are linked when each is among the other's ``k`` nearest
|
|
625
|
+
neighbors and they share at least ``min_shared`` neighbors; the clusters
|
|
626
|
+
are the connected components of this graph. Singletons can be read as
|
|
627
|
+
outliers. The result reacts strongly to both integer parameters, which
|
|
628
|
+
motivated the fuzzy neighborhood similarity.
|
|
629
|
+
"""
|
|
630
|
+
|
|
631
|
+
def __init__(self, k=8, min_shared=4, *, include_self=True):
|
|
632
|
+
self.k = k
|
|
633
|
+
self.min_shared = min_shared
|
|
634
|
+
self.include_self = include_self
|
|
635
|
+
|
|
636
|
+
def fit(self, X, y=None):
|
|
637
|
+
X = as_data(X, min_samples=2)
|
|
638
|
+
M, idx = shared_neighbor_counts(X, self.k, include_self=self.include_self)
|
|
639
|
+
N = len(X)
|
|
640
|
+
nbr = np.zeros((N, N), bool)
|
|
641
|
+
base = idx[:, 1:] if self.include_self else idx
|
|
642
|
+
nbr[np.repeat(np.arange(N), base.shape[1]), base.ravel()] = True
|
|
643
|
+
link = nbr & nbr.T & (M >= self.min_shared)
|
|
644
|
+
np.fill_diagonal(link, False)
|
|
645
|
+
self.n_clusters_, self.labels_ = connected_components(csr_matrix(link), directed=False)
|
|
646
|
+
self.shared_counts_ = M
|
|
647
|
+
return self
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
class FuzzyNeighborhoodClustering(ClusterMixin, BaseEstimator):
|
|
651
|
+
r"""Hierarchical clustering on the fuzzy neighborhood distance :math:`d_{ij}=1-s_{ij}`.
|
|
652
|
+
|
|
653
|
+
Computes :func:`fuzzy_neighborhood_similarity` and runs agglomerative
|
|
654
|
+
clustering (``linkage`` = single, average or complete) on the resulting
|
|
655
|
+
distances; the dendrogram is cut either at ``n_clusters`` or at
|
|
656
|
+
``distance_threshold``. Clusters smaller than ``min_cluster_size`` are
|
|
657
|
+
reported as outliers (label ``-1``).
|
|
658
|
+
|
|
659
|
+
Attributes
|
|
660
|
+
----------
|
|
661
|
+
similarity_, linkage_matrix_ (SciPy format, for dendrograms), labels_
|
|
662
|
+
"""
|
|
663
|
+
|
|
664
|
+
def __init__(
|
|
665
|
+
self,
|
|
666
|
+
n_clusters=None,
|
|
667
|
+
*,
|
|
668
|
+
k=6,
|
|
669
|
+
r_max=3,
|
|
670
|
+
alpha=0.2,
|
|
671
|
+
linkage="single",
|
|
672
|
+
distance_threshold=None,
|
|
673
|
+
min_cluster_size=1,
|
|
674
|
+
):
|
|
675
|
+
self.n_clusters = n_clusters
|
|
676
|
+
self.k = k
|
|
677
|
+
self.r_max = r_max
|
|
678
|
+
self.alpha = alpha
|
|
679
|
+
self.linkage = linkage
|
|
680
|
+
self.distance_threshold = distance_threshold
|
|
681
|
+
self.min_cluster_size = min_cluster_size
|
|
682
|
+
|
|
683
|
+
def fit(self, X, y=None):
|
|
684
|
+
X = as_data(X, min_samples=3)
|
|
685
|
+
S = fuzzy_neighborhood_similarity(X, self.k, self.r_max, self.alpha)
|
|
686
|
+
Dm = 1.0 - S
|
|
687
|
+
np.fill_diagonal(Dm, 0.0)
|
|
688
|
+
Z = linkage(squareform(Dm, checks=False), method=self.linkage)
|
|
689
|
+
if self.distance_threshold is not None:
|
|
690
|
+
lab = fcluster(Z, self.distance_threshold, criterion="distance") - 1
|
|
691
|
+
else:
|
|
692
|
+
lab = fcluster(Z, self.n_clusters or 2, criterion="maxclust") - 1
|
|
693
|
+
sizes = np.bincount(lab)
|
|
694
|
+
small = sizes[lab] < self.min_cluster_size
|
|
695
|
+
lab = lab.copy()
|
|
696
|
+
lab[small] = -1
|
|
697
|
+
uniq = np.unique(lab[lab >= 0])
|
|
698
|
+
remap = {u: i for i, u in enumerate(uniq)}
|
|
699
|
+
self.labels_ = np.array([remap.get(v, -1) for v in lab])
|
|
700
|
+
self.similarity_ = S
|
|
701
|
+
self.linkage_matrix_ = Z
|
|
702
|
+
self.n_clusters_ = len(uniq)
|
|
703
|
+
return self
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
class SharedNearestNeighborClustering(ClusterMixin, BaseEstimator):
|
|
707
|
+
r"""Shared nearest neighbor density clustering (SNN; Ertöz, Steinbach and Kumar 2003).
|
|
708
|
+
|
|
709
|
+
The SNN similarity of two samples is the number of neighbors they share
|
|
710
|
+
when each is in the other's ``k``-NN list (zero otherwise). The SNN
|
|
711
|
+
density of a sample is the number of samples with similarity at least
|
|
712
|
+
``eps``; samples with density at least ``min_pts`` are core samples. Core
|
|
713
|
+
samples linked by similarity :math:`\ge` ``eps`` form the clusters,
|
|
714
|
+
non-core samples join the most similar core sample if that similarity is at
|
|
715
|
+
least ``eps``, and the rest is noise. Working on shared neighbors instead
|
|
716
|
+
of distances makes the method robust to clusters of different density.
|
|
717
|
+
"""
|
|
718
|
+
|
|
719
|
+
def __init__(self, k=20, *, eps=7, min_pts=10):
|
|
720
|
+
self.k = k
|
|
721
|
+
self.eps = eps
|
|
722
|
+
self.min_pts = min_pts
|
|
723
|
+
|
|
724
|
+
def fit(self, X, y=None):
|
|
725
|
+
X = as_data(X, min_samples=3)
|
|
726
|
+
M, idx = shared_neighbor_counts(X, self.k, include_self=False)
|
|
727
|
+
N = len(X)
|
|
728
|
+
nbr = np.zeros((N, N), bool)
|
|
729
|
+
nbr[np.repeat(np.arange(N), idx.shape[1]), idx.ravel()] = True
|
|
730
|
+
S = np.where(nbr & nbr.T, M, 0)
|
|
731
|
+
np.fill_diagonal(S, 0)
|
|
732
|
+
dens = (S >= self.eps).sum(1)
|
|
733
|
+
core = dens >= self.min_pts
|
|
734
|
+
labels = -np.ones(N, int)
|
|
735
|
+
if core.any():
|
|
736
|
+
ci = np.flatnonzero(core)
|
|
737
|
+
sub = csr_matrix(S[np.ix_(ci, ci)] >= self.eps)
|
|
738
|
+
_, lab = connected_components(sub, directed=False)
|
|
739
|
+
labels[ci] = lab
|
|
740
|
+
for i in np.flatnonzero(~core):
|
|
741
|
+
j = ci[np.argmax(S[i, ci])]
|
|
742
|
+
if S[i, j] >= self.eps:
|
|
743
|
+
labels[i] = labels[j]
|
|
744
|
+
self.labels_ = labels
|
|
745
|
+
self.snn_density_ = dens
|
|
746
|
+
self.core_sample_mask_ = core
|
|
747
|
+
self.n_clusters_ = int(labels.max() + 1)
|
|
748
|
+
return self
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
class DensityPeaks(ClusterMixin, BaseEstimator):
|
|
752
|
+
r"""Clustering by fast search and find of density peaks (Rodriguez and Laio 2014).
|
|
753
|
+
|
|
754
|
+
For each sample the local density :math:`\rho_i` (Gaussian kernel with
|
|
755
|
+
cut-off :math:`d_c` set to the ``percent`` percentile of the pairwise
|
|
756
|
+
distances, or the inverse mean distance to the ``k`` nearest neighbors when
|
|
757
|
+
``density="knn"``) and the distance :math:`\delta_i` to the nearest sample
|
|
758
|
+
of higher density are computed. Cluster centers are the samples with the
|
|
759
|
+
largest :math:`\gamma_i=\rho_i\delta_i` (they stand out in the
|
|
760
|
+
:math:`(\rho,\delta)` *decision graph*); every other sample inherits the
|
|
761
|
+
label of its nearest denser neighbor. The "nearest denser neighbor" links
|
|
762
|
+
form a spanning tree directed towards the peaks.
|
|
763
|
+
|
|
764
|
+
Attributes
|
|
765
|
+
----------
|
|
766
|
+
rho_, delta_, gamma_, nearest_denser_ (parent in the density tree), centers_
|
|
767
|
+
"""
|
|
768
|
+
|
|
769
|
+
def __init__(self, n_clusters=3, *, density="gaussian", percent=2.0, k=10):
|
|
770
|
+
self.n_clusters = n_clusters
|
|
771
|
+
self.density = density
|
|
772
|
+
self.percent = percent
|
|
773
|
+
self.k = k
|
|
774
|
+
|
|
775
|
+
def fit(self, X, y=None):
|
|
776
|
+
X = as_data(X, min_samples=3)
|
|
777
|
+
N = len(X)
|
|
778
|
+
D = pairwise_distances(X)
|
|
779
|
+
if self.density == "gaussian":
|
|
780
|
+
dc = np.percentile(squareform(D, checks=False), self.percent)
|
|
781
|
+
rho = np.exp(-((D / max(dc, EPS)) ** 2)).sum(1) - 1.0
|
|
782
|
+
elif self.density == "knn":
|
|
783
|
+
_, dist = knn_indices(X, self.k)
|
|
784
|
+
rho = np.exp(-(dist**2).mean(1))
|
|
785
|
+
else:
|
|
786
|
+
raise ValueError("density must be 'gaussian' or 'knn'")
|
|
787
|
+
rho = rho + 1e-12 * np.arange(N)[::-1] / N # deterministic tie breaking
|
|
788
|
+
order = np.argsort(-rho)
|
|
789
|
+
delta = np.zeros(N)
|
|
790
|
+
parent = -np.ones(N, int)
|
|
791
|
+
for r, i in enumerate(order):
|
|
792
|
+
if r == 0:
|
|
793
|
+
continue
|
|
794
|
+
denser = order[:r]
|
|
795
|
+
j = denser[np.argmin(D[i, denser])]
|
|
796
|
+
delta[i] = D[i, j]
|
|
797
|
+
parent[i] = j
|
|
798
|
+
delta[order[0]] = D[order[0]].max()
|
|
799
|
+
gamma = rho * delta
|
|
800
|
+
centers = np.argsort(-gamma)[: self.n_clusters]
|
|
801
|
+
labels = -np.ones(N, int)
|
|
802
|
+
labels[centers] = np.arange(len(centers))
|
|
803
|
+
for i in order:
|
|
804
|
+
if labels[i] < 0:
|
|
805
|
+
labels[i] = labels[parent[i]] if parent[i] >= 0 else 0
|
|
806
|
+
self.rho_, self.delta_, self.gamma_ = rho, delta, gamma
|
|
807
|
+
self.nearest_denser_ = parent
|
|
808
|
+
self.centers_ = centers
|
|
809
|
+
self.labels_ = labels
|
|
810
|
+
self.n_clusters_ = len(centers)
|
|
811
|
+
return self
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
# =========================================================================== global graph methods
|
|
815
|
+
class SpectralGraphClustering(ClusterMixin, BaseEstimator):
|
|
816
|
+
r"""Normalized spectral clustering (Ng, Jordan and Weiss 2002) on a neighborhood graph.
|
|
817
|
+
|
|
818
|
+
Affinities:
|
|
819
|
+
|
|
820
|
+
* ``"self_tuning"``: :math:`a_{ij}=\exp(-d_{ij}^2/(\sigma_i\sigma_j))` on the
|
|
821
|
+
symmetric ``k``-NN graph with local scales :math:`\sigma_i` = distance to
|
|
822
|
+
the ``k``-th neighbor (Zelnik-Manor and Perona 2004);
|
|
823
|
+
* ``"fuzzy"``: the fuzzy neighborhood similarity matrix;
|
|
824
|
+
* ``"precomputed"``: ``X`` is an affinity matrix.
|
|
825
|
+
|
|
826
|
+
The ``n_clusters`` leading eigenvectors of
|
|
827
|
+
:math:`\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2}` are row-normalized and
|
|
828
|
+
clustered with k-means. With ``n_clusters="auto"`` the number of clusters
|
|
829
|
+
is taken at the largest relative gap of the Laplacian eigenvalues
|
|
830
|
+
:math:`\mu_l=1-\lambda_l` among the first ``max_clusters``
|
|
831
|
+
(:func:`graphclust.validity.eigengap`).
|
|
832
|
+
"""
|
|
833
|
+
|
|
834
|
+
def __init__(self, n_clusters=2, *, affinity="self_tuning", k=10, max_clusters=10, random_state=None):
|
|
835
|
+
self.n_clusters = n_clusters
|
|
836
|
+
self.affinity = affinity
|
|
837
|
+
self.k = k
|
|
838
|
+
self.max_clusters = max_clusters
|
|
839
|
+
self.random_state = random_state
|
|
840
|
+
|
|
841
|
+
def _affinity(self, X):
|
|
842
|
+
if self.affinity == "precomputed":
|
|
843
|
+
return np.asarray(X, dtype=float)
|
|
844
|
+
X = as_data(X, min_samples=3)
|
|
845
|
+
if self.affinity == "fuzzy":
|
|
846
|
+
return fuzzy_neighborhood_similarity(X, self.k)
|
|
847
|
+
idx, dist = knn_indices(X, self.k)
|
|
848
|
+
sigma = dist[:, -1] + EPS
|
|
849
|
+
N = len(X)
|
|
850
|
+
rows = np.repeat(np.arange(N), idx.shape[1])
|
|
851
|
+
cols = idx.ravel()
|
|
852
|
+
a = np.exp(-(dist.ravel() ** 2) / (sigma[rows] * sigma[cols]))
|
|
853
|
+
A = coo_matrix((a, (rows, cols)), shape=(N, N)).toarray()
|
|
854
|
+
return np.maximum(A, A.T)
|
|
855
|
+
|
|
856
|
+
def fit(self, X, y=None):
|
|
857
|
+
A = self._affinity(X)
|
|
858
|
+
np.fill_diagonal(A, 0.0)
|
|
859
|
+
d = A.sum(1)
|
|
860
|
+
dinv = 1.0 / np.sqrt(np.maximum(d, EPS))
|
|
861
|
+
L = dinv[:, None] * A * dinv[None, :]
|
|
862
|
+
vals, vecs = np.linalg.eigh(L)
|
|
863
|
+
vals, vecs = vals[::-1], vecs[:, ::-1]
|
|
864
|
+
if self.n_clusters == "auto":
|
|
865
|
+
from .validity import _eigengap_from_values
|
|
866
|
+
|
|
867
|
+
c = _eigengap_from_values(vals, self.max_clusters)
|
|
868
|
+
else:
|
|
869
|
+
c = int(self.n_clusters)
|
|
870
|
+
E = vecs[:, :c]
|
|
871
|
+
E = E / np.maximum(np.linalg.norm(E, axis=1, keepdims=True), EPS)
|
|
872
|
+
km = KMeans(c, n_init=10, random_state=self.random_state).fit(E)
|
|
873
|
+
self.affinity_matrix_ = A
|
|
874
|
+
self.eigenvalues_ = vals[: max(c, min(self.max_clusters + 1, len(vals)))]
|
|
875
|
+
self.embedding_ = E
|
|
876
|
+
self.labels_ = km.labels_
|
|
877
|
+
self.n_clusters_ = c
|
|
878
|
+
return self
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
class GraphCommunityClustering(ClusterMixin, BaseEstimator):
|
|
882
|
+
r"""Community detection on a neighborhood graph (PhenoGraph-style pipeline).
|
|
883
|
+
|
|
884
|
+
1. Build a graph: ``"jaccard"`` (kNN graph with Jaccard weights, i.e. the
|
|
885
|
+
first-order fuzzy neighborhood similarity), ``"knn"`` (binary symmetric
|
|
886
|
+
kNN graph) or ``"fuzzy"`` (transitive fuzzy neighborhood similarity,
|
|
887
|
+
sparsified to the kNN pairs).
|
|
888
|
+
2. Maximize modularity with ``method``:
|
|
889
|
+
|
|
890
|
+
* ``"louvain"`` (Blondel et al. 2008, via :mod:`networkx`);
|
|
891
|
+
* ``"leiden"`` (Traag, Waltman and van Eck 2019; uses the optional
|
|
892
|
+
packages ``leidenalg`` and ``python-igraph`` and falls back to Louvain
|
|
893
|
+
with a warning if they are missing);
|
|
894
|
+
* ``"label_propagation"`` (Raghavan et al. 2007);
|
|
895
|
+
* ``"greedy"`` (Clauset--Newman--Moore).
|
|
896
|
+
|
|
897
|
+
``resolution`` > 1 favors smaller communities. The number of clusters is
|
|
898
|
+
not an input: it follows from the graph and the resolution.
|
|
899
|
+
"""
|
|
900
|
+
|
|
901
|
+
def __init__(self, k=15, *, graph="jaccard", method="louvain", resolution=1.0, random_state=None):
|
|
902
|
+
self.k = k
|
|
903
|
+
self.graph = graph
|
|
904
|
+
self.method = method
|
|
905
|
+
self.resolution = resolution
|
|
906
|
+
self.random_state = random_state
|
|
907
|
+
|
|
908
|
+
def _graph(self, X):
|
|
909
|
+
if self.graph == "jaccard":
|
|
910
|
+
return jaccard_knn_graph(X, self.k)
|
|
911
|
+
idx, _ = knn_indices(X, self.k)
|
|
912
|
+
N = idx.shape[0]
|
|
913
|
+
rows = np.repeat(np.arange(N), idx.shape[1])
|
|
914
|
+
A = coo_matrix((np.ones(rows.size), (rows, idx.ravel())), shape=(N, N)).tocsr()
|
|
915
|
+
A = A.maximum(A.T)
|
|
916
|
+
if self.graph == "knn":
|
|
917
|
+
return A
|
|
918
|
+
if self.graph == "fuzzy":
|
|
919
|
+
S = fuzzy_neighborhood_similarity(X, self.k)
|
|
920
|
+
return csr_matrix(A.multiply(S))
|
|
921
|
+
raise ValueError(f"unknown graph {self.graph!r}")
|
|
922
|
+
|
|
923
|
+
def fit(self, X, y=None):
|
|
924
|
+
import warnings
|
|
925
|
+
|
|
926
|
+
import networkx as nx
|
|
927
|
+
|
|
928
|
+
X = as_data(X, min_samples=3)
|
|
929
|
+
A = self._graph(X)
|
|
930
|
+
G = to_networkx(A)
|
|
931
|
+
seed = check_random_state(self.random_state).randint(2**31 - 1)
|
|
932
|
+
method = self.method
|
|
933
|
+
comms = None
|
|
934
|
+
if method == "leiden":
|
|
935
|
+
try:
|
|
936
|
+
import igraph as ig
|
|
937
|
+
import leidenalg
|
|
938
|
+
|
|
939
|
+
e, wgt = edges_of(A)
|
|
940
|
+
g = ig.Graph(n=A.shape[0], edges=e.tolist())
|
|
941
|
+
part = leidenalg.find_partition(
|
|
942
|
+
g,
|
|
943
|
+
leidenalg.RBConfigurationVertexPartition,
|
|
944
|
+
weights=list(wgt),
|
|
945
|
+
resolution_parameter=self.resolution,
|
|
946
|
+
seed=seed,
|
|
947
|
+
)
|
|
948
|
+
comms = [set(c) for c in part]
|
|
949
|
+
except ImportError:
|
|
950
|
+
warnings.warn("leidenalg/igraph not installed: using Louvain", stacklevel=2)
|
|
951
|
+
method = "louvain"
|
|
952
|
+
if comms is None:
|
|
953
|
+
if method == "louvain":
|
|
954
|
+
comms = nx.community.louvain_communities(G, weight="weight", resolution=self.resolution, seed=seed)
|
|
955
|
+
elif method == "label_propagation":
|
|
956
|
+
comms = nx.community.asyn_lpa_communities(G, weight="weight", seed=seed)
|
|
957
|
+
elif method == "greedy":
|
|
958
|
+
comms = nx.community.greedy_modularity_communities(G, weight="weight", resolution=self.resolution)
|
|
959
|
+
else:
|
|
960
|
+
raise ValueError(f"unknown method {self.method!r}")
|
|
961
|
+
comms = sorted((sorted(c) for c in comms), key=lambda c: (-len(c), c[0]))
|
|
962
|
+
labels = np.empty(A.shape[0], int)
|
|
963
|
+
for i, c in enumerate(comms):
|
|
964
|
+
labels[c] = i
|
|
965
|
+
self.graph_ = A
|
|
966
|
+
self.labels_ = labels
|
|
967
|
+
self.n_clusters_ = len(comms)
|
|
968
|
+
self.modularity_ = float(
|
|
969
|
+
nx.community.modularity(G, [set(c) for c in comms], weight="weight", resolution=self.resolution)
|
|
970
|
+
)
|
|
971
|
+
return self
|