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/metrics.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Quality of low-dimensional maps.
|
|
4
|
+
|
|
5
|
+
Distance preservation
|
|
6
|
+
:func:`sammon_stress`, :func:`mds_stress`, :func:`residual_variance`.
|
|
7
|
+
Neighborhood preservation
|
|
8
|
+
:func:`trustworthiness_continuity` (Venna and Kaski 2001),
|
|
9
|
+
:func:`coranking_matrix` and the rank-based curves :func:`qnx_curve`,
|
|
10
|
+
:func:`rnx_curve`, :func:`lcmc_curve` with the scalar summary
|
|
11
|
+
:func:`auc_rnx` (Lee and Verleysen 2009; Lee, Peluffo-Ordóñez and Verleysen 2015).
|
|
12
|
+
Map topology
|
|
13
|
+
:func:`topographic_error`, :func:`topographic_product`.
|
|
14
|
+
|
|
15
|
+
All functions accept data matrices or, with ``precomputed=True``, distance
|
|
16
|
+
matrices, so that graph (geodesic) distances can serve as the reference in
|
|
17
|
+
the input space.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
from scipy.spatial.distance import squareform
|
|
24
|
+
|
|
25
|
+
from ._utils import EPS, as_data, pairwise_distances, ranks_from_distances
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"auc_rnx",
|
|
29
|
+
"coranking_matrix",
|
|
30
|
+
"lcmc_curve",
|
|
31
|
+
"mapping_quality",
|
|
32
|
+
"mds_stress",
|
|
33
|
+
"qnx_curve",
|
|
34
|
+
"residual_variance",
|
|
35
|
+
"rnx_curve",
|
|
36
|
+
"sammon_stress",
|
|
37
|
+
"topographic_error",
|
|
38
|
+
"topographic_product",
|
|
39
|
+
"trustworthiness_continuity",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _dist(A, precomputed):
|
|
44
|
+
if precomputed:
|
|
45
|
+
D = np.asarray(A, dtype=float)
|
|
46
|
+
if D.ndim != 2 or D.shape[0] != D.shape[1]:
|
|
47
|
+
raise ValueError("a precomputed distance matrix must be square")
|
|
48
|
+
return D
|
|
49
|
+
return pairwise_distances(as_data(A))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _pairs(Dh, Dl):
|
|
53
|
+
return squareform(Dh, checks=False), squareform(Dl, checks=False)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def sammon_stress(X_high, Y, *, precomputed: bool = False) -> float:
|
|
57
|
+
r"""Sammon stress :math:`E_S=\frac{1}{\sum_{i<j}d^*_{ij}}\sum_{i<j}\frac{(d^*_{ij}-d_{ij})^2}{d^*_{ij}}`."""
|
|
58
|
+
a, b = _pairs(_dist(X_high, precomputed), pairwise_distances(as_data(Y)))
|
|
59
|
+
a = np.maximum(a, EPS)
|
|
60
|
+
return float(((a - b) ** 2 / a).sum() / a.sum())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def mds_stress(X_high, Y, *, precomputed: bool = False) -> float:
|
|
64
|
+
r"""Normalized metric MDS stress :math:`\sum_{i<j}(d^*_{ij}-d_{ij})^2/\sum_{i<j}d^{*2}_{ij}`."""
|
|
65
|
+
a, b = _pairs(_dist(X_high, precomputed), pairwise_distances(as_data(Y)))
|
|
66
|
+
return float(((a - b) ** 2).sum() / max((a**2).sum(), EPS))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def residual_variance(X_high, Y, *, precomputed: bool = False) -> float:
|
|
70
|
+
r"""Residual variance :math:`1-R^2(\mathbf{D}^*_X,\mathbf{D}_Y)` (Tenenbaum et al. 2000)."""
|
|
71
|
+
a, b = _pairs(_dist(X_high, precomputed), pairwise_distances(as_data(Y)))
|
|
72
|
+
r = np.corrcoef(a, b)[0, 1]
|
|
73
|
+
return float(1.0 - r**2)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def coranking_matrix(X_high, Y, *, precomputed: bool = False) -> np.ndarray:
|
|
77
|
+
r"""Co-ranking matrix :math:`\mathbf{Q}` (Lee and Verleysen 2009).
|
|
78
|
+
|
|
79
|
+
:math:`Q_{hl}` is the number of ordered pairs :math:`(i,j)` for which
|
|
80
|
+
:math:`j` is the :math:`h`-th neighbor of :math:`i` in the input space and
|
|
81
|
+
the :math:`l`-th in the map (:math:`h,l=1,\dots,N-1`; returned 0-based).
|
|
82
|
+
Entries below the diagonal are "intrusions" (too close in the map), entries
|
|
83
|
+
above it "extrusions".
|
|
84
|
+
"""
|
|
85
|
+
Dh = _dist(X_high, precomputed)
|
|
86
|
+
Dl = pairwise_distances(as_data(Y))
|
|
87
|
+
N = len(Dh)
|
|
88
|
+
Rh = ranks_from_distances(Dh)
|
|
89
|
+
Rl = ranks_from_distances(Dl)
|
|
90
|
+
off = ~np.eye(N, dtype=bool)
|
|
91
|
+
h = Rh[off] - 1
|
|
92
|
+
l_ = Rl[off] - 1
|
|
93
|
+
Q = np.zeros((N - 1, N - 1), dtype=np.int64)
|
|
94
|
+
np.add.at(Q, (h, l_), 1)
|
|
95
|
+
return Q
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def trustworthiness_continuity(X_high, Y, k=10, *, precomputed: bool = False, Q=None):
|
|
99
|
+
r"""Trustworthiness :math:`M_1(k)` and continuity :math:`M_2(k)` (Venna and Kaski 2001).
|
|
100
|
+
|
|
101
|
+
.. math:: M_1(k)=1-\frac{2}{Nk(2N-3k-1)}\sum_i\sum_{j\in U_k(i)}(r(i,j)-k),\qquad
|
|
102
|
+
M_2(k)=1-\frac{2}{Nk(2N-3k-1)}\sum_i\sum_{j\in V_k(i)}(\hat r(i,j)-k),
|
|
103
|
+
|
|
104
|
+
where :math:`U_k(i)` are the map neighbors of :math:`i` that are not its
|
|
105
|
+
input-space neighbors (ranked :math:`r` in the input space) and
|
|
106
|
+
:math:`V_k(i)` the input-space neighbors missing from the map (ranked
|
|
107
|
+
:math:`\hat r` in the map). Low trustworthiness means false neighbors in
|
|
108
|
+
the display, low continuity means torn neighborhoods.
|
|
109
|
+
|
|
110
|
+
``k`` may be an int or a sequence; arrays are returned for sequences.
|
|
111
|
+
"""
|
|
112
|
+
if Q is None:
|
|
113
|
+
Q = coranking_matrix(X_high, Y, precomputed=precomputed)
|
|
114
|
+
N = Q.shape[0] + 1
|
|
115
|
+
ks = np.atleast_1d(k).astype(int)
|
|
116
|
+
ranks = np.arange(1, N)
|
|
117
|
+
T, C = [], []
|
|
118
|
+
for kk in ks:
|
|
119
|
+
norm = 2.0 / (N * kk * (2 * N - 3 * kk - 1))
|
|
120
|
+
# trust: high rank h > k, low rank l <= k -> penalty (h - k)
|
|
121
|
+
t = ((ranks[kk:, None] - kk) * Q[kk:, :kk]).sum()
|
|
122
|
+
c = ((ranks[None, kk:] - kk) * Q[:kk, kk:]).sum()
|
|
123
|
+
T.append(1 - norm * t)
|
|
124
|
+
C.append(1 - norm * c)
|
|
125
|
+
T, C = np.array(T), np.array(C)
|
|
126
|
+
if np.ndim(k) == 0:
|
|
127
|
+
return float(T[0]), float(C[0])
|
|
128
|
+
return T, C
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def qnx_curve(X_high=None, Y=None, *, precomputed: bool = False, Q=None) -> np.ndarray:
|
|
132
|
+
r""":math:`Q_{NX}(K)=\frac{1}{KN}\sum_{h,l\le K}Q_{hl}`, the average overlap of the K-ary neighborhoods, :math:`K=1..N-2`."""
|
|
133
|
+
if Q is None:
|
|
134
|
+
Q = coranking_matrix(X_high, Y, precomputed=precomputed)
|
|
135
|
+
N = Q.shape[0] + 1
|
|
136
|
+
cs = np.cumsum(np.cumsum(Q, 0), 1)
|
|
137
|
+
K = np.arange(1, N - 1)
|
|
138
|
+
return np.diag(cs)[: N - 2] / (K * N)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def rnx_curve(X_high=None, Y=None, *, precomputed: bool = False, Q=None) -> np.ndarray:
|
|
142
|
+
r""":math:`R_{NX}(K)=\frac{(N-1)Q_{NX}(K)-K}{N-1-K}`: neighborhood preservation rescaled so that a random map scores 0."""
|
|
143
|
+
q = qnx_curve(X_high, Y, precomputed=precomputed, Q=Q)
|
|
144
|
+
N = len(q) + 2
|
|
145
|
+
K = np.arange(1, N - 1)
|
|
146
|
+
return ((N - 1) * q - K) / (N - 1 - K)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def lcmc_curve(X_high=None, Y=None, *, precomputed: bool = False, Q=None) -> np.ndarray:
|
|
150
|
+
r"""Local continuity meta-criterion :math:`\mathrm{LCMC}(K)=Q_{NX}(K)-K/(N-1)` (Chen and Buja 2009)."""
|
|
151
|
+
q = qnx_curve(X_high, Y, precomputed=precomputed, Q=Q)
|
|
152
|
+
N = len(q) + 2
|
|
153
|
+
return q - np.arange(1, N - 1) / (N - 1)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def auc_rnx(X_high=None, Y=None, *, precomputed: bool = False, Q=None) -> float:
|
|
157
|
+
r"""Area under the :math:`R_{NX}(K)` curve with logarithmic K axis, :math:`\sum_K R_{NX}(K)/K\,/\sum_K 1/K`.
|
|
158
|
+
|
|
159
|
+
A single number in :math:`[0,1]` that weighs small neighborhoods more and
|
|
160
|
+
is the most common summary in recent comparisons of embeddings.
|
|
161
|
+
"""
|
|
162
|
+
r = rnx_curve(X_high, Y, precomputed=precomputed, Q=Q)
|
|
163
|
+
K = np.arange(1, len(r) + 1)
|
|
164
|
+
return float((r / K).sum() / (1.0 / K).sum())
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def mapping_quality(X_high, Y, *, k=(5, 10, 20), precomputed: bool = False) -> dict:
|
|
168
|
+
"""All distance- and neighborhood-preservation measures of a map in one dictionary."""
|
|
169
|
+
Dh = _dist(X_high, precomputed)
|
|
170
|
+
Q = coranking_matrix(Dh, Y, precomputed=True)
|
|
171
|
+
T, C = trustworthiness_continuity(None, None, list(k), Q=Q)
|
|
172
|
+
out = {
|
|
173
|
+
"sammon_stress": sammon_stress(Dh, Y, precomputed=True),
|
|
174
|
+
"mds_stress": mds_stress(Dh, Y, precomputed=True),
|
|
175
|
+
"residual_variance": residual_variance(Dh, Y, precomputed=True),
|
|
176
|
+
"auc_rnx": auc_rnx(Q=Q),
|
|
177
|
+
}
|
|
178
|
+
for kk, t, c in zip(k, T, C):
|
|
179
|
+
out[f"trustworthiness@{kk}"] = float(t)
|
|
180
|
+
out[f"continuity@{kk}"] = float(c)
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def topographic_error(X, nodes, map_adjacency) -> float:
|
|
185
|
+
r"""Share of samples whose two nearest nodes are not adjacent in the map graph (Kiviluoto 1996). 0 is perfect."""
|
|
186
|
+
X = as_data(X)
|
|
187
|
+
W = as_data(nodes)
|
|
188
|
+
A = np.asarray(map_adjacency.toarray() if hasattr(map_adjacency, "toarray") else map_adjacency) > 0
|
|
189
|
+
d2 = ((X[:, None, :] - W[None]) ** 2).sum(-1)
|
|
190
|
+
two = np.argsort(d2, axis=1)[:, :2]
|
|
191
|
+
return float(np.mean(~A[two[:, 0], two[:, 1]]))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def topographic_product(nodes, positions) -> float:
|
|
195
|
+
r"""Topographic product of Bauer and Pawelzik (1992) between node vectors and their map positions.
|
|
196
|
+
|
|
197
|
+
:math:`P=\frac{1}{n(n-1)}\sum_j\sum_{k=1}^{n-1}\log P_3(j,k)`. Values near
|
|
198
|
+
0 indicate a map dimension that matches the data; negative values a map
|
|
199
|
+
that is too small (folded), positive values one that is too large.
|
|
200
|
+
"""
|
|
201
|
+
W = as_data(nodes)
|
|
202
|
+
Z = as_data(positions)
|
|
203
|
+
n = len(W)
|
|
204
|
+
DV = pairwise_distances(W) + np.eye(n)
|
|
205
|
+
DA = pairwise_distances(Z) + np.eye(n)
|
|
206
|
+
nV = np.argsort(DV + np.diag(np.full(n, -np.inf)), axis=1)[:, 1:]
|
|
207
|
+
nA = np.argsort(DA + np.diag(np.full(n, -np.inf)), axis=1)[:, 1:]
|
|
208
|
+
rows = np.arange(n)[:, None]
|
|
209
|
+
q1 = np.log(np.maximum(DV[rows, nA], EPS) / np.maximum(DV[rows, nV], EPS))
|
|
210
|
+
q2 = np.log(np.maximum(DA[rows, nA], EPS) / np.maximum(DA[rows, nV], EPS))
|
|
211
|
+
cum = np.cumsum(q1 + q2, axis=1)
|
|
212
|
+
k = np.arange(1, n)
|
|
213
|
+
return float((cum / (2 * k)).sum() / (n * (n - 1)))
|
graphclust/plotting.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
"""Plotting helpers (matplotlib) with the color scheme used in the book."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from scipy.sparse import coo_matrix
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"PALETTE",
|
|
12
|
+
"plot_component_planes",
|
|
13
|
+
"plot_decision_graph",
|
|
14
|
+
"plot_dendrogram",
|
|
15
|
+
"plot_embedding",
|
|
16
|
+
"plot_graph",
|
|
17
|
+
"plot_partition",
|
|
18
|
+
"plot_quality_curves",
|
|
19
|
+
"plot_vat",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
#: Okabe--Ito colors (color-blind safe), the categorical palette of all figures.
|
|
23
|
+
PALETTE = ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00", "#56B4E9", "#F0E442", "#000000"]
|
|
24
|
+
NOISE = "#9AA5B1"
|
|
25
|
+
EDGE = "#6B7785"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _ax(ax, projection=None):
|
|
29
|
+
import matplotlib.pyplot as plt
|
|
30
|
+
|
|
31
|
+
if ax is None:
|
|
32
|
+
fig = plt.figure(figsize=(5, 4.2))
|
|
33
|
+
ax = fig.add_subplot(111, projection=projection)
|
|
34
|
+
return ax
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _colors(labels):
|
|
38
|
+
labels = np.asarray(labels)
|
|
39
|
+
cols = np.array([PALETTE[int(v) % len(PALETTE)] if v >= 0 else NOISE for v in labels])
|
|
40
|
+
return cols
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def plot_partition(X, labels, *, ax=None, s=18, title=None, markers=True):
|
|
44
|
+
"""Scatter plot of 2-D (or 3-D) data colored by cluster label (noise ``-1`` in gray)."""
|
|
45
|
+
X = np.asarray(X)
|
|
46
|
+
labels = np.asarray(labels)
|
|
47
|
+
proj = "3d" if X.shape[1] == 3 else None
|
|
48
|
+
ax = _ax(ax, proj)
|
|
49
|
+
mk = ["o", "s", "^", "D", "v", "P", "X", "*"]
|
|
50
|
+
for v in np.unique(labels):
|
|
51
|
+
m = labels == v
|
|
52
|
+
col = PALETTE[int(v) % len(PALETTE)] if v >= 0 else NOISE
|
|
53
|
+
kw = {"marker": mk[int(v) % len(mk)] if (markers and v >= 0) else "x" if v < 0 else "o"}
|
|
54
|
+
ax.scatter(*X[m].T, s=s, c=col, edgecolors="none" if kw["marker"] not in "x" else None, **kw)
|
|
55
|
+
if title:
|
|
56
|
+
ax.set_title(title)
|
|
57
|
+
if proj is None:
|
|
58
|
+
ax.set_aspect("equal", adjustable="datalim")
|
|
59
|
+
return ax
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def plot_graph(
|
|
63
|
+
positions, adjacency, *, X=None, labels=None, ax=None, node_size=14, title=None, edge_color=EDGE, lw=0.8
|
|
64
|
+
):
|
|
65
|
+
"""Draw a graph whose nodes have 2-D or 3-D ``positions``; optional data cloud ``X`` in the background."""
|
|
66
|
+
P = np.asarray(positions)
|
|
67
|
+
proj = "3d" if P.shape[1] == 3 else None
|
|
68
|
+
ax = _ax(ax, proj)
|
|
69
|
+
if X is not None:
|
|
70
|
+
ax.scatter(*np.asarray(X)[:, : P.shape[1]].T, s=3, c="#C9D3DD", edgecolors="none")
|
|
71
|
+
A = coo_matrix(adjacency)
|
|
72
|
+
keep = A.row < A.col
|
|
73
|
+
if proj is None:
|
|
74
|
+
from matplotlib.collections import LineCollection
|
|
75
|
+
|
|
76
|
+
segs = np.stack([P[A.row[keep]], P[A.col[keep]]], axis=1)
|
|
77
|
+
ax.add_collection(LineCollection(segs, colors=edge_color, linewidths=lw, zorder=1))
|
|
78
|
+
else:
|
|
79
|
+
for a, b in zip(A.row[keep], A.col[keep]):
|
|
80
|
+
ax.plot(*np.c_[P[a], P[b]], color=edge_color, lw=lw)
|
|
81
|
+
cols = _colors(labels) if labels is not None else PALETTE[0]
|
|
82
|
+
ax.scatter(*P.T, s=node_size, c=cols, zorder=2, edgecolors="white", linewidths=0.3)
|
|
83
|
+
if title:
|
|
84
|
+
ax.set_title(title)
|
|
85
|
+
if proj is None:
|
|
86
|
+
ax.set_aspect("equal", adjustable="datalim")
|
|
87
|
+
ax.autoscale_view()
|
|
88
|
+
return ax
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def plot_embedding(Y, labels=None, *, ax=None, s=12, title=None):
|
|
92
|
+
"""Scatter plot of a 2-D embedding colored by labels (or by a continuous value)."""
|
|
93
|
+
Y = np.asarray(Y)
|
|
94
|
+
ax = _ax(ax)
|
|
95
|
+
if labels is None:
|
|
96
|
+
ax.scatter(Y[:, 0], Y[:, 1], s=s, c=PALETTE[0], edgecolors="none")
|
|
97
|
+
elif np.issubdtype(np.asarray(labels).dtype, np.floating) and len(np.unique(labels)) > 12:
|
|
98
|
+
ax.scatter(Y[:, 0], Y[:, 1], s=s, c=labels, cmap="viridis", edgecolors="none")
|
|
99
|
+
else:
|
|
100
|
+
ax.scatter(Y[:, 0], Y[:, 1], s=s, c=_colors(labels), edgecolors="none")
|
|
101
|
+
ax.set_xticks([])
|
|
102
|
+
ax.set_yticks([])
|
|
103
|
+
if title:
|
|
104
|
+
ax.set_title(title)
|
|
105
|
+
return ax
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def plot_dendrogram(Z, *, ax=None, threshold=None, title=None, **kw):
|
|
109
|
+
"""SciPy dendrogram of a linkage matrix with an optional cut line."""
|
|
110
|
+
from scipy.cluster.hierarchy import dendrogram
|
|
111
|
+
|
|
112
|
+
ax = _ax(ax)
|
|
113
|
+
dendrogram(
|
|
114
|
+
Z, ax=ax, no_labels=True, color_threshold=threshold if threshold else 0, above_threshold_color=EDGE, **kw
|
|
115
|
+
)
|
|
116
|
+
if threshold is not None:
|
|
117
|
+
ax.axhline(threshold, color=PALETTE[1], ls="--", lw=1)
|
|
118
|
+
if title:
|
|
119
|
+
ax.set_title(title)
|
|
120
|
+
return ax
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def plot_vat(image, *, ax=None, title=None, cmap="gray"):
|
|
124
|
+
"""Show a (i)VAT image: dark diagonal blocks are clusters."""
|
|
125
|
+
ax = _ax(ax)
|
|
126
|
+
ax.imshow(image, cmap=cmap, interpolation="nearest")
|
|
127
|
+
ax.set_xticks([])
|
|
128
|
+
ax.set_yticks([])
|
|
129
|
+
if title:
|
|
130
|
+
ax.set_title(title)
|
|
131
|
+
return ax
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def plot_component_planes(positions, nodes, adjacency=None, *, feature_names=None, ncols=3, cmap="Greys", size=3.0):
|
|
135
|
+
"""Component planes: the map once per feature, nodes shaded by that feature of their codebook vector."""
|
|
136
|
+
import matplotlib.pyplot as plt
|
|
137
|
+
|
|
138
|
+
P = np.asarray(positions)
|
|
139
|
+
W = np.asarray(nodes)
|
|
140
|
+
D = W.shape[1]
|
|
141
|
+
nrows = int(np.ceil(D / ncols))
|
|
142
|
+
fig, axes = plt.subplots(nrows, min(ncols, D), figsize=(size * min(ncols, D), size * nrows * 0.9), squeeze=False)
|
|
143
|
+
for f in range(nrows * min(ncols, D)):
|
|
144
|
+
ax = axes.flat[f]
|
|
145
|
+
if f >= D:
|
|
146
|
+
ax.axis("off")
|
|
147
|
+
continue
|
|
148
|
+
if adjacency is not None:
|
|
149
|
+
plot_graph(P, adjacency, ax=ax, node_size=0, lw=0.5)
|
|
150
|
+
sc = ax.scatter(P[:, 0], P[:, 1], c=W[:, f], cmap=cmap, s=30, edgecolors=EDGE, linewidths=0.3, zorder=3)
|
|
151
|
+
ax.set_title(feature_names[f] if feature_names is not None else f"feature {f + 1}", fontsize=9)
|
|
152
|
+
ax.set_xticks([])
|
|
153
|
+
ax.set_yticks([])
|
|
154
|
+
ax.set_aspect("equal", adjustable="datalim")
|
|
155
|
+
fig.colorbar(sc, ax=ax, shrink=0.7)
|
|
156
|
+
fig.tight_layout()
|
|
157
|
+
return fig
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def plot_quality_curves(curves: dict, *, k=None, ax=None, ylabel="", title=None, logx=False):
|
|
161
|
+
"""Plot several quality curves (e.g. trustworthiness against k) given as ``{name: values}``."""
|
|
162
|
+
ax = _ax(ax)
|
|
163
|
+
for i, (name, vals) in enumerate(curves.items()):
|
|
164
|
+
x = np.arange(1, len(vals) + 1) if k is None else k
|
|
165
|
+
ax.plot(x, vals, label=name, color=PALETTE[i % len(PALETTE)], lw=1.6)
|
|
166
|
+
if logx:
|
|
167
|
+
ax.set_xscale("log")
|
|
168
|
+
ax.set_xlabel("k")
|
|
169
|
+
ax.set_ylabel(ylabel)
|
|
170
|
+
ax.legend(frameon=False, fontsize=8)
|
|
171
|
+
if title:
|
|
172
|
+
ax.set_title(title)
|
|
173
|
+
return ax
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def plot_decision_graph(rho, delta, centers=None, *, ax=None, title="decision graph"):
|
|
177
|
+
"""Density peaks decision graph (local density against distance to a denser sample)."""
|
|
178
|
+
ax = _ax(ax)
|
|
179
|
+
ax.scatter(rho, delta, s=10, c=EDGE, edgecolors="none")
|
|
180
|
+
if centers is not None:
|
|
181
|
+
ax.scatter(np.asarray(rho)[centers], np.asarray(delta)[centers], s=50, c=PALETTE[1], marker="*")
|
|
182
|
+
ax.set_xlabel(r"local density $\rho$")
|
|
183
|
+
ax.set_ylabel(r"distance to denser sample $\delta$")
|
|
184
|
+
ax.set_title(title)
|
|
185
|
+
return ax
|
graphclust/validity.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Cluster validity for graph-based clustering.
|
|
4
|
+
|
|
5
|
+
* :func:`dunn_mst_index` -- Dunn-like index with MST-based diameters (Pal and Biswas 1997);
|
|
6
|
+
* :func:`fukuyama_sugeno` -- compactness minus separation (Fukuyama and Sugeno 1989);
|
|
7
|
+
* :func:`fuzzy_hypervolume` -- total volume of the Gaussian clusters (Gath and Geva 1989);
|
|
8
|
+
* :func:`dbcv` -- density-based clustering validation on mutual reachability MSTs (Moulavi et al. 2014);
|
|
9
|
+
* :func:`clustering_rate` -- share of correctly grouped samples after optimal label matching;
|
|
10
|
+
* :func:`eigengap` -- number of clusters suggested by the spectrum of a graph.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from scipy.optimize import linear_sum_assignment
|
|
17
|
+
from scipy.sparse.csgraph import minimum_spanning_tree as _mst
|
|
18
|
+
|
|
19
|
+
from ._utils import EPS, as_data, pairwise_distances
|
|
20
|
+
from .fuzzy import fuzzy_covariances, fuzzy_hypervolume
|
|
21
|
+
|
|
22
|
+
__all__ = ["clustering_rate", "dbcv", "dunn_mst_index", "eigengap", "fukuyama_sugeno", "fuzzy_hypervolume"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clustering_rate(y_true, y_pred) -> float:
|
|
26
|
+
"""Fraction of samples in correctly matched clusters (Hungarian matching of the labels).
|
|
27
|
+
|
|
28
|
+
Noise labels (``-1``) in ``y_pred`` count as errors.
|
|
29
|
+
|
|
30
|
+
Examples
|
|
31
|
+
--------
|
|
32
|
+
>>> clustering_rate([0, 0, 1, 1], [1, 1, 0, 0])
|
|
33
|
+
1.0
|
|
34
|
+
"""
|
|
35
|
+
t = np.asarray(y_true)
|
|
36
|
+
p = np.asarray(y_pred)
|
|
37
|
+
ut, up = np.unique(t), np.unique(p[p >= 0])
|
|
38
|
+
if len(up) == 0:
|
|
39
|
+
return 0.0
|
|
40
|
+
C = np.array([[np.sum((t == a) & (p == b)) for b in up] for a in ut])
|
|
41
|
+
r, c = linear_sum_assignment(-C)
|
|
42
|
+
return float(C[r, c].sum() / len(t))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _mst_diameter(D):
|
|
46
|
+
"""Longest path (sum of weights) in the MST of a complete graph given by distance matrix D."""
|
|
47
|
+
n = len(D)
|
|
48
|
+
if n < 2:
|
|
49
|
+
return 0.0
|
|
50
|
+
T = _mst(np.where(D > 0, D, 1e-12) * (1 - np.eye(n))).toarray()
|
|
51
|
+
T = T + T.T
|
|
52
|
+
adj = [np.flatnonzero(T[i]) for i in range(n)]
|
|
53
|
+
|
|
54
|
+
def far(s):
|
|
55
|
+
dist = -np.ones(n)
|
|
56
|
+
dist[s] = 0
|
|
57
|
+
st = [s]
|
|
58
|
+
while st:
|
|
59
|
+
u = st.pop()
|
|
60
|
+
for v in adj[u]:
|
|
61
|
+
if dist[v] < 0:
|
|
62
|
+
dist[v] = dist[u] + T[u, v]
|
|
63
|
+
st.append(v)
|
|
64
|
+
return int(np.argmax(dist)), float(dist.max())
|
|
65
|
+
|
|
66
|
+
a, _ = far(0)
|
|
67
|
+
_, d = far(a)
|
|
68
|
+
return d
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def dunn_mst_index(X, labels) -> float:
|
|
72
|
+
r"""Dunn-like index with MST diameters: :math:`\min_{i\ne j}\delta(C_i,C_j)/\max_k\mathrm{diam}(C_k)`.
|
|
73
|
+
|
|
74
|
+
:math:`\delta` is the single-linkage distance of two clusters and the
|
|
75
|
+
diameter of a cluster is the length of the longest path in its minimal
|
|
76
|
+
spanning tree, which is insensitive to the shape of the cluster. Larger is
|
|
77
|
+
better; noise (``-1``) is ignored.
|
|
78
|
+
"""
|
|
79
|
+
X = as_data(X)
|
|
80
|
+
labels = np.asarray(labels)
|
|
81
|
+
D = pairwise_distances(X)
|
|
82
|
+
cl = [np.flatnonzero(labels == c) for c in np.unique(labels) if c >= 0]
|
|
83
|
+
if len(cl) < 2:
|
|
84
|
+
return np.nan
|
|
85
|
+
diam = max(_mst_diameter(D[np.ix_(c, c)]) for c in cl)
|
|
86
|
+
sep = min(D[np.ix_(a, b)].min() for i, a in enumerate(cl) for b in cl[i + 1 :])
|
|
87
|
+
return float(sep / max(diam, EPS))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def fukuyama_sugeno(X, U, m: float = 2.0) -> float:
|
|
91
|
+
r"""Fukuyama--Sugeno index :math:`\sum_k\sum_i\mu_{ik}^m(\|\mathbf{x}_k-\mathbf{v}_i\|^2-\|\mathbf{v}_i-\bar{\mathbf{v}}\|^2)`; smaller is better."""
|
|
92
|
+
X = as_data(X)
|
|
93
|
+
U = np.asarray(U, dtype=float)
|
|
94
|
+
V, _ = fuzzy_covariances(X, U, m)
|
|
95
|
+
vbar = X.mean(0)
|
|
96
|
+
d2 = ((X[:, None, :] - V[None]) ** 2).sum(-1)
|
|
97
|
+
sep = ((V - vbar) ** 2).sum(1)
|
|
98
|
+
return float((U**m * (d2 - sep[None, :])).sum())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _eigengap_from_values(vals, max_clusters):
|
|
102
|
+
"""Number of clusters from descending eigenvalues of the normalized affinity matrix."""
|
|
103
|
+
vals = np.sort(np.asarray(vals))[::-1][: max_clusters + 1]
|
|
104
|
+
mu = np.maximum(1.0 - vals, 0.0)
|
|
105
|
+
tiny = 1e-10 * max(mu.max(), EPS)
|
|
106
|
+
ratio = mu[2:] / np.maximum(mu[1:-1], tiny) # candidate c = 2, 3, ...
|
|
107
|
+
return int(np.argmax(ratio) + 2) if len(ratio) else 2
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def eigengap(affinity, max_clusters: int = 10) -> tuple[int, np.ndarray]:
|
|
111
|
+
r"""Number of clusters suggested by the spectrum of a graph, and the eigenvalues.
|
|
112
|
+
|
|
113
|
+
With :math:`\lambda_l` the eigenvalues of :math:`\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2}`
|
|
114
|
+
in decreasing order and :math:`\mu_l=1-\lambda_l` those of the normalized
|
|
115
|
+
Laplacian, :math:`c` clusters with few links between them give :math:`c`
|
|
116
|
+
eigenvalues :math:`\mu` near zero followed by a jump. The function returns
|
|
117
|
+
the :math:`c\ge2` with the largest ratio :math:`\mu_{c+1}/\mu_c` (a relative
|
|
118
|
+
gap, robust to the slow decay of the remaining spectrum).
|
|
119
|
+
"""
|
|
120
|
+
A = np.asarray(affinity, dtype=float).copy()
|
|
121
|
+
np.fill_diagonal(A, 0.0)
|
|
122
|
+
d = 1.0 / np.sqrt(np.maximum(A.sum(1), EPS))
|
|
123
|
+
vals = np.sort(np.linalg.eigvalsh(d[:, None] * A * d[None, :]))[::-1][: max_clusters + 1]
|
|
124
|
+
return _eigengap_from_values(vals, max_clusters), vals
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def dbcv(X, labels) -> float:
|
|
128
|
+
r"""Density-based clustering validation (DBCV; Moulavi, Jaskowiak, Campello, Zimek and Sander 2014).
|
|
129
|
+
|
|
130
|
+
Within each cluster the *all-points core distance*
|
|
131
|
+
:math:`a(\mathbf{x})=\big(\frac{1}{n_i-1}\sum_{\mathbf{y}\ne\mathbf{x}}
|
|
132
|
+
d(\mathbf{x},\mathbf{y})^{-D}\big)^{-1/D}` defines mutual reachability
|
|
133
|
+
distances and an MST. The *density sparseness* of a cluster is the
|
|
134
|
+
largest internal MST edge, the *density separation* of two clusters the
|
|
135
|
+
smallest mutual reachability distance between their internal nodes. The
|
|
136
|
+
validity of a cluster is :math:`(\mathrm{sep}-\mathrm{sparse})/\max(\mathrm{sep},\mathrm{sparse})`
|
|
137
|
+
and DBCV is their size-weighted mean (noise counted in the total).
|
|
138
|
+
Range :math:`[-1,1]`, larger is better; unlike centroid-based indices it
|
|
139
|
+
rewards arbitrarily shaped, density-separated clusters.
|
|
140
|
+
"""
|
|
141
|
+
X = as_data(X)
|
|
142
|
+
labels = np.asarray(labels)
|
|
143
|
+
N, Dm = X.shape
|
|
144
|
+
D = pairwise_distances(X)
|
|
145
|
+
D[D == 0] = 1e-12
|
|
146
|
+
np.fill_diagonal(D, 0.0)
|
|
147
|
+
clusters = [c for c in np.unique(labels) if c >= 0]
|
|
148
|
+
if len(clusters) < 2:
|
|
149
|
+
return np.nan
|
|
150
|
+
core = np.zeros(N)
|
|
151
|
+
internal = {}
|
|
152
|
+
sparse = {}
|
|
153
|
+
for c in clusters:
|
|
154
|
+
idx = np.flatnonzero(labels == c)
|
|
155
|
+
if len(idx) < 2:
|
|
156
|
+
core[idx] = 0.0
|
|
157
|
+
internal[c] = idx
|
|
158
|
+
sparse[c] = 0.0
|
|
159
|
+
continue
|
|
160
|
+
Dc = D[np.ix_(idx, idx)]
|
|
161
|
+
with np.errstate(divide="ignore"):
|
|
162
|
+
inv = np.where(Dc > 0, Dc ** (-Dm), 0.0)
|
|
163
|
+
core[idx] = (inv.sum(1) / (len(idx) - 1)) ** (-1.0 / Dm)
|
|
164
|
+
M = np.maximum(Dc, np.maximum(core[idx][:, None], core[idx][None, :]))
|
|
165
|
+
np.fill_diagonal(M, 0.0)
|
|
166
|
+
T = _mst(M).toarray()
|
|
167
|
+
T = np.maximum(T, T.T)
|
|
168
|
+
deg = (T > 0).sum(1)
|
|
169
|
+
inner = deg > 1
|
|
170
|
+
internal[c] = idx[inner] if inner.any() else idx
|
|
171
|
+
Ti = T[np.ix_(inner, inner)] if inner.sum() > 1 else T
|
|
172
|
+
sparse[c] = float(Ti.max()) if Ti.size and Ti.max() > 0 else float(T.max())
|
|
173
|
+
score = 0.0
|
|
174
|
+
for c in clusters:
|
|
175
|
+
sep = np.inf
|
|
176
|
+
for o in clusters:
|
|
177
|
+
if o == c:
|
|
178
|
+
continue
|
|
179
|
+
a, b = internal[c], internal[o]
|
|
180
|
+
M = np.maximum(D[np.ix_(a, b)], np.maximum(core[a][:, None], core[b][None, :]))
|
|
181
|
+
sep = min(sep, float(M.min()))
|
|
182
|
+
v = (sep - sparse[c]) / max(sep, sparse[c], EPS)
|
|
183
|
+
score += (labels == c).sum() / N * v
|
|
184
|
+
return float(score)
|
graphclust/vat.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Visual assessment of cluster tendency.
|
|
4
|
+
|
|
5
|
+
:func:`vat` (Bezdek and Hathaway 2002) reorders a dissimilarity matrix along
|
|
6
|
+
the order in which Prim's algorithm adds the samples to the minimal spanning
|
|
7
|
+
tree; clusters then appear as dark blocks on the diagonal of the image.
|
|
8
|
+
:func:`ivat` (Havens and Bezdek 2012) replaces every dissimilarity by the
|
|
9
|
+
largest edge on the MST path between the two samples (the minimax path
|
|
10
|
+
distance), which sharpens the blocks considerably for elongated or
|
|
11
|
+
chained clusters. Both work on any dissimilarity, e.g. Euclidean, geodesic
|
|
12
|
+
or fuzzy neighborhood distances.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
__all__ = ["ivat", "vat", "vat_order"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def vat_order(D) -> tuple[np.ndarray, np.ndarray]:
|
|
23
|
+
"""VAT ordering (Prim's order starting from an end point of the largest dissimilarity) and the
|
|
24
|
+
MST edge weight by which every sample was attached (``0`` for the first)."""
|
|
25
|
+
D = np.asarray(D, dtype=float)
|
|
26
|
+
n = len(D)
|
|
27
|
+
i, _ = np.unravel_index(np.argmax(D), D.shape)
|
|
28
|
+
order = [int(i)]
|
|
29
|
+
attach = [0.0]
|
|
30
|
+
in_tree = np.zeros(n, bool)
|
|
31
|
+
in_tree[i] = True
|
|
32
|
+
best = D[i].copy()
|
|
33
|
+
best[in_tree] = np.inf
|
|
34
|
+
for _ in range(n - 1):
|
|
35
|
+
j = int(np.argmin(best))
|
|
36
|
+
order.append(j)
|
|
37
|
+
attach.append(float(best[j]))
|
|
38
|
+
in_tree[j] = True
|
|
39
|
+
best = np.minimum(best, D[j])
|
|
40
|
+
best[in_tree] = np.inf
|
|
41
|
+
return np.array(order), np.array(attach)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def vat(D) -> tuple[np.ndarray, np.ndarray]:
|
|
45
|
+
"""Reordered dissimilarity image and the permutation.
|
|
46
|
+
|
|
47
|
+
Examples
|
|
48
|
+
--------
|
|
49
|
+
>>> import numpy as np
|
|
50
|
+
>>> D = np.abs(np.subtract.outer([0, 5, 1, 6], [0, 5, 1, 6])).astype(float)
|
|
51
|
+
>>> vat(D)[1].tolist()
|
|
52
|
+
[0, 2, 1, 3]
|
|
53
|
+
"""
|
|
54
|
+
D = np.asarray(D, dtype=float)
|
|
55
|
+
p, _ = vat_order(D)
|
|
56
|
+
return D[np.ix_(p, p)], p
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def ivat(D) -> tuple[np.ndarray, np.ndarray]:
|
|
60
|
+
r"""Improved VAT image: minimax (largest MST edge on the path) distances in VAT order."""
|
|
61
|
+
D = np.asarray(D, dtype=float)
|
|
62
|
+
p, _ = vat_order(D)
|
|
63
|
+
R = D[np.ix_(p, p)]
|
|
64
|
+
n = len(R)
|
|
65
|
+
out = np.zeros_like(R)
|
|
66
|
+
for r in range(1, n):
|
|
67
|
+
j = int(np.argmin(R[r, :r]))
|
|
68
|
+
out[r, :r] = np.maximum(R[r, j], out[j, :r])
|
|
69
|
+
out[r, j] = R[r, j]
|
|
70
|
+
out[:r, r] = out[r, :r]
|
|
71
|
+
return out, p
|