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/datasets.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Benchmark data for graph-based clustering and visualization.
|
|
4
|
+
|
|
5
|
+
Synthetic generators (all return ``X, y`` and take ``random_state``):
|
|
6
|
+
|
|
7
|
+
* :func:`make_variety` -- three clusters of different size, shape and density plus one outlier;
|
|
8
|
+
* :func:`make_chainlink` -- three compact clusters, two of them joined by a thin chain;
|
|
9
|
+
* :func:`make_curves` -- four curved, nearly touching clusters;
|
|
10
|
+
* :func:`make_s_curve`, :func:`make_swiss_roll` -- 2-D manifolds embedded in 3-D;
|
|
11
|
+
* :func:`make_boxlinecircle` -- a noisy cube, a bent line and a circle (shapes of different dimension).
|
|
12
|
+
|
|
13
|
+
:func:`load_boxlinecircle` returns the original 7100-point data set of the
|
|
14
|
+
authors (shipped with the package). Real data sets come from scikit-learn:
|
|
15
|
+
:func:`load_iris`, :func:`load_wine`, :func:`load_breast_cancer`,
|
|
16
|
+
:func:`load_digits`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from importlib import resources
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from ._utils import check_random_state, minmax_scale
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"load_boxlinecircle",
|
|
29
|
+
"load_breast_cancer",
|
|
30
|
+
"load_digits",
|
|
31
|
+
"load_iris",
|
|
32
|
+
"load_wine",
|
|
33
|
+
"make_boxlinecircle",
|
|
34
|
+
"make_chainlink",
|
|
35
|
+
"make_curves",
|
|
36
|
+
"make_s_curve",
|
|
37
|
+
"make_swiss_roll",
|
|
38
|
+
"make_variety",
|
|
39
|
+
"minmax_scale",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def make_variety(random_state=0, normalize=True):
|
|
44
|
+
"""Variety data: 100 points in 2-D, clusters of 22 (dense, round), 26 (elongated) and 51 (sparse) points and one outlier.
|
|
45
|
+
|
|
46
|
+
The clusters differ in size, shape and density at the same time, which
|
|
47
|
+
defeats k-means and fixed-threshold neighborhood methods; the outlier
|
|
48
|
+
lies between the groups and should be found as a group of its own (label 3).
|
|
49
|
+
"""
|
|
50
|
+
rng = check_random_state(random_state)
|
|
51
|
+
a = rng.normal([0.2, 0.25], 0.035, size=(22, 2))
|
|
52
|
+
t = rng.uniform(-1, 1, 26)
|
|
53
|
+
b = np.column_stack([0.25 + 0.18 * t, 0.75 + 0.06 * t]) + rng.normal(0, 0.012, (26, 2))
|
|
54
|
+
c = rng.uniform([0.55, 0.45], [0.95, 0.95], size=(51, 2))
|
|
55
|
+
o = np.array([[0.5, 0.3]])
|
|
56
|
+
X = np.vstack([a, b, c, o])
|
|
57
|
+
y = np.r_[np.zeros(22), np.ones(26), 2 * np.ones(51), [3]].astype(int)
|
|
58
|
+
return (minmax_scale(X) if normalize else X), y
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def make_chainlink(random_state=0, normalize=True):
|
|
62
|
+
"""ChainLink data: 75 points in 2-D -- three compact clusters, two of which are joined by a chain of points.
|
|
63
|
+
|
|
64
|
+
The chain keeps every minimal spanning tree edge short, so single linkage
|
|
65
|
+
and length-based MST cutting merge the two clusters (chaining effect).
|
|
66
|
+
Labels: clusters 0, 1, 2 and the chain 3.
|
|
67
|
+
"""
|
|
68
|
+
rng = check_random_state(random_state)
|
|
69
|
+
c1 = rng.normal([0.15, 0.5], 0.05, (20, 2))
|
|
70
|
+
c2 = rng.normal([0.85, 0.5], 0.05, (20, 2))
|
|
71
|
+
c3 = rng.normal([0.5, 0.12], 0.04, (20, 2))
|
|
72
|
+
s = np.linspace(0.27, 0.73, 15)
|
|
73
|
+
chain = np.column_stack([s, 0.5 + 0.008 * rng.normal(size=15)])
|
|
74
|
+
X = np.vstack([c1, c2, c3, chain])
|
|
75
|
+
y = np.r_[np.zeros(20), np.ones(20), 2 * np.ones(20), 3 * np.ones(15)].astype(int)
|
|
76
|
+
return (minmax_scale(X) if normalize else X), y
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def make_curves(random_state=0, normalize=True):
|
|
80
|
+
"""Curves data: 267 points in 2-D forming four curved clusters of different size that nearly touch.
|
|
81
|
+
|
|
82
|
+
Two pairs of interleaved half-circles; the gap between neighboring curves
|
|
83
|
+
is only slightly larger than the spacing of the points along a curve, so
|
|
84
|
+
that distance thresholds and prototype methods both struggle.
|
|
85
|
+
"""
|
|
86
|
+
rng = check_random_state(random_state)
|
|
87
|
+
specs = [ # center, radius, angle range, count
|
|
88
|
+
((0.0, 0.0), 1.0, (0.0, np.pi), 70),
|
|
89
|
+
((1.0, 0.45), 1.0, (np.pi, 2 * np.pi), 55),
|
|
90
|
+
((3.6, 0.2), 0.8, (0.0, np.pi), 80),
|
|
91
|
+
((4.4, 0.55), 0.8, (np.pi, 2 * np.pi), 62),
|
|
92
|
+
]
|
|
93
|
+
parts, labels = [], []
|
|
94
|
+
for lab, (c, r, (a0, a1), n) in enumerate(specs):
|
|
95
|
+
th = np.linspace(a0, a1, n) + rng.normal(0, 0.15 * (a1 - a0) / n, n)
|
|
96
|
+
rr = r + rng.normal(0, 0.04, n)
|
|
97
|
+
parts.append(np.column_stack([c[0] + rr * np.cos(th), c[1] + rr * np.sin(th)]))
|
|
98
|
+
labels.append(np.full(n, lab))
|
|
99
|
+
X = np.vstack(parts)
|
|
100
|
+
y = np.concatenate(labels)
|
|
101
|
+
return (minmax_scale(X) if normalize else X), y
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def make_s_curve(n_samples=2000, noise=0.0, random_state=0):
|
|
105
|
+
"""S-curve manifold (scikit-learn generator); ``y`` is the position along the curve."""
|
|
106
|
+
from sklearn.datasets import make_s_curve as _s
|
|
107
|
+
|
|
108
|
+
return _s(n_samples, noise=noise, random_state=random_state)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def make_swiss_roll(n_samples=2000, noise=0.0, random_state=0):
|
|
112
|
+
"""Swiss roll manifold (scikit-learn generator); ``y`` is the position along the roll."""
|
|
113
|
+
from sklearn.datasets import make_swiss_roll as _sr
|
|
114
|
+
|
|
115
|
+
return _sr(n_samples, noise=noise, random_state=random_state)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def make_boxlinecircle(n_box=5000, n_line=1100, n_circle=1000, random_state=0):
|
|
119
|
+
"""A noisy cube, a bent line and a circle in 3-D (shapes of dimension 3, 1 and 1). Labels 0, 1, 2."""
|
|
120
|
+
rng = check_random_state(random_state)
|
|
121
|
+
box = rng.uniform(-6, 6, (n_box, 3))
|
|
122
|
+
s = rng.uniform(0, 1, n_line)
|
|
123
|
+
knee = s < 0.5
|
|
124
|
+
line = np.where(
|
|
125
|
+
knee[:, None],
|
|
126
|
+
np.column_stack([6 + 16 * s, np.zeros_like(s), np.zeros_like(s)]),
|
|
127
|
+
np.column_stack([14 + 0 * s, 12 * (s - 0.5), 12 * (s - 0.5)]),
|
|
128
|
+
) + rng.normal(0, 0.05, (n_line, 3))
|
|
129
|
+
th = rng.uniform(0, 2 * np.pi, n_circle)
|
|
130
|
+
circle = np.column_stack([20 + 2.5 * np.cos(th), 2.5 * np.sin(th), 2.5 * np.sin(th)]) + rng.normal(
|
|
131
|
+
0, 0.05, (n_circle, 3)
|
|
132
|
+
)
|
|
133
|
+
X = np.vstack([box, line, circle])
|
|
134
|
+
y = np.r_[np.zeros(n_box), np.ones(n_line), 2 * np.ones(n_circle)].astype(int)
|
|
135
|
+
return X, y
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def load_boxlinecircle():
|
|
139
|
+
"""The original 'boxlinecircle' data of Vathy-Fogarassy and Abonyi (7100 x 3; no labels)."""
|
|
140
|
+
with resources.files("graphclust.data").joinpath("boxlinecircle.txt").open() as fh:
|
|
141
|
+
return np.loadtxt(fh)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _sk(name):
|
|
145
|
+
import sklearn.datasets as d
|
|
146
|
+
|
|
147
|
+
b = getattr(d, name)()
|
|
148
|
+
return b.data.astype(float), b.target.astype(int)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def load_iris():
|
|
152
|
+
"""Iris flowers (150 x 4, 3 classes)."""
|
|
153
|
+
return _sk("load_iris")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def load_wine():
|
|
157
|
+
"""Wine recognition data (178 x 13, 3 cultivars)."""
|
|
158
|
+
return _sk("load_wine")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def load_breast_cancer():
|
|
162
|
+
"""Wisconsin diagnostic breast cancer data (569 x 30, 2 classes) as shipped with scikit-learn.
|
|
163
|
+
|
|
164
|
+
The 2013 book used the older 9-attribute Wisconsin *original* data set
|
|
165
|
+
(683 complete records); the diagnostic version is its widely used
|
|
166
|
+
successor and gives qualitatively the same picture.
|
|
167
|
+
"""
|
|
168
|
+
return _sk("load_breast_cancer")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def load_digits():
|
|
172
|
+
"""Handwritten digits (1797 x 64, 10 classes), a stand-in for the Semeion digits of the book."""
|
|
173
|
+
return _sk("load_digits")
|
graphclust/fuzzy.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Gath--Geva fuzzy maximum likelihood clustering, used to give MST clusters a Gaussian description.
|
|
4
|
+
|
|
5
|
+
The implementation follows the conventions of the companion package
|
|
6
|
+
``fuzzyclust`` (same symbols, memberships stored as an
|
|
7
|
+
``(n_samples, n_clusters)`` matrix) but is self-contained, so that
|
|
8
|
+
graphclust has no dependency on it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from scipy.special import logsumexp
|
|
15
|
+
from sklearn.base import BaseEstimator, ClusterMixin
|
|
16
|
+
from sklearn.utils.validation import check_is_fitted
|
|
17
|
+
|
|
18
|
+
from ._utils import EPS, as_data, check_random_state
|
|
19
|
+
|
|
20
|
+
__all__ = ["GathGeva", "fuzzy_covariances", "fuzzy_hypervolume", "labels_to_membership"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def labels_to_membership(labels, n_clusters=None) -> np.ndarray:
|
|
24
|
+
"""Crisp labels to a 0/1 membership matrix of shape (n_samples, n_clusters)."""
|
|
25
|
+
labels = np.asarray(labels, dtype=int)
|
|
26
|
+
c = int(n_clusters or labels.max() + 1)
|
|
27
|
+
U = np.zeros((len(labels), c))
|
|
28
|
+
U[np.arange(len(labels)), labels] = 1.0
|
|
29
|
+
return U
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fuzzy_covariances(X, U, m: float = 1.0):
|
|
33
|
+
r"""Centers :math:`\mathbf{v}_i` and fuzzy covariance matrices
|
|
34
|
+
|
|
35
|
+
.. math:: \mathbf{F}_i=\frac{\sum_k\mu_{ik}^m(\mathbf{x}_k-\mathbf{v}_i)(\mathbf{x}_k-\mathbf{v}_i)^T}{\sum_k\mu_{ik}^m}.
|
|
36
|
+
|
|
37
|
+
With a crisp partition (``U`` from :func:`labels_to_membership`) and
|
|
38
|
+
``m = 1`` these are the cluster means and (biased) covariance matrices.
|
|
39
|
+
"""
|
|
40
|
+
X = as_data(X)
|
|
41
|
+
Um = np.asarray(U, dtype=float) ** m
|
|
42
|
+
s = Um.sum(0) + EPS
|
|
43
|
+
V = (Um.T @ X) / s[:, None]
|
|
44
|
+
F = np.empty((U.shape[1], X.shape[1], X.shape[1]))
|
|
45
|
+
for i in range(U.shape[1]):
|
|
46
|
+
R = X - V[i]
|
|
47
|
+
F[i] = (Um[:, i, None] * R).T @ R / s[i]
|
|
48
|
+
return V, F
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fuzzy_hypervolume(X, U, m: float = 1.0, *, per_cluster: bool = False):
|
|
52
|
+
r"""Fuzzy hypervolume :math:`\mathrm{FHV}=\sum_i\sqrt{\det\mathbf{F}_i}` (Gath and Geva 1989); smaller is better."""
|
|
53
|
+
_, F = fuzzy_covariances(X, U, m)
|
|
54
|
+
vol = np.sqrt(np.maximum([np.linalg.det(Fi) for Fi in F], 0.0))
|
|
55
|
+
return vol if per_cluster else float(vol.sum())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class GathGeva(ClusterMixin, BaseEstimator):
|
|
59
|
+
r"""Gath--Geva (fuzzy maximum likelihood estimates) clustering.
|
|
60
|
+
|
|
61
|
+
The distance of sample :math:`k` from cluster :math:`i` is inversely
|
|
62
|
+
proportional to the Gaussian likelihood,
|
|
63
|
+
|
|
64
|
+
.. math:: D^2_{ik}=\frac{\sqrt{\det\mathbf{F}_i}}{\alpha_i}\exp\!\Big(\tfrac12
|
|
65
|
+
(\mathbf{x}_k-\mathbf{v}_i)^T\mathbf{F}_i^{-1}(\mathbf{x}_k-\mathbf{v}_i)\Big),
|
|
66
|
+
|
|
67
|
+
with prior :math:`\alpha_i=\frac1N\sum_k\mu_{ik}`, and the memberships are
|
|
68
|
+
:math:`\mu_{ik}=1/\sum_j(D_{ik}/D_{jk})^{2/(m-1)}` (all evaluated in the log
|
|
69
|
+
domain). GG is very sensitive to its initial partition, which is why the
|
|
70
|
+
hybrid MST algorithm supplies one.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
n_clusters : int, default=3
|
|
75
|
+
m : float, default=2.0
|
|
76
|
+
tol : float, default=1e-4
|
|
77
|
+
Stop when the largest membership change is below ``tol``.
|
|
78
|
+
max_iter : int, default=100
|
|
79
|
+
init : ndarray (n_samples, n_clusters) or "random", default="random"
|
|
80
|
+
Initial membership matrix (rows are normalized).
|
|
81
|
+
reg : float, default=1e-6
|
|
82
|
+
Ridge added to the covariance matrices (relative to their trace).
|
|
83
|
+
random_state : int, RandomState or None
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, n_clusters=3, *, m=2.0, tol=1e-4, max_iter=100, init="random", reg=1e-6, random_state=None):
|
|
87
|
+
self.n_clusters = n_clusters
|
|
88
|
+
self.m = m
|
|
89
|
+
self.tol = tol
|
|
90
|
+
self.max_iter = max_iter
|
|
91
|
+
self.init = init
|
|
92
|
+
self.reg = reg
|
|
93
|
+
self.random_state = random_state
|
|
94
|
+
|
|
95
|
+
def _log_d2(self, X):
|
|
96
|
+
N, D = X.shape
|
|
97
|
+
out = np.empty((N, self.n_clusters_))
|
|
98
|
+
for i in range(self.n_clusters_):
|
|
99
|
+
Fi = self.covariances_[i]
|
|
100
|
+
sign, logdet = np.linalg.slogdet(Fi)
|
|
101
|
+
R = X - self.cluster_centers_[i]
|
|
102
|
+
maha = np.einsum("kd,de,ke->k", R, np.linalg.inv(Fi), R)
|
|
103
|
+
out[:, i] = 0.5 * logdet - np.log(self.priors_[i]) + 0.5 * maha
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
def _memberships(self, logd2):
|
|
107
|
+
expo = 1.0 / (self.m - 1.0) if self.m > 1 else 1.0
|
|
108
|
+
z = -expo * logd2
|
|
109
|
+
return np.exp(z - logsumexp(z, axis=1, keepdims=True))
|
|
110
|
+
|
|
111
|
+
def _m_step(self, X, U):
|
|
112
|
+
V, F = fuzzy_covariances(X, U, self.m)
|
|
113
|
+
D = X.shape[1]
|
|
114
|
+
for i in range(len(F)):
|
|
115
|
+
F[i] += (self.reg * max(np.trace(F[i]) / D, EPS) + EPS) * np.eye(D)
|
|
116
|
+
self.cluster_centers_ = V
|
|
117
|
+
self.covariances_ = F
|
|
118
|
+
self.priors_ = np.maximum(U.mean(0), EPS)
|
|
119
|
+
|
|
120
|
+
def fit(self, X, y=None):
|
|
121
|
+
X = as_data(X)
|
|
122
|
+
N = len(X)
|
|
123
|
+
if isinstance(self.init, np.ndarray):
|
|
124
|
+
U = np.array(self.init, dtype=float)
|
|
125
|
+
if U.shape != (N, self.n_clusters):
|
|
126
|
+
raise ValueError("init must be a membership matrix of shape (n_samples, n_clusters)")
|
|
127
|
+
else:
|
|
128
|
+
rng = check_random_state(self.random_state)
|
|
129
|
+
U = rng.random_sample((N, self.n_clusters))
|
|
130
|
+
U = U / U.sum(1, keepdims=True)
|
|
131
|
+
self.n_clusters_ = self.n_clusters
|
|
132
|
+
it = 0
|
|
133
|
+
for it in range(1, self.max_iter + 1): # noqa: B007
|
|
134
|
+
self._m_step(X, U)
|
|
135
|
+
U_new = self._memberships(self._log_d2(X))
|
|
136
|
+
delta = np.abs(U_new - U).max()
|
|
137
|
+
U = U_new
|
|
138
|
+
if delta < self.tol:
|
|
139
|
+
break
|
|
140
|
+
self._m_step(X, U)
|
|
141
|
+
self.membership_ = U
|
|
142
|
+
self.labels_ = U.argmax(1)
|
|
143
|
+
self.n_iter_ = it
|
|
144
|
+
self.n_features_in_ = X.shape[1]
|
|
145
|
+
return self
|
|
146
|
+
|
|
147
|
+
def predict_proba(self, X):
|
|
148
|
+
check_is_fitted(self, "membership_")
|
|
149
|
+
return self._memberships(self._log_d2(as_data(X)))
|
|
150
|
+
|
|
151
|
+
def predict(self, X):
|
|
152
|
+
return self.predict_proba(X).argmax(1)
|
graphclust/graphs.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
|
|
3
|
+
r"""Graphs built from data: neighborhood graphs, spanning trees and graph distances.
|
|
4
|
+
|
|
5
|
+
Every function returns a symmetric :class:`scipy.sparse.csr_matrix` whose
|
|
6
|
+
entry :math:`(i,j)` is the Euclidean length of the edge between samples
|
|
7
|
+
:math:`\mathbf{x}_i` and :math:`\mathbf{x}_j` (zero means "no edge"). This is
|
|
8
|
+
the format of :mod:`scipy.sparse.csgraph`, so shortest paths, connected
|
|
9
|
+
components and spanning trees can be computed directly; :func:`to_networkx`
|
|
10
|
+
converts the result for community detection or drawing.
|
|
11
|
+
|
|
12
|
+
The proximity graphs form the classical chain
|
|
13
|
+
|
|
14
|
+
.. math:: \mathrm{NNG}\subseteq\mathrm{MST}\subseteq\mathrm{RNG}\subseteq
|
|
15
|
+
\mathrm{GG}\subseteq\mathrm{DT},
|
|
16
|
+
|
|
17
|
+
which :func:`neighborhood_chain` verifies on a data set.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
from scipy.sparse import coo_matrix, csr_matrix
|
|
24
|
+
from scipy.sparse.csgraph import connected_components, shortest_path
|
|
25
|
+
from scipy.sparse.csgraph import minimum_spanning_tree as _csgraph_mst
|
|
26
|
+
from scipy.spatial import Delaunay
|
|
27
|
+
from sklearn.neighbors import NearestNeighbors
|
|
28
|
+
|
|
29
|
+
from ._utils import as_data, pairwise_distances
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"competitive_hebbian_graph",
|
|
33
|
+
"connect_components",
|
|
34
|
+
"delaunay_graph",
|
|
35
|
+
"edges_of",
|
|
36
|
+
"epsilon_graph",
|
|
37
|
+
"gabriel_graph",
|
|
38
|
+
"geodesic_distances",
|
|
39
|
+
"knn_graph",
|
|
40
|
+
"knn_indices",
|
|
41
|
+
"minimum_spanning_tree",
|
|
42
|
+
"mutual_knn_graph",
|
|
43
|
+
"nearest_neighbor_graph",
|
|
44
|
+
"neighborhood_chain",
|
|
45
|
+
"relative_neighborhood_graph",
|
|
46
|
+
"shared_neighbor_counts",
|
|
47
|
+
"to_networkx",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# --------------------------------------------------------------------------- helpers
|
|
52
|
+
def _symmetric_from_edges(i, j, w, n) -> csr_matrix:
|
|
53
|
+
i = np.asarray(i, dtype=int)
|
|
54
|
+
j = np.asarray(j, dtype=int)
|
|
55
|
+
w = np.asarray(w, dtype=float)
|
|
56
|
+
keep = i != j
|
|
57
|
+
i, j, w = i[keep], j[keep], w[keep]
|
|
58
|
+
# tiny positive weight for coincident points so that the edge is not lost
|
|
59
|
+
w = np.where(w > 0, w, 1e-12)
|
|
60
|
+
a, b = np.minimum(i, j), np.maximum(i, j)
|
|
61
|
+
if len(a) == 0:
|
|
62
|
+
return csr_matrix((n, n))
|
|
63
|
+
key = a * n + b
|
|
64
|
+
order = np.lexsort((-w, key))
|
|
65
|
+
key, w = key[order], w[order]
|
|
66
|
+
first = np.r_[True, key[1:] != key[:-1]] # one entry per pair (largest weight)
|
|
67
|
+
key, w = key[first], w[first]
|
|
68
|
+
a, b = key // n, key % n
|
|
69
|
+
return coo_matrix((np.r_[w, w], (np.r_[a, b], np.r_[b, a])), shape=(n, n)).tocsr()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def edges_of(A) -> tuple[np.ndarray, np.ndarray]:
|
|
73
|
+
"""Undirected edge list ``(edges, weights)`` of a symmetric sparse graph (each edge once, i < j)."""
|
|
74
|
+
A = coo_matrix(A)
|
|
75
|
+
keep = A.row < A.col
|
|
76
|
+
edges = np.column_stack([A.row[keep], A.col[keep]])
|
|
77
|
+
order = np.lexsort((edges[:, 1], edges[:, 0])) if len(edges) else np.arange(0)
|
|
78
|
+
return edges[order], np.asarray(A.data[keep], dtype=float)[order]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def to_networkx(A, positions=None):
|
|
82
|
+
"""Convert a sparse adjacency matrix to a :class:`networkx.Graph` (edge attribute ``weight``)."""
|
|
83
|
+
import networkx as nx
|
|
84
|
+
|
|
85
|
+
G = nx.Graph()
|
|
86
|
+
G.add_nodes_from(range(A.shape[0]))
|
|
87
|
+
edges, w = edges_of(A)
|
|
88
|
+
G.add_weighted_edges_from((int(a), int(b), float(c)) for (a, b), c in zip(edges, w))
|
|
89
|
+
if positions is not None:
|
|
90
|
+
nx.set_node_attributes(G, {i: tuple(p) for i, p in enumerate(np.asarray(positions))}, "pos")
|
|
91
|
+
return G
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --------------------------------------------------------------------------- neighbor queries
|
|
95
|
+
def knn_indices(X, k: int, metric: str = "euclidean"):
|
|
96
|
+
"""Indices and distances of the ``k`` nearest neighbors of every sample (the sample itself excluded)."""
|
|
97
|
+
X = as_data(X, min_samples=2)
|
|
98
|
+
k = int(min(k, X.shape[0] - 1))
|
|
99
|
+
nn = NearestNeighbors(n_neighbors=k + 1, metric=metric).fit(X)
|
|
100
|
+
dist, idx = nn.kneighbors(X)
|
|
101
|
+
# remove the sample itself (robust to duplicates: drop the own index wherever it is)
|
|
102
|
+
N = X.shape[0]
|
|
103
|
+
mask = idx != np.arange(N)[:, None]
|
|
104
|
+
lost = mask.all(axis=1) # own index pushed out by duplicates: drop the farthest instead
|
|
105
|
+
mask[lost, -1] = False
|
|
106
|
+
return idx[mask].reshape(N, k), dist[mask].reshape(N, k)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def knn_graph(X, k: int = 5, metric: str = "euclidean") -> csr_matrix:
|
|
110
|
+
r"""Symmetric :math:`k`-nearest-neighbor graph.
|
|
111
|
+
|
|
112
|
+
Samples :math:`\mathbf{x}_i` and :math:`\mathbf{x}_j` are linked when one
|
|
113
|
+
of them is among the :math:`k` nearest neighbors of the other (union rule).
|
|
114
|
+
|
|
115
|
+
Examples
|
|
116
|
+
--------
|
|
117
|
+
>>> import numpy as np
|
|
118
|
+
>>> A = knn_graph(np.arange(10.0).reshape(-1, 1), k=1)
|
|
119
|
+
>>> int(A.nnz // 2)
|
|
120
|
+
9
|
|
121
|
+
"""
|
|
122
|
+
idx, dist = knn_indices(X, k, metric)
|
|
123
|
+
N = idx.shape[0]
|
|
124
|
+
rows = np.repeat(np.arange(N), idx.shape[1])
|
|
125
|
+
return _symmetric_from_edges(rows, idx.ravel(), dist.ravel(), N)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def mutual_knn_graph(X, k: int = 5, metric: str = "euclidean") -> csr_matrix:
|
|
129
|
+
"""Mutual :math:`k`-nearest-neighbor graph: an edge only if each sample is among the other's neighbors."""
|
|
130
|
+
idx, dist = knn_indices(X, k, metric)
|
|
131
|
+
N = idx.shape[0]
|
|
132
|
+
rows = np.repeat(np.arange(N), idx.shape[1])
|
|
133
|
+
D = coo_matrix((dist.ravel(), (rows, idx.ravel())), shape=(N, N)).tocsr()
|
|
134
|
+
M = D.minimum(D.T) # nonzero only where both directions exist
|
|
135
|
+
M.eliminate_zeros()
|
|
136
|
+
return M.tocsr()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def nearest_neighbor_graph(X) -> csr_matrix:
|
|
140
|
+
"""Nearest neighbor graph (NNG): every sample is linked to its single nearest neighbor."""
|
|
141
|
+
return knn_graph(X, k=1)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def epsilon_graph(X, eps: float) -> csr_matrix:
|
|
145
|
+
r""":math:`\varepsilon`-neighborhood graph: samples closer than ``eps`` are linked."""
|
|
146
|
+
X = as_data(X)
|
|
147
|
+
nn = NearestNeighbors(radius=eps).fit(X)
|
|
148
|
+
A = nn.radius_neighbors_graph(X, mode="distance")
|
|
149
|
+
A.setdiag(0)
|
|
150
|
+
A.eliminate_zeros()
|
|
151
|
+
return A.maximum(A.T).tocsr()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def minimum_spanning_tree(X=None, *, graph=None) -> csr_matrix:
|
|
155
|
+
r"""Euclidean minimal spanning tree (symmetric) of the samples or of a given weighted graph.
|
|
156
|
+
|
|
157
|
+
The tree has :math:`N-1` edges and minimal total length; SciPy computes it
|
|
158
|
+
with Kruskal's algorithm. Pass ``graph`` to obtain the minimal spanning
|
|
159
|
+
forest of an arbitrary weighted graph (e.g. a mutual reachability graph).
|
|
160
|
+
"""
|
|
161
|
+
if graph is None:
|
|
162
|
+
D = pairwise_distances(as_data(X, min_samples=2))
|
|
163
|
+
D[D == 0] = 1e-12
|
|
164
|
+
np.fill_diagonal(D, 0.0)
|
|
165
|
+
T = _csgraph_mst(D)
|
|
166
|
+
else:
|
|
167
|
+
T = _csgraph_mst(csr_matrix(graph))
|
|
168
|
+
return T.maximum(T.T).tocsr()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _empty_region_graph(X, rule: str) -> csr_matrix:
|
|
172
|
+
X = as_data(X, min_samples=2)
|
|
173
|
+
D = pairwise_distances(X)
|
|
174
|
+
N = len(X)
|
|
175
|
+
ii, jj, ww = [], [], []
|
|
176
|
+
big = np.inf
|
|
177
|
+
for i in range(N - 1):
|
|
178
|
+
Di = D[i]
|
|
179
|
+
js = np.arange(i + 1, N)
|
|
180
|
+
if rule == "rng":
|
|
181
|
+
M = np.maximum(Di[None, :], D[js]) # lune: max(d(i,r), d(j,r))
|
|
182
|
+
thr = D[i, js]
|
|
183
|
+
else: # gabriel: d(i,r)^2 + d(j,r)^2
|
|
184
|
+
M = Di[None, :] ** 2 + D[js] ** 2
|
|
185
|
+
thr = D[i, js] ** 2
|
|
186
|
+
M[:, i] = big
|
|
187
|
+
M[np.arange(len(js)), js] = big
|
|
188
|
+
ok = M.min(axis=1) >= thr - 1e-12
|
|
189
|
+
ii.append(np.full(ok.sum(), i))
|
|
190
|
+
jj.append(js[ok])
|
|
191
|
+
ww.append(D[i, js][ok])
|
|
192
|
+
return _symmetric_from_edges(np.concatenate(ii), np.concatenate(jj), np.concatenate(ww), N)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def relative_neighborhood_graph(X) -> csr_matrix:
|
|
196
|
+
r"""Relative neighborhood graph (Toussaint): :math:`\mathbf{x}_i,\mathbf{x}_j` are linked when no
|
|
197
|
+
third sample is closer to both of them than they are to each other. :math:`O(N^3)` time."""
|
|
198
|
+
return _empty_region_graph(X, "rng")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def gabriel_graph(X) -> csr_matrix:
|
|
202
|
+
r"""Gabriel graph: :math:`\mathbf{x}_i,\mathbf{x}_j` are linked when the ball with diameter
|
|
203
|
+
:math:`\overline{\mathbf{x}_i\mathbf{x}_j}` contains no other sample. :math:`O(N^3)` time."""
|
|
204
|
+
return _empty_region_graph(X, "gabriel")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def delaunay_graph(X) -> csr_matrix:
|
|
208
|
+
"""Delaunay triangulation as a graph (practical up to about six dimensions)."""
|
|
209
|
+
X = as_data(X, min_samples=3)
|
|
210
|
+
tri = Delaunay(X)
|
|
211
|
+
s = tri.simplices
|
|
212
|
+
pairs = np.vstack([s[:, [a, b]] for a in range(s.shape[1]) for b in range(a + 1, s.shape[1])])
|
|
213
|
+
pairs = np.unique(np.sort(pairs, axis=1), axis=0)
|
|
214
|
+
w = np.linalg.norm(X[pairs[:, 0]] - X[pairs[:, 1]], axis=1)
|
|
215
|
+
return _symmetric_from_edges(pairs[:, 0], pairs[:, 1], w, len(X))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def neighborhood_chain(X) -> dict:
|
|
219
|
+
"""Edge counts of NNG, MST, RNG, Gabriel graph and Delaunay triangulation, and whether each is
|
|
220
|
+
contained in the next (for 2-D or 3-D data)."""
|
|
221
|
+
graphs = {
|
|
222
|
+
"NNG": nearest_neighbor_graph(X),
|
|
223
|
+
"MST": minimum_spanning_tree(X),
|
|
224
|
+
"RNG": relative_neighborhood_graph(X),
|
|
225
|
+
"GG": gabriel_graph(X),
|
|
226
|
+
"DT": delaunay_graph(X),
|
|
227
|
+
}
|
|
228
|
+
names = list(graphs)
|
|
229
|
+
out = {"edges": {n: int(graphs[n].nnz // 2) for n in names}, "nested": {}}
|
|
230
|
+
for a, b in zip(names[:-1], names[1:]):
|
|
231
|
+
A = graphs[a] > 0
|
|
232
|
+
B = graphs[b] > 0
|
|
233
|
+
out["nested"][f"{a}<={b}"] = bool((A.multiply(B)).nnz == A.nnz)
|
|
234
|
+
return out
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def competitive_hebbian_graph(X, nodes) -> csr_matrix:
|
|
238
|
+
r"""Induced Delaunay triangulation by competitive Hebbian learning (Martinetz 1993).
|
|
239
|
+
|
|
240
|
+
For every sample, its nearest and second nearest node are linked. The
|
|
241
|
+
resulting graph is the Delaunay triangulation of the nodes masked by the
|
|
242
|
+
data distribution: edges through empty regions do not appear.
|
|
243
|
+
"""
|
|
244
|
+
X = as_data(X)
|
|
245
|
+
W = as_data(nodes, min_samples=2, name="nodes")
|
|
246
|
+
nn = NearestNeighbors(n_neighbors=2).fit(W)
|
|
247
|
+
_, idx = nn.kneighbors(X)
|
|
248
|
+
pairs = np.unique(np.sort(idx, axis=1), axis=0)
|
|
249
|
+
w = np.linalg.norm(W[pairs[:, 0]] - W[pairs[:, 1]], axis=1)
|
|
250
|
+
return _symmetric_from_edges(pairs[:, 0], pairs[:, 1], w, len(W))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def shared_neighbor_counts(X, k: int = 10, *, include_self: bool = True):
|
|
254
|
+
r"""Number of shared :math:`k`-nearest neighbors :math:`m_{ij}=|A_i\cap A_j|` for every pair.
|
|
255
|
+
|
|
256
|
+
Returns a dense integer matrix and the neighbor index array. With
|
|
257
|
+
``include_self=True`` every sample is counted as its own neighbor, the
|
|
258
|
+
convention of the original Jarvis--Patrick implementation.
|
|
259
|
+
"""
|
|
260
|
+
idx, _ = knn_indices(X, k)
|
|
261
|
+
N = idx.shape[0]
|
|
262
|
+
if include_self:
|
|
263
|
+
idx = np.column_stack([np.arange(N), idx])
|
|
264
|
+
M = np.zeros((N, N), dtype=np.int32)
|
|
265
|
+
M[np.repeat(np.arange(N), idx.shape[1]), idx.ravel()] = 1
|
|
266
|
+
return M @ M.T, idx
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# --------------------------------------------------------------------------- graph distances
|
|
270
|
+
def connect_components(points, adjacency) -> csr_matrix:
|
|
271
|
+
r"""Join the connected components of a graph by its shortest inter-component edges.
|
|
272
|
+
|
|
273
|
+
Repeatedly takes the component of node 0 and links it to the closest node
|
|
274
|
+
outside it, until the graph is connected (step 2 of TRNMap). The added
|
|
275
|
+
edges are weighted by their Euclidean length.
|
|
276
|
+
"""
|
|
277
|
+
P = as_data(points)
|
|
278
|
+
A = csr_matrix(adjacency, dtype=float).tolil()
|
|
279
|
+
n_comp, lab = connected_components(A.tocsr(), directed=False)
|
|
280
|
+
while n_comp > 1:
|
|
281
|
+
inside = np.flatnonzero(lab == lab[0])
|
|
282
|
+
outside = np.flatnonzero(lab != lab[0])
|
|
283
|
+
Dm = pairwise_distances(P[inside], P[outside])
|
|
284
|
+
a, b = np.unravel_index(np.argmin(Dm), Dm.shape)
|
|
285
|
+
w = max(Dm[a, b], 1e-12)
|
|
286
|
+
A[inside[a], outside[b]] = w
|
|
287
|
+
A[outside[b], inside[a]] = w
|
|
288
|
+
n_comp, lab = connected_components(A.tocsr(), directed=False)
|
|
289
|
+
return A.tocsr()
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def geodesic_distances(graph, *, points=None, connect: bool = False) -> np.ndarray:
|
|
293
|
+
r"""All-pairs shortest-path (graph, geodesic) distances with Dijkstra's algorithm.
|
|
294
|
+
|
|
295
|
+
Parameters
|
|
296
|
+
----------
|
|
297
|
+
graph : sparse matrix of shape (n, n)
|
|
298
|
+
Weighted symmetric graph, e.g. from :func:`knn_graph` or the
|
|
299
|
+
``adjacency_`` of a topology learner.
|
|
300
|
+
points : array of shape (n, n_features), optional
|
|
301
|
+
Coordinates of the nodes; needed when ``connect=True``.
|
|
302
|
+
connect : bool, default=False
|
|
303
|
+
Join the components first with :func:`connect_components` so that all
|
|
304
|
+
distances are finite.
|
|
305
|
+
"""
|
|
306
|
+
G = csr_matrix(graph)
|
|
307
|
+
if connect:
|
|
308
|
+
if points is None:
|
|
309
|
+
raise ValueError("points are required to connect the components")
|
|
310
|
+
G = connect_components(points, G)
|
|
311
|
+
return shortest_path(G, method="D", directed=False)
|