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/manifold.py ADDED
@@ -0,0 +1,1135 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
3
+ r"""Dimensionality reduction and visualization of high-dimensional data.
4
+
5
+ Distance-based mappings
6
+ :func:`classical_mds`, :class:`MetricMDS`, :class:`NonMetricMDS`,
7
+ :class:`SammonMapping`.
8
+ Neighborhood-based mappings
9
+ :class:`LocalityPreservingProjection`, :class:`SelfOrganizingMap`,
10
+ :class:`IncrementalGridGrowing`.
11
+ Topology-based (graph distance) mappings
12
+ :class:`Isomap`, :class:`Isotop`, :class:`CurvilinearComponentAnalysis`
13
+ (CCA, and CDA with ``geodesic=True``), :class:`OnlineVisualizationNG`
14
+ (OVI-NG), :class:`GeodesicNLPNG` (GNLP-NG) and :class:`TRNMap`.
15
+ Neighbor-graph embeddings (post-2013 state of the art)
16
+ :class:`LaplacianEigenmap`, :class:`DiffusionMap`,
17
+ :class:`UMAPEmbedding` (a NumPy implementation of the UMAP algorithm) and
18
+ :func:`tsne` (a thin wrapper of scikit-learn's Barnes--Hut t-SNE).
19
+
20
+ Every class has ``fit(X)`` and ``fit_transform(X)`` and stores the map in
21
+ ``embedding_``. The methods that first quantize the data (OVI-NG, GNLP-NG,
22
+ TRNMap, Isotop with ``n_nodes``) map the *nodes*: their ``embedding_`` has one
23
+ row per node and ``transform(X)`` places samples at the position of their
24
+ nearest node.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import numpy as np
30
+ from scipy.linalg import eigh
31
+ from scipy.optimize import curve_fit
32
+ from scipy.sparse import coo_matrix, csr_matrix
33
+ from sklearn.base import BaseEstimator, TransformerMixin
34
+ from sklearn.manifold import smacof
35
+ from sklearn.utils.validation import check_is_fitted
36
+
37
+ from ._utils import EPS, as_data, check_random_state, decay, pairwise_distances, sq_distances
38
+ from .graphs import connect_components, geodesic_distances, knn_graph, knn_indices
39
+ from .vq import NeuralGas, TopologyRepresentingNetwork
40
+
41
+ __all__ = [
42
+ "CurvilinearComponentAnalysis",
43
+ "DiffusionMap",
44
+ "GeodesicNLPNG",
45
+ "IncrementalGridGrowing",
46
+ "Isomap",
47
+ "Isotop",
48
+ "LaplacianEigenmap",
49
+ "LocalityPreservingProjection",
50
+ "MetricMDS",
51
+ "NonMetricMDS",
52
+ "OnlineVisualizationNG",
53
+ "SammonMapping",
54
+ "SelfOrganizingMap",
55
+ "TRNMap",
56
+ "UMAPEmbedding",
57
+ "classical_mds",
58
+ "tsne",
59
+ ]
60
+
61
+
62
+ # =========================================================================== MDS family
63
+ def classical_mds(D, n_components: int = 2) -> np.ndarray:
64
+ r"""Classical (Torgerson) MDS of a distance matrix.
65
+
66
+ Double-centers the squared distances, :math:`\mathbf{B}=-\tfrac12\mathbf{J}\mathbf{D}^{(2)}\mathbf{J}`,
67
+ and returns the coordinates :math:`\mathbf{E}_q\boldsymbol{\Lambda}_q^{1/2}` of the
68
+ :math:`q` largest eigenpairs. For Euclidean distances this equals PCA.
69
+ """
70
+ D = np.asarray(D, dtype=float)
71
+ n = len(D)
72
+ J = np.eye(n) - 1.0 / n
73
+ B = -0.5 * J @ (D**2) @ J
74
+ vals, vecs = eigh(B, subset_by_index=[n - n_components, n - 1])
75
+ vals, vecs = vals[::-1], vecs[:, ::-1]
76
+ Y = vecs * np.sqrt(np.maximum(vals, 0.0))
77
+ # deterministic sign
78
+ s = np.sign(Y[np.argmax(np.abs(Y), axis=0), np.arange(n_components)])
79
+ return Y * np.where(s == 0, 1, s)
80
+
81
+
82
+ class _Mapper(TransformerMixin, BaseEstimator):
83
+ def fit_transform(self, X, y=None):
84
+ return self.fit(X).embedding_
85
+
86
+
87
+ def _input_distances(X, dissimilarity):
88
+ if dissimilarity == "precomputed":
89
+ D = np.asarray(X, dtype=float)
90
+ if D.shape[0] != D.shape[1]:
91
+ raise ValueError("precomputed dissimilarities must be square")
92
+ return D
93
+ return pairwise_distances(as_data(X, min_samples=2))
94
+
95
+
96
+ class MetricMDS(_Mapper):
97
+ r"""Metric multidimensional scaling.
98
+
99
+ ``method="classical"`` solves the eigenproblem of :func:`classical_mds`;
100
+ ``method="smacof"`` minimizes the raw stress
101
+ :math:`\sum_{i<j}(d^*_{ij}-d_{ij})^2` by majorization (de Leeuw), started
102
+ from the classical solution. ``dissimilarity="precomputed"`` accepts any
103
+ distance matrix, e.g. geodesic distances.
104
+ """
105
+
106
+ def __init__(self, n_components=2, *, method="smacof", dissimilarity="euclidean", max_iter=300, random_state=None):
107
+ self.n_components = n_components
108
+ self.method = method
109
+ self.dissimilarity = dissimilarity
110
+ self.max_iter = max_iter
111
+ self.random_state = random_state
112
+
113
+ def fit(self, X, y=None):
114
+ D = _input_distances(X, self.dissimilarity)
115
+ Y = classical_mds(D, self.n_components)
116
+ if self.method == "smacof":
117
+ Y, stress = smacof(
118
+ D,
119
+ metric=True,
120
+ n_components=self.n_components,
121
+ init=Y,
122
+ n_init=1,
123
+ max_iter=self.max_iter,
124
+ random_state=self.random_state,
125
+ normalized_stress=False,
126
+ )
127
+ self.stress_ = float(stress)
128
+ elif self.method != "classical":
129
+ raise ValueError("method must be 'classical' or 'smacof'")
130
+ self.embedding_ = Y
131
+ return self
132
+
133
+
134
+ class NonMetricMDS(_Mapper):
135
+ r"""Non-metric (ordinal) MDS (Kruskal 1964): preserves the rank order of the dissimilarities.
136
+
137
+ The map distances are fitted to monotone transformations (disparities) of
138
+ the dissimilarities by isotonic regression inside SMACOF; started from
139
+ classical MDS. Kruskal's stress-1 is reported in ``stress_``. The solution
140
+ is rescaled to fit the dissimilarities in least squares, so that distance
141
+ measures remain comparable with metric maps.
142
+ """
143
+
144
+ def __init__(self, n_components=2, *, dissimilarity="euclidean", max_iter=300, random_state=None):
145
+ self.n_components = n_components
146
+ self.dissimilarity = dissimilarity
147
+ self.max_iter = max_iter
148
+ self.random_state = random_state
149
+
150
+ def fit(self, X, y=None):
151
+ D = _input_distances(X, self.dissimilarity)
152
+ init = classical_mds(D, self.n_components)
153
+ Y, stress = smacof(
154
+ D,
155
+ metric=False,
156
+ n_components=self.n_components,
157
+ init=init,
158
+ n_init=1,
159
+ max_iter=self.max_iter,
160
+ random_state=self.random_state,
161
+ normalized_stress=True,
162
+ )
163
+ # the ordinal solution has no natural scale: match the input distances in least squares
164
+ d = pairwise_distances(Y)
165
+ Y = Y * (D * d).sum() / max((d * d).sum(), EPS)
166
+ self.embedding_ = Y
167
+ self.stress_ = float(stress)
168
+ return self
169
+
170
+
171
+ class SammonMapping(_Mapper):
172
+ r"""Sammon's nonlinear mapping (1969).
173
+
174
+ Minimizes :math:`E=\frac{1}{\sum_{i<j}d^*_{ij}}\sum_{i<j}\frac{(d^*_{ij}-d_{ij})^2}{d^*_{ij}}`
175
+ with Sammon's pseudo-Newton steps (gradient divided by the absolute
176
+ diagonal of the Hessian) and step halving when the stress increases.
177
+ Small distances get large weights, so local structure is preserved better
178
+ than by metric MDS.
179
+ """
180
+
181
+ def __init__(
182
+ self, n_components=2, *, dissimilarity="euclidean", max_iter=500, tol=1e-9, init="pca", random_state=None
183
+ ):
184
+ self.n_components = n_components
185
+ self.dissimilarity = dissimilarity
186
+ self.max_iter = max_iter
187
+ self.tol = tol
188
+ self.init = init
189
+ self.random_state = random_state
190
+
191
+ def fit(self, X, y=None):
192
+ Ds = _input_distances(X, self.dissimilarity)
193
+ n = len(Ds)
194
+ Ds = Ds + np.eye(n)
195
+ Ds = np.where(Ds > 0, Ds, EPS)
196
+ Dinv = 1.0 / Ds
197
+ np.fill_diagonal(Dinv, 0.0)
198
+ scale = 0.5 / Ds[np.triu_indices(n, 1)].sum()
199
+ if isinstance(self.init, np.ndarray):
200
+ Y = np.array(self.init, dtype=float)
201
+ elif self.init == "pca":
202
+ Y = classical_mds(Ds - np.eye(n), self.n_components)
203
+ else:
204
+ Y = check_random_state(self.random_state).normal(size=(n, self.n_components))
205
+ one = np.ones((n, self.n_components))
206
+
207
+ def stress_of(Y):
208
+ d = pairwise_distances(Y) + np.eye(n)
209
+ return scale * ((Ds - d) ** 2 * Dinv).sum(), d
210
+
211
+ E, d = stress_of(Y)
212
+ for _ in range(self.max_iter):
213
+ dinv = 1.0 / d
214
+ np.fill_diagonal(dinv, 0.0)
215
+ delta = dinv - Dinv
216
+ deltaone = delta @ one
217
+ g = delta @ Y - Y * deltaone
218
+ dinv3 = dinv**3
219
+ y2 = Y**2
220
+ H = dinv3 @ y2 - deltaone - 2 * Y * (dinv3 @ Y) + y2 * (dinv3 @ one)
221
+ s = -g.ravel() / np.maximum(np.abs(H.ravel()), EPS)
222
+ Y_old = Y
223
+ for _ in range(20):
224
+ Y = Y_old + s.reshape(Y.shape)
225
+ E_new, d_new = stress_of(Y)
226
+ if E_new < E:
227
+ break
228
+ s *= 0.5
229
+ else:
230
+ Y = Y_old
231
+ break
232
+ if abs((E - E_new) / max(E, EPS)) < self.tol:
233
+ E, d = E_new, d_new
234
+ break
235
+ E, d = E_new, d_new
236
+ self.embedding_ = Y
237
+ self.stress_ = float(E)
238
+ return self
239
+
240
+
241
+ # =========================================================================== neighborhood-based
242
+ class LocalityPreservingProjection(_Mapper):
243
+ r"""Locality preserving projections (He and Niyogi 2003): a *linear* map that keeps neighbors close.
244
+
245
+ With heat-kernel weights :math:`w_{ij}=e^{-\|\mathbf{x}_i-\mathbf{x}_j\|^2/t}` on the
246
+ symmetric ``k``-NN graph, :math:`\mathbf{L}=\mathbf{D}-\mathbf{W}`, the projection
247
+ directions solve :math:`\mathbf{X}^T\mathbf{L}\mathbf{X}\mathbf{a}=\lambda\mathbf{X}^T\mathbf{D}\mathbf{X}\mathbf{a}`
248
+ for the smallest eigenvalues. Being linear, it projects new samples with
249
+ ``transform``. ``t=None`` uses the mean squared edge length.
250
+ """
251
+
252
+ def __init__(self, n_components=2, *, k=10, t=None, reg=1e-8):
253
+ self.n_components = n_components
254
+ self.k = k
255
+ self.t = t
256
+ self.reg = reg
257
+
258
+ def fit(self, X, y=None):
259
+ X = as_data(X, min_samples=3)
260
+ self.mean_ = X.mean(0)
261
+ Xc = X - self.mean_
262
+ A = knn_graph(Xc, self.k).tocoo()
263
+ t = self.t or float((A.data**2).mean())
264
+ W = coo_matrix((np.exp(-(A.data**2) / t), (A.row, A.col)), shape=A.shape).toarray()
265
+ Dg = np.diag(W.sum(1))
266
+ L = Dg - W
267
+ M1 = Xc.T @ L @ Xc
268
+ M2 = Xc.T @ Dg @ Xc
269
+ M2 += self.reg * np.trace(M2) / len(M2) * np.eye(len(M2))
270
+ vals, vecs = eigh(M1, M2)
271
+ self.components_ = vecs[:, : self.n_components].T
272
+ self.eigenvalues_ = vals[: self.n_components]
273
+ self.embedding_ = Xc @ self.components_.T
274
+ return self
275
+
276
+ def transform(self, X):
277
+ check_is_fitted(self, "components_")
278
+ return (as_data(X) - self.mean_) @ self.components_.T
279
+
280
+
281
+ def _grid(rows, cols, topology):
282
+ r, c = np.meshgrid(np.arange(rows), np.arange(cols), indexing="ij")
283
+ P = np.column_stack([c.ravel().astype(float), r.ravel().astype(float)])
284
+ if topology == "hexagonal":
285
+ P[:, 0] += 0.5 * (P[:, 1] % 2)
286
+ P[:, 1] *= np.sqrt(3) / 2
287
+ return P
288
+
289
+
290
+ class SelfOrganizingMap(_Mapper):
291
+ r"""Kohonen's self-organizing map (batch training).
292
+
293
+ The nodes sit on a fixed 2-D lattice (``grid`` rows x columns, rectangular
294
+ or hexagonal). In each epoch every node becomes the neighborhood-weighted
295
+ mean of the samples, with Gaussian neighborhood
296
+ :math:`h_{ij}=\exp(-\|\mathbf{r}_i-\mathbf{r}_j\|^2/2\sigma(t)^2)` on the lattice
297
+ and :math:`\sigma` shrinking from ``sigma[0]`` (default: half the larger
298
+ grid side) to ``sigma[1]``. The nodes are initialized on the plane of the
299
+ first two principal components. Batch training is deterministic and much
300
+ faster than the original online rule, with the same fixed points.
301
+
302
+ Attributes
303
+ ----------
304
+ nodes_ (prototype vectors), grid_positions_ (lattice coordinates, the map),
305
+ adjacency_ (lattice neighbors), embedding_ (lattice position of the BMU of every training sample).
306
+ """
307
+
308
+ def __init__(self, grid=(10, 10), *, topology="hexagonal", n_epochs=50, sigma=(None, 0.5)):
309
+ self.grid = grid
310
+ self.topology = topology
311
+ self.n_epochs = n_epochs
312
+ self.sigma = sigma
313
+
314
+ def fit(self, X, y=None):
315
+ X = as_data(X, min_samples=2)
316
+ rows, cols = self.grid
317
+ P = _grid(rows, cols, self.topology)
318
+ # PCA initialization
319
+ mu = X.mean(0)
320
+ U, s, Vt = np.linalg.svd(X - mu, full_matrices=False)
321
+ k = min(2, Vt.shape[0])
322
+ span = (s[:k] / np.sqrt(len(X))) * 2
323
+ Pc = (P - P.mean(0)) / np.maximum(np.ptp(P, 0), EPS)
324
+ W = mu + (Pc[:, :k] * span) @ Vt[:k]
325
+ s0 = self.sigma[0] if self.sigma[0] is not None else max(rows, cols) / 2.0
326
+ G2 = sq_distances(P, P)
327
+ for e in range(1, int(self.n_epochs) + 1):
328
+ sig = decay(s0, self.sigma[1], e, self.n_epochs)
329
+ bmu = np.argmin(sq_distances(X, W), axis=1)
330
+ H = np.exp(-G2[:, bmu] / (2 * sig**2)) # (nodes, samples)
331
+ W = (H @ X) / np.maximum(H.sum(1, keepdims=True), EPS)
332
+ self.nodes_ = W
333
+ self.grid_positions_ = P
334
+ thr = 1.01 if self.topology == "rectangular" else 1.01
335
+ A = (np.sqrt(G2) <= thr) & (G2 > 0)
336
+ self.adjacency_ = csr_matrix(A.astype(float))
337
+ self.labels_ = np.argmin(sq_distances(X, W), axis=1)
338
+ self.embedding_ = P[self.labels_]
339
+ return self
340
+
341
+ def transform(self, X):
342
+ check_is_fitted(self, "nodes_")
343
+ return self.grid_positions_[np.argmin(sq_distances(as_data(X), self.nodes_), axis=1)]
344
+
345
+ def umatrix(self) -> np.ndarray:
346
+ """Mean distance of every node to its lattice neighbors (the U-matrix), one value per node."""
347
+ check_is_fitted(self, "nodes_")
348
+ A = self.adjacency_.toarray() > 0
349
+ Dn = pairwise_distances(self.nodes_)
350
+ return np.array([Dn[i, A[i]].mean() if A[i].any() else 0.0 for i in range(len(A))])
351
+
352
+
353
+ class IncrementalGridGrowing(_Mapper):
354
+ r"""Incremental grid growing (Blackmore and Miikkulainen 1993).
355
+
356
+ A self-organizing map whose lattice grows: training starts on a 2 x 2
357
+ grid; after every ``epochs_per_growth`` epochs the boundary node with the
358
+ largest accumulated quantization error receives new nodes in all free
359
+ lattice positions next to it (initialized by extrapolation from their
360
+ neighbors). Lattice links between adjacent nodes are cut when their
361
+ vectors drift farther apart than ``disconnect`` times the median link
362
+ length and restored below ``connect`` times it, so the map can tear
363
+ along cluster borders. Growth stops at ``max_nodes``.
364
+ """
365
+
366
+ def __init__(
367
+ self, *, max_nodes=60, epochs_per_growth=3, sigma=1.0, lr=0.3, connect=0.8, disconnect=2.5, random_state=None
368
+ ):
369
+ self.max_nodes = max_nodes
370
+ self.epochs_per_growth = epochs_per_growth
371
+ self.sigma = sigma
372
+ self.lr = lr
373
+ self.connect = connect
374
+ self.disconnect = disconnect
375
+ self.random_state = random_state
376
+
377
+ def fit(self, X, y=None):
378
+ X = as_data(X, min_samples=4)
379
+ rng = check_random_state(self.random_state)
380
+ pos = [(0, 0), (1, 0), (0, 1), (1, 1)]
381
+ W = [X[i].copy() for i in rng.choice(len(X), 4, replace=False)]
382
+ links = {(0, 1), (0, 2), (1, 3), (2, 3)}
383
+
384
+ def lattice_nb(i):
385
+ px, py = pos[i]
386
+ return [j for j, q in enumerate(pos) if abs(q[0] - px) + abs(q[1] - py) == 1]
387
+
388
+ while True:
389
+ Wa = np.array(W)
390
+ P = np.array(pos, dtype=float)
391
+ err = np.zeros(len(W))
392
+ for e in range(int(self.epochs_per_growth)):
393
+ lr = self.lr * (1 - e / max(self.epochs_per_growth, 1)) + 0.02
394
+ for k in rng.permutation(len(X)):
395
+ x = X[k]
396
+ b = int(np.argmin(((Wa - x) ** 2).sum(1)))
397
+ err[b] += ((Wa[b] - x) ** 2).sum()
398
+ linked = np.array([b] + [j for j in lattice_nb(b) if (min(b, j), max(b, j)) in links])
399
+ h = np.exp(-((P[linked] - P[b]) ** 2).sum(1) / (2 * self.sigma**2))
400
+ Wa[linked] += (lr * h)[:, None] * (x - Wa[linked])
401
+ W = list(Wa)
402
+ # link maintenance
403
+ L = [np.linalg.norm(Wa[a] - Wa[b]) for a, b in links] or [1.0]
404
+ med = float(np.median(L))
405
+ for i in range(len(W)):
406
+ for j in lattice_nb(i):
407
+ if j <= i:
408
+ continue
409
+ d = np.linalg.norm(Wa[i] - Wa[j])
410
+ if (i, j) in links and d > self.disconnect * med:
411
+ links.discard((i, j))
412
+ elif (i, j) not in links and d < self.connect * med:
413
+ links.add((i, j))
414
+ if len(W) >= self.max_nodes:
415
+ break
416
+ occupied = set(pos)
417
+ boundary = [i for i in range(len(W)) if len(lattice_nb(i)) < 4]
418
+ q = max(boundary, key=lambda i: err[i])
419
+ px, py = pos[q]
420
+ free = [
421
+ (px + dx, py + dy)
422
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))
423
+ if (px + dx, py + dy) not in occupied
424
+ ]
425
+ for fx, fy in free:
426
+ if len(W) >= self.max_nodes:
427
+ break
428
+ # extrapolate: w_new = 2 w_q - w_opposite (if the opposite neighbor exists)
429
+ opp = (2 * px - fx, 2 * py - fy)
430
+ wq = Wa[q]
431
+ wn = 2 * wq - W[pos.index(opp)] if opp in pos else wq + 0.01 * rng.normal(size=wq.shape)
432
+ pos.append((fx, fy))
433
+ W.append(wn)
434
+ links.add((q, len(W) - 1))
435
+ self.nodes_ = np.array(W)
436
+ self.grid_positions_ = np.array(pos, dtype=float)
437
+ n = len(W)
438
+ A = np.zeros((n, n))
439
+ for a, b in links:
440
+ A[a, b] = A[b, a] = 1.0
441
+ self.adjacency_ = csr_matrix(A)
442
+ self.labels_ = np.argmin(sq_distances(X, self.nodes_), axis=1)
443
+ self.embedding_ = self.grid_positions_[self.labels_]
444
+ return self
445
+
446
+ def transform(self, X):
447
+ check_is_fitted(self, "nodes_")
448
+ return self.grid_positions_[np.argmin(sq_distances(as_data(X), self.nodes_), axis=1)]
449
+
450
+
451
+ # =========================================================================== topology-based
452
+ class _NodeMapper(_Mapper):
453
+ """Mapping of quantized nodes; samples are placed at their nearest node."""
454
+
455
+ def transform(self, X):
456
+ check_is_fitted(self, "embedding_")
457
+ return self.embedding_[np.argmin(sq_distances(as_data(X), self.nodes_), axis=1)]
458
+
459
+ def sample_embedding(self, X):
460
+ """Alias of :meth:`transform`: map coordinates of samples (position of their nearest node)."""
461
+ return self.transform(X)
462
+
463
+
464
+ class Isomap(_Mapper):
465
+ r"""Isomap (Tenenbaum, de Silva and Langford 2000).
466
+
467
+ Builds the ``k``-NN graph (or the :math:`\varepsilon`-graph), computes the
468
+ geodesic distances with Dijkstra's algorithm, and embeds them by classical
469
+ MDS. Disconnected graphs are joined by their shortest inter-component
470
+ edges, so that multi-cluster data can still be mapped (a known weakness of
471
+ the original method). ``graph`` may also be a precomputed sparse graph.
472
+ """
473
+
474
+ def __init__(self, n_components=2, *, k=10, eps=None, graph=None):
475
+ self.n_components = n_components
476
+ self.k = k
477
+ self.eps = eps
478
+ self.graph = graph
479
+
480
+ def fit(self, X, y=None):
481
+ from .graphs import epsilon_graph
482
+
483
+ X = as_data(X, min_samples=3)
484
+ if self.graph is not None:
485
+ G = csr_matrix(self.graph)
486
+ elif self.eps is not None:
487
+ G = epsilon_graph(X, self.eps)
488
+ else:
489
+ G = knn_graph(X, self.k)
490
+ self.graph_ = connect_components(X, G)
491
+ self.dist_matrix_ = geodesic_distances(self.graph_)
492
+ self.embedding_ = classical_mds(self.dist_matrix_, self.n_components)
493
+ return self
494
+
495
+
496
+ class Isotop(_NodeMapper):
497
+ r"""Isotop (Lee and Verleysen 2002, 2004).
498
+
499
+ 1. Optionally quantize the data with neural gas (``n_nodes``).
500
+ 2. Link the nodes by a ``k``-NN graph and compute geodesic distances
501
+ :math:`\delta_{ij}`.
502
+ 3. Self-organize the map positions :math:`\mathbf{y}_i` like a SOM whose
503
+ lattice is replaced by the graph: draw a point :math:`\mathbf{g}` from
504
+ a Gaussian kernel centered on a random map node, find the node
505
+ :math:`c` closest to it *in the map*, and move every node towards
506
+ :math:`\mathbf{g}` with step
507
+ :math:`\alpha(t)\exp\{-\tfrac12[\delta_{ci}/(\lambda(t)\mu_\delta)]^2\}`,
508
+ where :math:`\mu_\delta` is the mean edge length.
509
+
510
+ Isotop unfolds manifolds without solving an eigenproblem; it can fall
511
+ into local minima and needs the schedules to be set with some care.
512
+ """
513
+
514
+ def __init__(
515
+ self, n_components=2, *, n_nodes=None, k=6, n_iter=None, alpha=(1.0, 0.01), lam=(None, 0.5), random_state=None
516
+ ):
517
+ self.n_components = n_components
518
+ self.n_nodes = n_nodes
519
+ self.k = k
520
+ self.n_iter = n_iter
521
+ self.alpha = alpha
522
+ self.lam = lam
523
+ self.random_state = random_state
524
+
525
+ def fit(self, X, y=None):
526
+ X = as_data(X, min_samples=4)
527
+ rng = check_random_state(self.random_state)
528
+ if self.n_nodes:
529
+ W = NeuralGas(self.n_nodes, random_state=rng.randint(2**31 - 1)).fit(X).nodes_
530
+ else:
531
+ W = X.copy()
532
+ n = len(W)
533
+ G = connect_components(W, knn_graph(W, self.k))
534
+ delta = geodesic_distances(G)
535
+ mu = float(G.data.mean())
536
+ Y = classical_mds(pairwise_distances(W), self.n_components)
537
+ Y = (Y - Y.mean(0)) / max(Y.std(), EPS)
538
+ # width of the Gaussian kernels: initial mean edge length in the map (kept fixed,
539
+ # otherwise the map contracts together with the kernels)
540
+ gi, gj = G.nonzero()
541
+ width = float(np.linalg.norm(Y[gi] - Y[gj], axis=1).mean())
542
+ T = int(self.n_iter or 100 * n)
543
+ lam0 = self.lam[0] if self.lam[0] is not None else float(delta.max() / mu / 4)
544
+ for t in range(1, T + 1):
545
+ r = rng.randint(n)
546
+ g = Y[r] + rng.normal(scale=width, size=self.n_components)
547
+ c = int(np.argmin(((Y - g) ** 2).sum(1)))
548
+ a = decay(self.alpha[0], self.alpha[1], t, T)
549
+ la = decay(lam0, self.lam[1], t, T)
550
+ h = np.exp(-0.5 * (delta[c] / (la * mu)) ** 2)
551
+ Y += (a * h)[:, None] * (g - Y)
552
+ self.nodes_ = W
553
+ self.adjacency_ = G
554
+ self.dist_matrix_ = delta
555
+ self.embedding_ = Y
556
+ return self
557
+
558
+
559
+ class CurvilinearComponentAnalysis(_NodeMapper):
560
+ r"""Curvilinear component analysis (CCA; Demartines and Hérault 1997) and curvilinear distance analysis (CDA).
561
+
562
+ Minimizes :math:`E=\tfrac12\sum_{i\ne j}(\delta_{ij}-d_{ij})^2F(d_{ij},\lambda)` with the
563
+ stochastic rule: pick a sample :math:`i` and move every other point,
564
+
565
+ .. math:: \mathbf{y}_j \leftarrow \mathbf{y}_j + \alpha(t)\,F(d_{ij},\lambda(t))\,
566
+ \frac{\delta_{ij}-d_{ij}}{d_{ij}}(\mathbf{y}_j-\mathbf{y}_i),
567
+
568
+ with the step weighting :math:`F(d,\lambda)=\mathbb{1}[d<\lambda]` (or
569
+ :math:`e^{-d/\lambda}`). Because only short map distances are enforced,
570
+ long distances can stretch and manifolds unfold. With ``geodesic=True``
571
+ the input distances :math:`\delta_{ij}` are graph distances on the ``k``-NN
572
+ graph, which turns CCA into CDA (Lee, Lendasse and Verleysen 2004).
573
+ ``n_nodes`` quantizes the data with neural gas first.
574
+ """
575
+
576
+ def __init__(
577
+ self,
578
+ n_components=2,
579
+ *,
580
+ geodesic=False,
581
+ k=8,
582
+ n_nodes=None,
583
+ n_epochs=50,
584
+ alpha=(0.5, 0.01),
585
+ lam=(None, 0.01),
586
+ weighting="step",
587
+ random_state=None,
588
+ ):
589
+ self.n_components = n_components
590
+ self.geodesic = geodesic
591
+ self.k = k
592
+ self.n_nodes = n_nodes
593
+ self.n_epochs = n_epochs
594
+ self.alpha = alpha
595
+ self.lam = lam
596
+ self.weighting = weighting
597
+ self.random_state = random_state
598
+
599
+ def fit(self, X, y=None):
600
+ X = as_data(X, min_samples=3)
601
+ rng = check_random_state(self.random_state)
602
+ W = NeuralGas(self.n_nodes, random_state=rng.randint(2**31 - 1)).fit(X).nodes_ if self.n_nodes else X.copy()
603
+ n = len(W)
604
+ if self.geodesic:
605
+ G = connect_components(W, knn_graph(W, self.k))
606
+ Dh = geodesic_distances(G)
607
+ self.adjacency_ = G
608
+ else:
609
+ Dh = pairwise_distances(W)
610
+ Y = classical_mds(Dh, self.n_components)
611
+ lam0 = self.lam[0] if self.lam[0] is not None else 3.0 * float(Y.std(0).max())
612
+ lam1 = self.lam[1] * lam0 if self.lam[1] < 1 else self.lam[1]
613
+ T = int(self.n_epochs) * n
614
+ t = 0
615
+ for _ in range(int(self.n_epochs)):
616
+ for i in rng.permutation(n):
617
+ t += 1
618
+ a = decay(self.alpha[0], self.alpha[1], t, T)
619
+ la = decay(lam0, lam1, t, T)
620
+ diff = Y - Y[i]
621
+ d = np.sqrt((diff**2).sum(1))
622
+ d[i] = 1.0
623
+ F = (d < la).astype(float) if self.weighting == "step" else np.exp(-d / la)
624
+ F[i] = 0.0
625
+ Y += (a * F * (Dh[i] - d) / np.maximum(d, EPS))[:, None] * diff
626
+ self.nodes_ = W
627
+ self.dist_matrix_ = Dh
628
+ self.embedding_ = Y
629
+ return self
630
+
631
+
632
+ class OnlineVisualizationNG(_NodeMapper):
633
+ r"""Online visualization neural gas (OVI-NG; Estévez and Figueroa 2006).
634
+
635
+ Learns a topology representing network (neural gas + competitive Hebbian
636
+ rule) and, *simultaneously*, 2-D positions :math:`\mathbf{z}_j` for the
637
+ nodes. After each adaptation step with winner :math:`s`, every other node
638
+ moves in the map so that its map distance to :math:`s` approaches the
639
+ distance of the codebook vectors,
640
+
641
+ .. math:: \mathbf{z}_j \leftarrow \mathbf{z}_j + \alpha(t)\,e^{-r_j/\sigma(t)}\,
642
+ \frac{D_{js}-d_{js}}{D_{js}}(\mathbf{z}_s-\mathbf{z}_j),
643
+
644
+ where :math:`D_{js}=\|\mathbf{z}_j-\mathbf{z}_s\|`, :math:`d_{js}=\|\mathbf{w}_j-\mathbf{w}_s\|`
645
+ and :math:`r_j` is the rank of node :math:`j` by map distance from
646
+ :math:`s`. Only the rank ordering enters the neighborhood function, so
647
+ nearby relations dominate. The input distances are Euclidean, so curved
648
+ manifolds are not unfolded.
649
+ """
650
+
651
+ def __init__(
652
+ self,
653
+ n_nodes=100,
654
+ *,
655
+ n_components=2,
656
+ max_iter=None,
657
+ eps=(0.3, 0.05),
658
+ lam=None,
659
+ lifetime=None,
660
+ alpha=(0.3, 0.01),
661
+ sigma=None,
662
+ random_state=None,
663
+ ):
664
+ self.n_nodes = n_nodes
665
+ self.n_components = n_components
666
+ self.max_iter = max_iter
667
+ self.eps = eps
668
+ self.lam = lam
669
+ self.lifetime = lifetime
670
+ self.alpha = alpha
671
+ self.sigma = sigma
672
+ self.random_state = random_state
673
+
674
+ def fit(self, X, y=None):
675
+ X = as_data(X, min_samples=3)
676
+ rng = check_random_state(self.random_state)
677
+ n = int(self.n_nodes)
678
+ t_max = int(self.max_iter or 200 * n)
679
+ lam = self.lam or (0.2 * n, 0.01)
680
+ Ti, Tf = self.lifetime or (0.1 * n, 0.5 * n)
681
+ sig = self.sigma or (0.7 * n, 0.1)
682
+ lo, hi = X.min(0), X.max(0)
683
+ W = lo + (hi - lo) * rng.random_sample((n, X.shape[1]))
684
+ Z = rng.random_sample((n, self.n_components))
685
+ C = np.zeros((n, n), bool)
686
+ age = np.zeros((n, n))
687
+ draws = rng.randint(len(X), size=t_max)
688
+ for t in range(1, t_max + 1):
689
+ x = X[draws[t - 1]]
690
+ d2 = ((W - x) ** 2).sum(1)
691
+ order = np.argsort(d2)
692
+ rank = np.empty(n)
693
+ rank[order] = np.arange(n)
694
+ W += (decay(*self.eps, t, t_max) * np.exp(-rank / decay(*lam, t, t_max)))[:, None] * (x - W)
695
+ s, s2 = order[0], order[1]
696
+ C[s, s2] = C[s2, s] = True
697
+ age[s, s2] = age[s2, s] = 0
698
+ nb = C[s]
699
+ age[s, nb] += 1
700
+ age[nb, s] = age[s, nb]
701
+ old = nb & (age[s] > decay(Ti, Tf, t, t_max))
702
+ C[s, old] = C[old, s] = False
703
+ Dz = np.sqrt(((Z - Z[s]) ** 2).sum(1))
704
+ dw = np.sqrt(((W - W[s]) ** 2).sum(1))
705
+ rz = np.empty(n)
706
+ rz[np.argsort(Dz)] = np.arange(n)
707
+ coef = decay(*self.alpha, t, t_max) * np.exp(-rz / decay(*sig, t, t_max)) * (Dz - dw) / np.maximum(Dz, EPS)
708
+ coef[s] = 0.0
709
+ Z += coef[:, None] * (Z[s] - Z)
710
+ self.nodes_ = W
711
+ i, j = np.nonzero(np.triu(C, 1))
712
+ w = np.linalg.norm(W[i] - W[j], axis=1)
713
+ self.adjacency_ = coo_matrix((np.r_[w, w], (np.r_[i, j], np.r_[j, i])), shape=(n, n)).tocsr()
714
+ self.embedding_ = Z
715
+ return self
716
+
717
+
718
+ def _geodesic_refine(X, W, Z, Dg, t_max, alpha, delta, rng):
719
+ """GNLP-NG style fine tuning of node positions Z towards geodesic distances Dg."""
720
+ n = len(W)
721
+ draws = rng.randint(len(X), size=t_max)
722
+ rank_geo = np.empty((n, n))
723
+ for s in range(n):
724
+ rank_geo[s, np.argsort(Dg[:, s])] = np.arange(n)
725
+ for t in range(1, t_max + 1):
726
+ x = X[draws[t - 1]]
727
+ s = int(np.argmin(((W - x) ** 2).sum(1)))
728
+ Dz = np.sqrt(((Z - Z[s]) ** 2).sum(1))
729
+ h = np.exp(-((rank_geo[s] / decay(*delta, t, t_max)) ** 2))
730
+ coef = decay(*alpha, t, t_max) * h * (Dz - Dg[:, s]) / np.maximum(Dz, EPS)
731
+ coef[s] = 0.0
732
+ Z += coef[:, None] * (Z[s] - Z)
733
+ return Z
734
+
735
+
736
+ class GeodesicNLPNG(_NodeMapper):
737
+ r"""Geodesic nonlinear projection neural gas (GNLP-NG; Estévez, Chong, Held and Pérez 2006).
738
+
739
+ First learns the codebook with neural gas and links every sample's
740
+ ``n_links + 1`` nearest nodes (competitive Hebbian learning), connects the
741
+ graph and computes geodesic distances :math:`\delta_{js}` between nodes.
742
+ Then the map positions are adapted online: for the winner :math:`s` of
743
+ each drawn sample,
744
+
745
+ .. math:: \mathbf{z}_j \leftarrow \mathbf{z}_j + \alpha(t)\,e^{-(r_j/\sigma(t))^2}\,
746
+ \frac{D_{js}-\delta_{js}}{D_{js}}(\mathbf{z}_s-\mathbf{z}_j),
747
+
748
+ with :math:`r_j` the rank of node :math:`j` by *geodesic* distance from
749
+ :math:`s`. Geodesic distances let the map unfold curved manifolds.
750
+ """
751
+
752
+ def __init__(
753
+ self,
754
+ n_nodes=100,
755
+ *,
756
+ n_components=2,
757
+ max_iter=None,
758
+ eps=(0.3, 0.05),
759
+ lam=None,
760
+ n_links=1,
761
+ alpha=(0.3, 0.01),
762
+ sigma=None,
763
+ random_state=None,
764
+ ):
765
+ self.n_nodes = n_nodes
766
+ self.n_components = n_components
767
+ self.max_iter = max_iter
768
+ self.eps = eps
769
+ self.lam = lam
770
+ self.n_links = n_links
771
+ self.alpha = alpha
772
+ self.sigma = sigma
773
+ self.random_state = random_state
774
+
775
+ def fit(self, X, y=None):
776
+ X = as_data(X, min_samples=3)
777
+ rng = check_random_state(self.random_state)
778
+ n = int(self.n_nodes)
779
+ t_max = int(self.max_iter or 200 * n)
780
+ ng = NeuralGas(n, max_iter=t_max, eps=self.eps, lam=self.lam, random_state=rng.randint(2**31 - 1)).fit(X)
781
+ W = ng.nodes_
782
+ idx = np.argsort(sq_distances(X, W), axis=1)[:, : self.n_links + 1]
783
+ C = np.zeros((n, n), bool)
784
+ for col in range(1, idx.shape[1]):
785
+ C[idx[:, 0], idx[:, col]] = True
786
+ C |= C.T
787
+ i, j = np.nonzero(np.triu(C, 1))
788
+ w = np.maximum(np.linalg.norm(W[i] - W[j], axis=1), 1e-12)
789
+ G = coo_matrix((np.r_[w, w], (np.r_[i, j], np.r_[j, i])), shape=(n, n)).tocsr()
790
+ G = connect_components(W, G)
791
+ Dg = geodesic_distances(G)
792
+ Z = rng.random_sample((n, self.n_components))
793
+ sig = self.sigma or (0.7 * n, 0.1)
794
+ Z = _geodesic_refine(X, W, Z, Dg, t_max, self.alpha, sig, rng)
795
+ self.nodes_ = W
796
+ self.adjacency_ = G
797
+ self.dist_matrix_ = Dg
798
+ self.embedding_ = Z
799
+ return self
800
+
801
+
802
+ class TRNMap(_NodeMapper):
803
+ r"""Topology representing network map (Vathy-Fogarassy, Kiss and Abonyi 2008).
804
+
805
+ 0. The data are scaled to the unit hypercube (``normalize=True``).
806
+ 1. A :class:`~graphclust.vq.TopologyRepresentingNetwork` with ``n_nodes``
807
+ nodes (initialized on random samples) quantizes the data and learns
808
+ their topology; ``prune`` removes links that no sample supports at the
809
+ end of training.
810
+ 2. Disconnected parts of the graph are joined by their shortest
811
+ inter-component edges.
812
+ 3. Geodesic distances between the nodes are computed along the graph.
813
+ 4. The graph is mapped to ``n_components`` dimensions by metric MDS
814
+ (``mapping="metric"``, the distance-preserving DP-TRNMap), non-metric
815
+ MDS (``"nonmetric"``, the neighborhood-preserving NP-TRNMap) or
816
+ classical MDS (``"classical"``).
817
+ 5. Optionally (``fine_tune=True``) the positions are refined online
818
+ towards the geodesic distances as in GNLP-NG.
819
+
820
+ The node vectors provide component planes
821
+ (:func:`graphclust.plotting.plot_component_planes`); the nodes are
822
+ natural prototypes for clustering the map.
823
+
824
+ Attributes
825
+ ----------
826
+ nodes_ (in the scale of the input data), adjacency_ (original TRN graph),
827
+ connected_adjacency_, dist_matrix_ (geodesic), embedding_, trn_ (fitted network).
828
+ """
829
+
830
+ def __init__(
831
+ self,
832
+ n_nodes=100,
833
+ *,
834
+ n_components=2,
835
+ mapping="metric",
836
+ fine_tune=False,
837
+ normalize=True,
838
+ max_iter=None,
839
+ eps=(0.3, 0.05),
840
+ lam=None,
841
+ lifetime=None,
842
+ prune=True,
843
+ alpha=(0.3, 0.01),
844
+ sigma=None,
845
+ random_state=None,
846
+ ):
847
+ self.n_nodes = n_nodes
848
+ self.n_components = n_components
849
+ self.prune = prune
850
+ self.mapping = mapping
851
+ self.fine_tune = fine_tune
852
+ self.normalize = normalize
853
+ self.max_iter = max_iter
854
+ self.eps = eps
855
+ self.lam = lam
856
+ self.lifetime = lifetime
857
+ self.alpha = alpha
858
+ self.sigma = sigma
859
+ self.random_state = random_state
860
+
861
+ def fit(self, X, y=None):
862
+ X = as_data(X, min_samples=3)
863
+ rng = check_random_state(self.random_state)
864
+ if self.normalize:
865
+ self._lo, hi = X.min(0), X.max(0)
866
+ self._rng = np.where(hi - self._lo > 0, hi - self._lo, 1.0)
867
+ else:
868
+ self._lo, self._rng = np.zeros(X.shape[1]), np.ones(X.shape[1])
869
+ Xs = (X - self._lo) / self._rng
870
+ n = int(self.n_nodes)
871
+ lifetime = self.lifetime or (0.1 * n, 0.5 * n)
872
+ trn = TopologyRepresentingNetwork(
873
+ n,
874
+ max_iter=self.max_iter,
875
+ eps=self.eps,
876
+ lam=self.lam,
877
+ lifetime=lifetime,
878
+ random_state=rng.randint(2**31 - 1),
879
+ ).fit(Xs)
880
+ W = trn.nodes_
881
+ Gc = connect_components(W, trn.adjacency_)
882
+ Dg = geodesic_distances(Gc)
883
+ if self.mapping == "metric":
884
+ Z = (
885
+ MetricMDS(self.n_components, dissimilarity="precomputed", random_state=rng.randint(2**31 - 1))
886
+ .fit(Dg)
887
+ .embedding_
888
+ )
889
+ elif self.mapping == "nonmetric":
890
+ Z = (
891
+ NonMetricMDS(self.n_components, dissimilarity="precomputed", random_state=rng.randint(2**31 - 1))
892
+ .fit(Dg)
893
+ .embedding_
894
+ )
895
+ Z *= np.sqrt((Dg**2).sum() / max((pairwise_distances(Z) ** 2).sum(), EPS))
896
+ elif self.mapping == "classical":
897
+ Z = classical_mds(Dg, self.n_components)
898
+ else:
899
+ raise ValueError("mapping must be 'metric', 'nonmetric' or 'classical'")
900
+ if self.fine_tune:
901
+ t_max = int(self.max_iter or 200 * n)
902
+ Z = _geodesic_refine(Xs, W, Z.copy(), Dg, t_max, self.alpha, self.sigma or (0.7 * n, 0.1), rng)
903
+ self.trn_ = trn
904
+ self.nodes_ = W * self._rng + self._lo
905
+ self.adjacency_ = trn.adjacency_
906
+ self.connected_adjacency_ = Gc
907
+ self.dist_matrix_ = Dg
908
+ self.embedding_ = Z
909
+ return self
910
+
911
+
912
+ # =========================================================================== neighbor-graph embeddings
913
+ class LaplacianEigenmap(_Mapper):
914
+ r"""Laplacian eigenmaps (Belkin and Niyogi 2003).
915
+
916
+ Heat-kernel weights on the symmetric ``k``-NN graph; the embedding consists
917
+ of the eigenvectors of :math:`\mathbf{L}\mathbf{f}=\lambda\mathbf{D}\mathbf{f}` belonging to
918
+ the smallest non-zero eigenvalues: the smoothest functions on the graph.
919
+ """
920
+
921
+ def __init__(self, n_components=2, *, k=10, t=None):
922
+ self.n_components = n_components
923
+ self.k = k
924
+ self.t = t
925
+
926
+ def fit(self, X, y=None):
927
+ X = as_data(X, min_samples=3)
928
+ A = connect_components(X, knn_graph(X, self.k)).tocoo()
929
+ t = self.t or float((A.data**2).mean())
930
+ W = coo_matrix((np.exp(-(A.data**2) / t), (A.row, A.col)), shape=A.shape).toarray()
931
+ d = W.sum(1)
932
+ vals, vecs = eigh(np.diag(d) - W, np.diag(d), subset_by_index=[0, self.n_components])
933
+ self.eigenvalues_ = vals[1:]
934
+ self.embedding_ = vecs[:, 1 : self.n_components + 1]
935
+ return self
936
+
937
+
938
+ class DiffusionMap(_Mapper):
939
+ r"""Diffusion maps (Coifman and Lafon 2006).
940
+
941
+ Gaussian kernel with bandwidth :math:`\varepsilon` (default: median squared
942
+ distance to the ``k``-th neighbor), density normalization with exponent
943
+ ``alpha`` (1 gives the Laplace--Beltrami operator, independent of the
944
+ sampling density), row-stochastic Markov matrix :math:`\mathbf{P}` and the
945
+ embedding :math:`\lambda_l^t\boldsymbol{\psi}_l` of its non-trivial eigenvectors
946
+ after ``t`` diffusion steps. Distances in the map approximate diffusion
947
+ distances on the data graph.
948
+ """
949
+
950
+ def __init__(self, n_components=2, *, k=10, epsilon=None, alpha=1.0, t=1):
951
+ self.n_components = n_components
952
+ self.k = k
953
+ self.epsilon = epsilon
954
+ self.alpha = alpha
955
+ self.t = t
956
+
957
+ def fit(self, X, y=None):
958
+ X = as_data(X, min_samples=3)
959
+ D2 = sq_distances(X, X)
960
+ if self.epsilon is None:
961
+ kth = np.sort(D2, axis=1)[:, min(self.k, len(X) - 1)]
962
+ eps = float(np.median(kth))
963
+ else:
964
+ eps = float(self.epsilon)
965
+ K = np.exp(-D2 / max(eps, EPS))
966
+ q = K.sum(1)
967
+ K = K / np.outer(q, q) ** self.alpha
968
+ d = K.sum(1)
969
+ S = K / np.sqrt(np.outer(d, d))
970
+ vals, vecs = eigh(S, subset_by_index=[len(S) - self.n_components - 1, len(S) - 1])
971
+ vals, vecs = vals[::-1], vecs[:, ::-1]
972
+ psi = vecs / vecs[:, [0]]
973
+ self.eigenvalues_ = vals[1:]
974
+ self.embedding_ = psi[:, 1:] * vals[1:] ** self.t
975
+ return self
976
+
977
+
978
+ def _fit_ab(spread, min_dist):
979
+ x = np.linspace(0, spread * 3, 300)
980
+ yv = np.where(x < min_dist, 1.0, np.exp(-(x - min_dist) / spread))
981
+ (a, b), _ = curve_fit(lambda x, a, b: 1.0 / (1.0 + a * x ** (2 * b)), x, yv, p0=(1.6, 0.9), maxfev=10000)
982
+ return float(a), float(b)
983
+
984
+
985
+ class UMAPEmbedding(_Mapper):
986
+ r"""Uniform manifold approximation and projection (UMAP; McInnes, Healy and Melville 2018), NumPy implementation.
987
+
988
+ 1. *Fuzzy neighborhood graph.* For every sample the distances to its
989
+ ``k`` nearest neighbors are converted to memberships
990
+ :math:`w_{ij}=\exp(-(d_{ij}-\rho_i)/\sigma_i)`, with :math:`\rho_i` the
991
+ distance to the nearest neighbor and :math:`\sigma_i` chosen so that
992
+ :math:`\sum_j w_{ij}=\log_2 k`; the directed graph is symmetrized by
993
+ the probabilistic t-conorm :math:`w_{ij}+w_{ji}-w_{ij}w_{ji}`.
994
+ 2. *Layout.* Starting from a spectral embedding of this graph, the map is
995
+ optimized by stochastic gradient descent on the fuzzy cross-entropy:
996
+ edges attract their end points with the low-dimensional similarity
997
+ :math:`(1+a\,d^{2b})^{-1}` and ``negative_sample_rate`` random pairs per
998
+ edge repel each other. :math:`a,b` follow from ``min_dist`` and
999
+ ``spread``.
1000
+
1001
+ This implementation updates all edges of an epoch at once (vectorized),
1002
+ which is adequate up to a few ten thousand samples; for large data use
1003
+ the ``umap-learn`` package, which implements the same algorithm with
1004
+ approximate nearest neighbors and Numba. The graph is exposed as
1005
+ ``graph_`` for clustering (e.g. with Leiden).
1006
+ """
1007
+
1008
+ def __init__(
1009
+ self,
1010
+ n_components=2,
1011
+ *,
1012
+ k=15,
1013
+ min_dist=0.1,
1014
+ spread=1.0,
1015
+ n_epochs=None,
1016
+ learning_rate=1.0,
1017
+ negative_sample_rate=5,
1018
+ init="spectral",
1019
+ random_state=None,
1020
+ ):
1021
+ self.n_components = n_components
1022
+ self.k = k
1023
+ self.min_dist = min_dist
1024
+ self.spread = spread
1025
+ self.n_epochs = n_epochs
1026
+ self.learning_rate = learning_rate
1027
+ self.negative_sample_rate = negative_sample_rate
1028
+ self.init = init
1029
+ self.random_state = random_state
1030
+
1031
+ @staticmethod
1032
+ def _smooth_knn(dist, k):
1033
+ target = np.log2(k)
1034
+ rho = dist[:, 0]
1035
+ sig = np.ones(len(dist))
1036
+ for i in range(len(dist)):
1037
+ lo, hi, mid = 0.0, np.inf, 1.0
1038
+ di = dist[i] - rho[i]
1039
+ for _ in range(64):
1040
+ s = np.exp(-np.maximum(di, 0) / mid).sum()
1041
+ if abs(s - target) < 1e-5:
1042
+ break
1043
+ if s > target:
1044
+ hi = mid
1045
+ mid = (lo + hi) / 2
1046
+ else:
1047
+ lo = mid
1048
+ mid = mid * 2 if hi == np.inf else (lo + hi) / 2
1049
+ sig[i] = max(mid, 1e-3 * dist[i].mean() if dist[i].mean() > 0 else 1e-3)
1050
+ return rho, sig
1051
+
1052
+ def fit(self, X, y=None):
1053
+ X = as_data(X, min_samples=4)
1054
+ rng = check_random_state(self.random_state)
1055
+ N = len(X)
1056
+ k = min(self.k, N - 1)
1057
+ idx, dist = knn_indices(X, k)
1058
+ rho, sig = self._smooth_knn(dist, k)
1059
+ w = np.exp(-np.maximum(dist - rho[:, None], 0) / sig[:, None])
1060
+ rows = np.repeat(np.arange(N), k)
1061
+ P = coo_matrix((w.ravel(), (rows, idx.ravel())), shape=(N, N)).tocsr()
1062
+ G = P + P.T - P.multiply(P.T)
1063
+ G = G.tocoo()
1064
+ G.eliminate_zeros()
1065
+ self.graph_ = G.tocsr()
1066
+ a, b = _fit_ab(self.spread, self.min_dist)
1067
+ self.a_, self.b_ = a, b
1068
+ # initialization
1069
+ if isinstance(self.init, np.ndarray):
1070
+ Y = np.array(self.init, dtype=float)
1071
+ elif self.init == "spectral":
1072
+ try:
1073
+ A = self.graph_.toarray()
1074
+ d = A.sum(1)
1075
+ dinv = 1 / np.sqrt(np.maximum(d, EPS))
1076
+ L = np.eye(N) - dinv[:, None] * A * dinv[None, :]
1077
+ _, vecs = eigh(L, subset_by_index=[1, self.n_components])
1078
+ Y = vecs
1079
+ Y = 10 * (Y - Y.min(0)) / np.maximum(np.ptp(Y, 0), EPS) - 5
1080
+ Y += rng.normal(scale=1e-4, size=Y.shape)
1081
+ except Exception: # pragma: no cover - fallback
1082
+ Y = rng.uniform(-10, 10, size=(N, self.n_components))
1083
+ else:
1084
+ Y = rng.uniform(-10, 10, size=(N, self.n_components))
1085
+ n_epochs = int(self.n_epochs or (500 if N <= 10000 else 200))
1086
+ head, tail, wt = G.row, G.col, G.data
1087
+ keep = wt >= wt.max() / n_epochs
1088
+ head, tail, wt = head[keep], tail[keep], wt[keep]
1089
+ eps_per = wt.max() / wt
1090
+ next_due = eps_per.copy()
1091
+ for ep in range(1, n_epochs + 1):
1092
+ alpha = self.learning_rate * (1.0 - (ep - 1) / n_epochs)
1093
+ due = next_due <= ep
1094
+ if not due.any():
1095
+ continue
1096
+ h, t_ = head[due], tail[due]
1097
+ diff = Y[h] - Y[t_]
1098
+ d2 = (diff**2).sum(1)
1099
+ coef = (-2 * a * b * np.power(np.maximum(d2, EPS), b - 1)) / (1 + a * np.power(d2, b))
1100
+ grad = np.clip(coef[:, None] * diff, -4, 4)
1101
+ upd = np.zeros_like(Y)
1102
+ np.add.at(upd, h, grad)
1103
+ np.add.at(upd, t_, -grad)
1104
+ # negative sampling
1105
+ nn = int(self.negative_sample_rate)
1106
+ hn = np.repeat(h, nn)
1107
+ tn = rng.randint(N, size=hn.size)
1108
+ diff = Y[hn] - Y[tn]
1109
+ d2 = (diff**2).sum(1)
1110
+ coef = (2 * b) / ((0.001 + d2) * (1 + a * np.power(d2, b)))
1111
+ grad = np.clip(coef[:, None] * diff, -4, 4)
1112
+ grad[hn == tn] = 0
1113
+ np.add.at(upd, hn, grad)
1114
+ cnt = np.bincount(np.r_[h, t_, hn], minlength=N)[:, None]
1115
+ Y += alpha * upd / np.maximum(cnt, 1) ** 0.5
1116
+ next_due[due] += eps_per[due]
1117
+ self.embedding_ = Y
1118
+ return self
1119
+
1120
+
1121
+ def tsne(X, n_components=2, *, perplexity=30.0, metric="euclidean", random_state=None, **kwargs):
1122
+ r"""t-distributed stochastic neighbor embedding (van der Maaten and Hinton 2008) via scikit-learn.
1123
+
1124
+ t-SNE converts distances into a sparse affinity *graph* (Gaussian
1125
+ neighborhoods of fixed perplexity, i.e. effectively a weighted kNN graph)
1126
+ and lays it out with heavy-tailed Student-t similarities; it is the
1127
+ neighbor-embedding method against which UMAP is usually compared. Pass
1128
+ ``metric="precomputed"`` to embed geodesic or fuzzy neighborhood distances.
1129
+ """
1130
+ from sklearn.manifold import TSNE
1131
+
1132
+ init = "random" if metric == "precomputed" else kwargs.pop("init", "pca")
1133
+ return TSNE(
1134
+ n_components, perplexity=perplexity, metric=metric, init=init, random_state=random_state, **kwargs
1135
+ ).fit_transform(np.asarray(X, dtype=float))