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/vq.py ADDED
@@ -0,0 +1,707 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Ágnes Vathy-Fogarassy, János Abonyi
3
+ r"""Vector quantization and topology learning.
4
+
5
+ The estimators of this module replace the :math:`N` samples by
6
+ :math:`n\ll N` representatives (codebook vectors, nodes, neurons)
7
+ :math:`\mathbf{w}_1,\dots,\mathbf{w}_n` and, except for :class:`LBG`, also
8
+ learn a graph over them that reflects the topology of the data. They share
9
+ one interface (:class:`BaseTopologyLearner`):
10
+
11
+ ``fit(X)`` sets
12
+ ``nodes_`` (n, D) representatives, ``adjacency_`` symmetric sparse graph
13
+ weighted by the Euclidean edge lengths, ``labels_`` index of the nearest
14
+ node of every training sample, ``n_nodes_``, ``n_edges_``.
15
+
16
+ Fitted learners provide ``predict(X)``, ``transform(X)``,
17
+ ``quantization_error(X)`` and ``graph_distances()``.
18
+
19
+ All the incremental algorithms draw one sample per iteration, so their
20
+ results depend on ``random_state``; the parameter schedules use
21
+ :func:`graphclust._utils.decay`.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import numpy as np
27
+ from scipy.sparse import coo_matrix
28
+ from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin
29
+ from sklearn.utils.validation import check_is_fitted
30
+
31
+ from ._utils import as_data, check_random_state, decay, sq_distances
32
+ from .graphs import competitive_hebbian_graph, geodesic_distances
33
+
34
+ __all__ = [
35
+ "BaseTopologyLearner",
36
+ "DynamicTopologyRepresentingNetwork",
37
+ "GrowWhenRequired",
38
+ "GrowingNeuralGas",
39
+ "LBG",
40
+ "NeuralGas",
41
+ "TopologyRepresentingNetwork",
42
+ "WeightedIncrementalNetwork",
43
+ ]
44
+
45
+
46
+ class BaseTopologyLearner(ClusterMixin, TransformerMixin, BaseEstimator):
47
+ """Common interface of the vector quantizers and topology learners."""
48
+
49
+ # ----------------------------------------------------------------- finishing
50
+ def _finish(self, X, W, C=None):
51
+ W = np.asarray(W, dtype=float)
52
+ n = len(W)
53
+ if C is None:
54
+ C = np.zeros((n, n), bool)
55
+ C = np.asarray(C, bool)
56
+ C = C | C.T
57
+ np.fill_diagonal(C, False)
58
+ i, j = np.nonzero(np.triu(C, 1))
59
+ w = np.maximum(np.linalg.norm(W[i] - W[j], axis=1), 1e-12)
60
+ self.nodes_ = W
61
+ self.adjacency_ = coo_matrix((np.r_[w, w], (np.r_[i, j], np.r_[j, i])), shape=(n, n)).tocsr()
62
+ self.n_nodes_ = n
63
+ self.n_edges_ = int(len(i))
64
+ self.labels_ = self.predict(X)
65
+ self.n_features_in_ = X.shape[1]
66
+ return self
67
+
68
+ # ----------------------------------------------------------------- queries
69
+ def transform(self, X):
70
+ """Euclidean distances of the samples to every node, shape (n_samples, n_nodes)."""
71
+ check_is_fitted(self, "nodes_")
72
+ return np.sqrt(sq_distances(as_data(X), self.nodes_))
73
+
74
+ def predict(self, X):
75
+ """Index of the nearest node (best matching unit) of every sample."""
76
+ check_is_fitted(self, "nodes_")
77
+ return np.argmin(sq_distances(as_data(X), self.nodes_), axis=1)
78
+
79
+ def quantization_error(self, X) -> float:
80
+ r"""Mean squared distance of the samples to their nearest node, :math:`\frac1N\sum_k\min_i\|\mathbf{x}_k-\mathbf{w}_i\|^2`."""
81
+ check_is_fitted(self, "nodes_")
82
+ return float(sq_distances(as_data(X), self.nodes_).min(axis=1).mean())
83
+
84
+ def graph_distances(self, connect: bool = True):
85
+ """Geodesic distances between the nodes along ``adjacency_`` (components joined if ``connect``)."""
86
+ check_is_fitted(self, "adjacency_")
87
+ return geodesic_distances(self.adjacency_, points=self.nodes_, connect=connect)
88
+
89
+ def _init_nodes(self, X, n, rng):
90
+ if isinstance(self.init, np.ndarray):
91
+ W = np.array(self.init, dtype=float)
92
+ if W.shape != (n, X.shape[1]):
93
+ raise ValueError(f"init must have shape {(n, X.shape[1])}, got {W.shape}")
94
+ return W
95
+ if self.init == "sample":
96
+ return X[rng.choice(len(X), n, replace=len(X) < n)].copy()
97
+ if self.init == "range": # uniform in the bounding box (MATLAB toolbox)
98
+ lo, hi = X.min(0), X.max(0)
99
+ return lo + (hi - lo) * rng.random_sample((n, X.shape[1]))
100
+ raise ValueError(f"unknown init {self.init!r}")
101
+
102
+
103
+ # =========================================================================== k-means family
104
+ class LBG(BaseTopologyLearner):
105
+ r"""Linde--Buzo--Gray vector quantizer: k-means with codebook splitting.
106
+
107
+ Starts from the centroid of the data, doubles the codebook by splitting
108
+ every codevector :math:`\mathbf{w}\to\mathbf{w}(1\pm\delta)` and refines
109
+ the doubled codebook with k-means (Lloyd) iterations, until ``n_nodes``
110
+ codevectors exist (the last split adds only as many as needed). With
111
+ ``graph=True`` the nodes are linked afterwards by competitive Hebbian
112
+ learning (:func:`graphclust.graphs.competitive_hebbian_graph`).
113
+
114
+ Examples
115
+ --------
116
+ >>> import numpy as np
117
+ >>> X = np.random.default_rng(0).normal(size=(200, 2))
118
+ >>> LBG(n_nodes=8, random_state=0).fit(X).nodes_.shape
119
+ (8, 2)
120
+ """
121
+
122
+ def __init__(self, n_nodes=16, *, delta=1e-3, max_iter=100, tol=1e-6, graph=True, random_state=None):
123
+ self.n_nodes = n_nodes
124
+ self.delta = delta
125
+ self.max_iter = max_iter
126
+ self.tol = tol
127
+ self.graph = graph
128
+ self.random_state = random_state
129
+
130
+ def _lloyd(self, X, W):
131
+ prev = np.inf
132
+ for _ in range(self.max_iter):
133
+ lab = np.argmin(sq_distances(X, W), axis=1)
134
+ for i in range(len(W)):
135
+ m = lab == i
136
+ if m.any():
137
+ W[i] = X[m].mean(0)
138
+ J = sq_distances(X, W).min(1).sum()
139
+ if prev - J <= self.tol * max(prev, 1e-300):
140
+ break
141
+ prev = J
142
+ return W
143
+
144
+ def fit(self, X, y=None):
145
+ X = as_data(X)
146
+ rng = check_random_state(self.random_state)
147
+ W = X.mean(0, keepdims=True)
148
+ while len(W) < self.n_nodes:
149
+ k = min(len(W), self.n_nodes - len(W))
150
+ # split the codevectors with the largest distortion first
151
+ lab = np.argmin(sq_distances(X, W), axis=1)
152
+ dist = np.bincount(lab, sq_distances(X, W).min(1), minlength=len(W))
153
+ pick = np.argsort(-dist)[:k]
154
+ jitter = self.delta * (np.abs(W[pick]) + 1e-3) * rng.choice([-1, 1], size=W[pick].shape)
155
+ W = np.vstack([W, W[pick] + jitter])
156
+ W[pick] -= jitter
157
+ W = self._lloyd(X, W)
158
+ C = competitive_hebbian_graph(X, W).toarray() > 0 if self.graph else None
159
+ return self._finish(X, W, C)
160
+
161
+
162
+ # =========================================================================== neural gas family
163
+ class NeuralGas(BaseTopologyLearner):
164
+ r"""Neural gas vector quantization (Martinetz and Schulten 1991).
165
+
166
+ In each iteration a random sample :math:`\mathbf{x}` is drawn, the nodes
167
+ are ranked by their distance to it (:math:`r_j=0` for the nearest) and all
168
+ of them move towards the sample,
169
+
170
+ .. math:: \mathbf{w}_j \leftarrow \mathbf{w}_j + \varepsilon(t)\,e^{-r_j/\lambda(t)}(\mathbf{x}-\mathbf{w}_j),
171
+
172
+ with exponentially decreasing step size :math:`\varepsilon` and
173
+ neighborhood range :math:`\lambda`. The rank-based soft competition makes
174
+ neural gas far less sensitive to its initialization than k-means. Neural
175
+ gas itself learns no graph; :class:`TopologyRepresentingNetwork` adds one.
176
+
177
+ Parameters
178
+ ----------
179
+ n_nodes : int, default=50
180
+ max_iter : int, optional
181
+ Number of adaptation steps :math:`t_{\max}` (default ``200 * n_nodes``).
182
+ eps : (float, float), default=(0.3, 0.05)
183
+ Initial and final step size.
184
+ lam : (float, float), optional
185
+ Initial and final neighborhood range (default ``(0.2 * n_nodes, 0.01)``).
186
+ init : {"range", "sample"} or ndarray, default="range"
187
+ random_state : int, RandomState or None
188
+ """
189
+
190
+ def __init__(self, n_nodes=50, *, max_iter=None, eps=(0.3, 0.05), lam=None, init="range", random_state=None):
191
+ self.n_nodes = n_nodes
192
+ self.max_iter = max_iter
193
+ self.eps = eps
194
+ self.lam = lam
195
+ self.init = init
196
+ self.random_state = random_state
197
+
198
+ def _schedule(self, n):
199
+ t_max = int(self.max_iter or 200 * n)
200
+ lam = self.lam if self.lam is not None else (0.2 * n, 0.01)
201
+ return t_max, lam
202
+
203
+ def _ng_step(self, W, x, t, t_max, lam):
204
+ d2 = ((W - x) ** 2).sum(1)
205
+ order = np.argsort(d2)
206
+ rank = np.empty(len(W))
207
+ rank[order] = np.arange(len(W))
208
+ e = decay(self.eps[0], self.eps[1], t, t_max)
209
+ la = decay(lam[0], lam[1], t, t_max)
210
+ W += (e * np.exp(-rank / la))[:, None] * (x - W)
211
+ return order
212
+
213
+ def fit(self, X, y=None):
214
+ X = as_data(X)
215
+ rng = check_random_state(self.random_state)
216
+ n = int(self.n_nodes)
217
+ W = self._init_nodes(X, n, rng)
218
+ t_max, lam = self._schedule(n)
219
+ draws = rng.randint(len(X), size=t_max)
220
+ for t in range(t_max):
221
+ self._ng_step(W, X[draws[t]], t + 1, t_max, lam)
222
+ return self._finish(X, W, None)
223
+
224
+
225
+ class TopologyRepresentingNetwork(NeuralGas):
226
+ r"""Topology representing network (TRN; Martinetz and Schulten 1994).
227
+
228
+ Neural gas adaptation combined with competitive Hebbian learning: after
229
+ each step the nearest and second nearest node of the drawn sample are
230
+ linked (or their link is refreshed, age 0), the ages of all other links of
231
+ the winner grow by one, and links older than the lifetime
232
+ :math:`T(t)` are removed. The resulting graph approximates the induced
233
+ Delaunay triangulation of the nodes, i.e. it connects nodes whose Voronoi
234
+ cells are adjacent *where data exist*.
235
+
236
+ Parameters
237
+ ----------
238
+ prune : bool, default=True
239
+ After training, delete the links that no sample supports any more
240
+ (no sample has their two end points as nearest and second nearest
241
+ node). This removes stale links created while the nodes were moving.
242
+ lifetime : (float, float), optional
243
+ Initial and final edge lifetime :math:`(T_i, T_f)`; default
244
+ ``(0.1 * n_nodes, 0.5 * n_nodes)``: the lifetime grows, as recommended
245
+ by Martinetz and Schulten, so that early links of the still moving nodes
246
+ are forgotten quickly and the final links persist.
247
+ The other parameters are those of :class:`NeuralGas`.
248
+
249
+ Attributes
250
+ ----------
251
+ edge_strength_ : ndarray (n_nodes, n_nodes)
252
+ Time-weighted count of refreshes of every edge (:math:`\sum t/t_{\max}`),
253
+ useful to tell persistent from transient links.
254
+ """
255
+
256
+ def __init__(
257
+ self,
258
+ n_nodes=50,
259
+ *,
260
+ max_iter=None,
261
+ eps=(0.3, 0.05),
262
+ lam=None,
263
+ lifetime=None,
264
+ prune=True,
265
+ init="range",
266
+ random_state=None,
267
+ ):
268
+ super().__init__(n_nodes, max_iter=max_iter, eps=eps, lam=lam, init=init, random_state=random_state)
269
+ self.lifetime = lifetime
270
+ self.prune = prune
271
+
272
+ def fit(self, X, y=None):
273
+ X = as_data(X)
274
+ rng = check_random_state(self.random_state)
275
+ n = int(self.n_nodes)
276
+ W = self._init_nodes(X, n, rng)
277
+ t_max, lam = self._schedule(n)
278
+ Ti, Tf = self.lifetime if self.lifetime is not None else (0.1 * n, 0.5 * n)
279
+ C = np.zeros((n, n), bool)
280
+ age = np.zeros((n, n))
281
+ strength = np.zeros((n, n))
282
+ draws = rng.randint(len(X), size=t_max)
283
+ for t in range(1, t_max + 1):
284
+ order = self._ng_step(W, X[draws[t - 1]], t, t_max, lam)
285
+ a, b = order[0], order[1]
286
+ C[a, b] = C[b, a] = True
287
+ age[a, b] = age[b, a] = 0.0
288
+ strength[a, b] += t / t_max
289
+ strength[b, a] = strength[a, b]
290
+ nb = C[a]
291
+ age[a, nb] += 1.0
292
+ age[nb, a] = age[a, nb]
293
+ T = decay(Ti, Tf, t, t_max)
294
+ old = nb & (age[a] > T)
295
+ C[a, old] = C[old, a] = False
296
+ age[a, old] = age[old, a] = 0.0
297
+ if self.prune:
298
+ # keep only links that are still the first-second winner pair of some sample
299
+ C &= competitive_hebbian_graph(X, W).toarray() > 0
300
+ self.edge_strength_ = strength * C
301
+ return self._finish(X, W, C)
302
+
303
+
304
+ # =========================================================================== growing networks
305
+ class _DynamicGraph:
306
+ """Resizable node/edge store used by the growing networks."""
307
+
308
+ def __init__(self, dim, cap=64):
309
+ self.W = np.zeros((cap, dim))
310
+ self.active = np.zeros(cap, bool)
311
+ self.C = np.zeros((cap, cap), bool)
312
+ self.age = np.zeros((cap, cap))
313
+ self.err = np.zeros(cap)
314
+ self.weight = np.zeros(cap)
315
+ self.eweight = np.zeros((cap, cap))
316
+ self.habit = np.ones(cap)
317
+
318
+ def _grow(self):
319
+ cap = len(self.active)
320
+ new = 2 * cap
321
+ for name in ("W",):
322
+ A = getattr(self, name)
323
+ B = np.zeros((new, A.shape[1]))
324
+ B[:cap] = A
325
+ setattr(self, name, B)
326
+ for name, fill in (("active", False), ("err", 0.0), ("weight", 0.0), ("habit", 1.0)):
327
+ A = getattr(self, name)
328
+ B = np.full(new, fill, dtype=A.dtype)
329
+ B[:cap] = A
330
+ setattr(self, name, B)
331
+ for name in ("C", "age", "eweight"):
332
+ A = getattr(self, name)
333
+ B = np.zeros((new, new), dtype=A.dtype)
334
+ B[:cap, :cap] = A
335
+ setattr(self, name, B)
336
+
337
+ def add(self, w):
338
+ free = np.flatnonzero(~self.active)
339
+ if len(free) == 0:
340
+ self._grow()
341
+ free = np.flatnonzero(~self.active)
342
+ i = free[0]
343
+ self.W[i] = w
344
+ self.active[i] = True
345
+ self.C[i, :] = self.C[:, i] = False
346
+ self.age[i, :] = self.age[:, i] = 0.0
347
+ self.eweight[i, :] = self.eweight[:, i] = 0.0
348
+ self.err[i] = 0.0
349
+ self.weight[i] = 0.0
350
+ self.habit[i] = 1.0
351
+ return i
352
+
353
+ def connect(self, a, b):
354
+ self.C[a, b] = self.C[b, a] = True
355
+ self.age[a, b] = self.age[b, a] = 0.0
356
+
357
+ def disconnect(self, a, b):
358
+ self.C[a, b] = self.C[b, a] = False
359
+ self.age[a, b] = self.age[b, a] = 0.0
360
+ self.eweight[a, b] = self.eweight[b, a] = 0.0
361
+
362
+ def nearest(self, x, k=2):
363
+ idx = np.flatnonzero(self.active)
364
+ d2 = ((self.W[idx] - x) ** 2).sum(1)
365
+ o = np.argsort(d2)[:k]
366
+ return idx[o], d2[o]
367
+
368
+ def remove_old_edges(self, a, T):
369
+ old = self.C[a] & (self.age[a] > T)
370
+ for b in np.flatnonzero(old):
371
+ self.disconnect(a, b)
372
+
373
+ def remove_all_old_edges(self, T):
374
+ old = self.C & (self.age > T)
375
+ self.C[old] = False
376
+ self.age[old] = 0.0
377
+ self.eweight[old] = 0.0
378
+
379
+ def remove_isolated(self, keep_min=2):
380
+ iso = self.active & ~self.C.any(1)
381
+ if self.active.sum() - iso.sum() >= keep_min:
382
+ self.active[iso] = False
383
+
384
+ def export(self):
385
+ idx = np.flatnonzero(self.active)
386
+ return idx, self.W[idx].copy(), self.C[np.ix_(idx, idx)].copy()
387
+
388
+
389
+ class GrowingNeuralGas(BaseTopologyLearner):
390
+ r"""Growing neural gas (GNG; Fritzke 1995).
391
+
392
+ Starts with two nodes and grows: the winner :math:`s_1` of each drawn
393
+ sample accumulates the squared error, moves towards the sample with step
394
+ :math:`\varepsilon_b`, its graph neighbors with :math:`\varepsilon_n`;
395
+ :math:`s_1` and the second nearest node :math:`s_2` are linked
396
+ (age 0), edges older than ``max_age`` are deleted together with the nodes
397
+ left isolated, and every ``lambda_`` steps a new node is inserted halfway
398
+ between the node :math:`q` with the largest error and its neighbor
399
+ :math:`f` with the largest error. Errors decay by ``alpha`` at insertion and
400
+ by ``d`` in every step. Training stops after ``max_iter`` steps or when
401
+ ``max_nodes`` is reached.
402
+ """
403
+
404
+ def __init__(
405
+ self,
406
+ max_nodes=100,
407
+ *,
408
+ max_iter=None,
409
+ eps_b=0.05,
410
+ eps_n=0.006,
411
+ max_age=50,
412
+ lambda_=100,
413
+ alpha=0.5,
414
+ d=0.995,
415
+ init="sample",
416
+ random_state=None,
417
+ ):
418
+ self.max_nodes = max_nodes
419
+ self.max_iter = max_iter
420
+ self.eps_b = eps_b
421
+ self.eps_n = eps_n
422
+ self.max_age = max_age
423
+ self.lambda_ = lambda_
424
+ self.alpha = alpha
425
+ self.d = d
426
+ self.init = init
427
+ self.random_state = random_state
428
+
429
+ def fit(self, X, y=None):
430
+ X = as_data(X, min_samples=2)
431
+ rng = check_random_state(self.random_state)
432
+ G = _DynamicGraph(X.shape[1])
433
+ for w in self._init_nodes(X, 2, rng):
434
+ G.add(w)
435
+ t_max = int(self.max_iter or self.lambda_ * self.max_nodes * 2)
436
+ draws = rng.randint(len(X), size=t_max)
437
+ for t in range(1, t_max + 1):
438
+ x = X[draws[t - 1]]
439
+ (s1, s2), d2 = G.nearest(x, 2)
440
+ nb = G.C[s1]
441
+ G.age[s1, nb] += 1
442
+ G.age[nb, s1] = G.age[s1, nb]
443
+ G.err[s1] += d2[0]
444
+ G.W[s1] += self.eps_b * (x - G.W[s1])
445
+ G.W[nb] += self.eps_n * (x - G.W[nb])
446
+ G.connect(s1, s2)
447
+ G.remove_old_edges(s1, self.max_age)
448
+ G.remove_isolated()
449
+ if t % self.lambda_ == 0 and G.active.sum() < self.max_nodes:
450
+ act = np.flatnonzero(G.active)
451
+ q = act[np.argmax(G.err[act])]
452
+ nbq = np.flatnonzero(G.C[q])
453
+ if len(nbq):
454
+ f = nbq[np.argmax(G.err[nbq])]
455
+ r = G.add(0.5 * (G.W[q] + G.W[f]))
456
+ G.disconnect(q, f)
457
+ G.connect(q, r)
458
+ G.connect(f, r)
459
+ G.err[q] *= self.alpha
460
+ G.err[f] *= self.alpha
461
+ G.err[r] = G.err[q]
462
+ G.err[G.active] *= self.d
463
+ _, W, C = G.export()
464
+ return self._finish(X, W, C)
465
+
466
+
467
+ class GrowWhenRequired(BaseTopologyLearner):
468
+ r"""Grow when required network (GWR; Marsland, Shapiro and Nehmzow 2002).
469
+
470
+ A node is inserted as soon as the winner represents the current sample
471
+ poorly, not at fixed intervals: when the activity
472
+ :math:`a=\exp(-\|\mathbf{x}-\mathbf{w}_{s_1}\|)` is below
473
+ ``activity_threshold`` and the winner has already been trained (its
474
+ habituation :math:`h_{s_1}` has dropped below ``habituation_threshold``),
475
+ a new node is placed at :math:`(\mathbf{w}_{s_1}+\mathbf{x})/2` and linked
476
+ to :math:`s_1` and :math:`s_2`. Otherwise the winner and its neighbors move
477
+ towards the sample with steps proportional to their habituation, which
478
+ decays towards zero with use. Edges age as in GNG. GWR reacts quickly to
479
+ new regions of the input space, which makes it popular for streaming data
480
+ and robotics.
481
+
482
+ ``activity_threshold`` refers to data scaled to roughly unit range.
483
+ """
484
+
485
+ def __init__(
486
+ self,
487
+ *,
488
+ activity_threshold=0.9,
489
+ habituation_threshold=0.1,
490
+ eps_b=0.1,
491
+ eps_n=0.01,
492
+ tau_b=0.3,
493
+ tau_n=0.1,
494
+ max_age=50,
495
+ max_nodes=500,
496
+ n_epochs=5,
497
+ init="sample",
498
+ random_state=None,
499
+ ):
500
+ self.activity_threshold = activity_threshold
501
+ self.habituation_threshold = habituation_threshold
502
+ self.eps_b = eps_b
503
+ self.eps_n = eps_n
504
+ self.tau_b = tau_b
505
+ self.tau_n = tau_n
506
+ self.max_age = max_age
507
+ self.max_nodes = max_nodes
508
+ self.n_epochs = n_epochs
509
+ self.init = init
510
+ self.random_state = random_state
511
+
512
+ def fit(self, X, y=None):
513
+ X = as_data(X, min_samples=2)
514
+ rng = check_random_state(self.random_state)
515
+ G = _DynamicGraph(X.shape[1])
516
+ for w in self._init_nodes(X, 2, rng):
517
+ G.add(w)
518
+ kappa = 1.05
519
+ for _ in range(int(self.n_epochs)):
520
+ for k in rng.permutation(len(X)):
521
+ x = X[k]
522
+ (s1, s2), d2 = G.nearest(x, 2)
523
+ G.connect(s1, s2)
524
+ act = np.exp(-np.sqrt(d2[0]))
525
+ if (
526
+ act < self.activity_threshold
527
+ and G.habit[s1] < self.habituation_threshold
528
+ and G.active.sum() < self.max_nodes
529
+ ):
530
+ r = G.add(0.5 * (G.W[s1] + x))
531
+ G.disconnect(s1, s2)
532
+ G.connect(r, s1)
533
+ G.connect(r, s2)
534
+ else:
535
+ nb = np.flatnonzero(G.C[s1])
536
+ G.W[s1] += self.eps_b * G.habit[s1] * (x - G.W[s1])
537
+ G.W[nb] += self.eps_n * G.habit[nb][:, None] * (x - G.W[nb])
538
+ # habituation dynamics (closed-form step of the ODE of the original paper)
539
+ G.habit[s1] += self.tau_b * kappa * (1.0 - G.habit[s1]) - self.tau_b
540
+ G.habit[nb] += self.tau_n * kappa * (1.0 - G.habit[nb]) - self.tau_n
541
+ G.habit[[s1, *nb]] = np.clip(G.habit[[s1, *nb]], 0.0, 1.0)
542
+ nb = G.C[s1]
543
+ G.age[s1, nb] += 1
544
+ G.age[nb, s1] = G.age[s1, nb]
545
+ G.remove_old_edges(s1, self.max_age)
546
+ G.remove_isolated()
547
+ _, W, C = G.export()
548
+ return self._finish(X, W, C)
549
+
550
+
551
+ class DynamicTopologyRepresentingNetwork(BaseTopologyLearner):
552
+ r"""Dynamic topology representing network (DTRN; Si, Lin and Vuong 2000).
553
+
554
+ Grows from a single node by a vigilance test: if the winner
555
+ :math:`\mathbf{w}_c` of the drawn sample is farther than the vigilance
556
+ threshold :math:`\rho(t)`, the sample itself becomes a new node linked to
557
+ the winner. Otherwise the winner and its graph neighbors move towards the
558
+ sample with Gaussian-normalized steps
559
+
560
+ .. math:: \Delta\mathbf{w}_i = \alpha(t)\,\frac{s_{ci}\,e^{-\beta\|\mathbf{x}-\mathbf{w}_i\|^2}}
561
+ {\sum_j s_{cj}\,e^{-\beta\|\mathbf{x}-\mathbf{w}_j\|^2}}\,(\mathbf{x}-\mathbf{w}_i),
562
+
563
+ (:math:`s_{ci}=1` for the winner and its neighbors) and the winner is linked
564
+ to the second nearest node. Links of the winner older than ``max_age``
565
+ are deleted and isolated nodes are removed. :math:`\rho` decays from
566
+ ``rho[0]`` (default: mean standard deviation of the features) to
567
+ ``rho[1]``; the annealing parameter :math:`\beta` grows by a factor 100.
568
+ """
569
+
570
+ def __init__(self, *, max_iter=1000, alpha=(0.05, 0.0005), rho=(None, 0.1), max_age=5, random_state=None):
571
+ self.max_iter = max_iter
572
+ self.alpha = alpha
573
+ self.rho = rho
574
+ self.max_age = max_age
575
+ self.random_state = random_state
576
+
577
+ def fit(self, X, y=None):
578
+ X = as_data(X, min_samples=2)
579
+ rng = check_random_state(self.random_state)
580
+ t_max = int(self.max_iter)
581
+ rho_i = self.rho[0] if self.rho[0] is not None else float(X.std(0).mean())
582
+ rho_f = self.rho[1]
583
+ beta_i = 2.0 / decay(rho_i, rho_f, 1, t_max) ** 2
584
+ G = _DynamicGraph(X.shape[1])
585
+ G.add(X[rng.randint(len(X))])
586
+ draws = rng.randint(len(X), size=t_max)
587
+ for t in range(1, t_max + 1):
588
+ x = X[draws[t - 1]]
589
+ near, d2 = G.nearest(x, 2)
590
+ c = near[0]
591
+ rho = decay(rho_i, rho_f, t, t_max)
592
+ a = decay(self.alpha[0], self.alpha[1], t, t_max)
593
+ beta = decay(beta_i, 100 * beta_i, t, t_max)
594
+ if np.sqrt(d2[0]) < rho:
595
+ grp = np.r_[c, np.flatnonzero(G.C[c])]
596
+ g = np.exp(-beta * ((x - G.W[grp]) ** 2).sum(1))
597
+ s = g.sum()
598
+ if s > 0:
599
+ G.W[grp] += (a * g / s)[:, None] * (x - G.W[grp])
600
+ if len(near) > 1:
601
+ G.connect(c, near[1])
602
+ else:
603
+ r = G.add(x.copy())
604
+ G.connect(r, c)
605
+ nb = G.C[c]
606
+ G.age[c, nb] += 1
607
+ G.age[nb, c] = G.age[c, nb]
608
+ G.remove_old_edges(c, self.max_age)
609
+ if G.active.sum() > 1:
610
+ G.remove_isolated(keep_min=1)
611
+ _, W, C = G.export()
612
+ return self._finish(X, W, C)
613
+
614
+
615
+ class WeightedIncrementalNetwork(BaseTopologyLearner):
616
+ r"""Weighted incremental neural network (WINN; Muhammed 2004).
617
+
618
+ A growing network in the spirit of GNG that also estimates local
619
+ densities: every drawn sample increments the weight of its ``n_winners``
620
+ nearest nodes and the weight of the edges between the winner and the other
621
+ winners, so that node and edge weights become proportional to the local
622
+ data density. Nodes are inserted every ``lambda_`` signals between the
623
+ node of largest error and its neighbor of largest error (the new node
624
+ inherits the averaged node weight and the old edge weight). The original
625
+ paper proposes ``max_age = N / 10``; much smaller values (3--10) remove
626
+ spurious links on curved manifolds.
627
+
628
+ Attributes
629
+ ----------
630
+ node_weights_ : ndarray (n_nodes,)
631
+ edge_weights_ : ndarray (n_nodes, n_nodes)
632
+ """
633
+
634
+ def __init__(
635
+ self,
636
+ n_nodes=100,
637
+ *,
638
+ n_signals=None,
639
+ n_winners=2,
640
+ eps_b=0.05,
641
+ eps_n=0.0006,
642
+ alpha=0.5,
643
+ d=0.9995,
644
+ max_age=None,
645
+ init="sample",
646
+ random_state=None,
647
+ ):
648
+ self.n_nodes = n_nodes
649
+ self.n_signals = n_signals
650
+ self.n_winners = n_winners
651
+ self.eps_b = eps_b
652
+ self.eps_n = eps_n
653
+ self.alpha = alpha
654
+ self.d = d
655
+ self.max_age = max_age
656
+ self.init = init
657
+ self.random_state = random_state
658
+
659
+ def fit(self, X, y=None):
660
+ X = as_data(X, min_samples=2)
661
+ rng = check_random_state(self.random_state)
662
+ N = len(X)
663
+ n_sig = int(self.n_signals or 50 * N)
664
+ lam = max(1, n_sig // int(self.n_nodes))
665
+ max_age = self.max_age if self.max_age is not None else N / 10
666
+ G = _DynamicGraph(X.shape[1])
667
+ a0, b0 = (G.add(w) for w in self._init_nodes(X, 2, rng))
668
+ G.connect(a0, b0)
669
+ draws = rng.randint(N, size=n_sig)
670
+ for t in range(1, n_sig + 1):
671
+ x = X[draws[t - 1]]
672
+ win, d2 = G.nearest(x, int(self.n_winners))
673
+ s1 = win[0]
674
+ G.weight[win] += 1
675
+ nb = G.C[s1]
676
+ G.age[s1, nb] += 1
677
+ G.age[nb, s1] = G.age[s1, nb]
678
+ G.err[s1] += d2[0]
679
+ G.W[s1] += self.eps_b * (x - G.W[s1])
680
+ G.W[nb] += self.eps_n * (x - G.W[nb])
681
+ for o in win[1:]:
682
+ G.connect(s1, o)
683
+ G.eweight[s1, o] += 1
684
+ G.eweight[o, s1] = G.eweight[s1, o]
685
+ G.remove_all_old_edges(max_age)
686
+ G.remove_isolated()
687
+ if t % lam == 0 and G.active.sum() < self.n_nodes:
688
+ act = np.flatnonzero(G.active)
689
+ q = act[np.argmax(G.err[act])]
690
+ nbq = np.flatnonzero(G.C[q])
691
+ if len(nbq):
692
+ f = nbq[np.argmax(G.err[nbq])]
693
+ ew = G.eweight[q, f]
694
+ r = G.add(0.5 * (G.W[q] + G.W[f]))
695
+ G.weight[r] = 0.5 * (G.weight[q] + G.weight[f])
696
+ G.disconnect(q, f)
697
+ for o in (q, f):
698
+ G.connect(r, o)
699
+ G.eweight[r, o] = G.eweight[o, r] = ew
700
+ G.err[q] *= self.alpha
701
+ G.err[f] *= self.alpha
702
+ G.err[r] = G.err[q]
703
+ G.err[G.active] *= self.d
704
+ idx, W, C = G.export()
705
+ self.node_weights_ = G.weight[idx].copy()
706
+ self.edge_weights_ = G.eweight[np.ix_(idx, idx)] * C
707
+ return self._finish(X, W, C)