GTSOM Tutorial: General Topology Learning on Synthetic Blobs¶
Beyond the grid: data-driven output topology¶
The companion tutorial, GTSOM Tutorial: Mapping MNIST Handwritten Digits, trains a SOM on a fixed hexagonal grid (GTSOM.from_grid). That grid is chosen up front by the user — its shape, size, and connectivity are decided before training begins and have nothing to do with the structure of the data itself.
GTSOM's namesake feature is the ability to do without that fixed grid entirely. Instead of a regular lattice, the output space topology can be derived directly from the data: prototype positions are projected into a low-dimensional embedding (via PCA, Laplacian Eigenmaps, or a random projection), and the neuron adjacency graph is then built from those projected positions using a proximity graph — a Delaunay triangulation or a Gabriel graph. This tutorial demonstrates that workflow (GTSOM.from_data) on a synthetic dataset designed to make the resulting topology easy to see and interpret.
What we will do¶
- Generate 5 well-separated Gaussian blobs in 10 dimensions (N=5,000)
- Initialize a 100-prototype GTSOM with a data-driven topology, using PCA for prototype coordinates and a Gabriel graph for adjacency
- Train and inspect the learned map
- Discuss what the Gabriel graph is, how it relates to a Delaunay triangulation, and when you might prefer one over the other
1. Imports¶
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from gtsom import GTSOM
%matplotlib inline
plt.rcParams['figure.dpi'] = 120
2. Generating the Data¶
We use sklearn.datasets.make_blobs to generate 5 isotropic Gaussian clusters in 10 dimensions, with 5,000 total samples (1,000 per cluster) and unit standard deviation within each cluster. In 10 dimensions, even moderately-spaced cluster centers produce blobs that are extremely well separated — Euclidean distances between different clusters' points grow much faster than distances within a cluster as dimensionality increases. This gives us labeled data with unambiguous ground-truth structure, which makes it easy to visually verify that GTSOM's learned topology recovers the true cluster organization.
The features are standardized (zero mean, unit variance per dimension) before training, since GTSOM performs no internal scaling of its own.
SEED = 42
N = 5_000
D = 10
N_BLOBS = 5
X_raw, y = make_blobs(
n_samples=N,
n_features=D,
centers=N_BLOBS,
cluster_std=1.0,
random_state=SEED,
)
print(f"Generated: {X_raw.shape}, labels: {np.unique(y)}")
print(f"Label counts: { {c: int((y==c).sum()) for c in range(N_BLOBS)} }")
scaler = StandardScaler()
X = scaler.fit_transform(X_raw).astype(np.float32)
print(f"Standardized: mean~0, std~1 per feature")
Generated: (5000, 10), labels: [0 1 2 3 4]
Label counts: {0: 1000, 1: 1000, 2: 1000, 3: 1000, 4: 1000}
Standardized: mean~0, std~1 per feature
3. A Reference PCA Projection¶
Before training, it's useful to see what the data actually looks like. We compute a standalone 2-D PCA projection purely for visualization — this is not the same PCA that GTSOM will use internally to place prototypes; it's just a sanity check on the data's separability. GTSOM trains directly on the standardized 10-D data, not on this projection.
pca_ref = PCA(n_components=2, random_state=SEED)
Z_ref = pca_ref.fit_transform(X)
print(f"Reference 2-D PCA projection: variance explained = "
f"{pca_ref.explained_variance_ratio_.sum()*100:.1f}%")
fig, ax = plt.subplots(figsize=(6, 5))
for c in range(N_BLOBS):
mask = y == c
ax.scatter(Z_ref[mask, 0], Z_ref[mask, 1], s=8, alpha=0.6, label=f'Blob {c}')
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_title('Reference PCA projection of the 10-D blobs')
ax.legend(fontsize=8, markerscale=2)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Reference 2-D PCA projection: variance explained = 76.0%
4. Choosing a Data-Driven Output Topology¶
From a fixed grid to a learned topology¶
GTSOM.from_grid requires choosing a lattice shape (e.g. 20×20 hex) before seeing how the data is actually structured. GTSOM.from_data instead builds the output topology from the data itself, in three steps:
- Find prototype vectors.
Mprototypes are computed from the input data — either via k-means (W_init='kmeans') or random sampling (W_init='random'). We use k-means here, since cluster centroids in well-separated data are a natural and efficient way to seed prototype positions. - Project prototypes to low dimensions. The
Mprototype vectors are projected intocoord_dimdimensions (2 or 3) to define their positions in output space — thecoord_initparameter controls how ('pca','le'for Laplacian Eigenmaps,'random', or'random_proj'). We use'pca', which pairs naturally with k-means prototypes since cluster centroids carry real data structure that a linear projection can faithfully summarize. - Build the adjacency graph. Once prototypes have 2-D (or 3-D) positions,
coord_topodetermines which proximity graph connects them — either a Delaunay triangulation or a Gabriel graph. This graph is the SOM's output space topology: it defines which prototypes are considered neighbors during training, replacing the fixed grid adjacency used byfrom_grid.
Delaunay triangulation vs. Gabriel graph¶
Both are classic proximity graphs built from a set of points in the plane (or higher dimensions), and they're closely related: the Gabriel graph is always a subgraph of the Delaunay triangulation — every Gabriel edge is also a Delaunay edge, but not vice versa.
A Delaunay triangulation connects two points if there exists a circle passing through both that contains no other point in its interior. It produces a dense, fully triangulated mesh.
A Gabriel graph is more restrictive: two points are connected only if the circle having the segment between them as its diameter contains no other point. This is a stricter emptiness condition than Delaunay's (the diametric circle is always at least as large as some valid Delaunay circumcircle through the same two points), so the Gabriel graph keeps only a subset of Delaunay edges — typically the "more locally meaningful" ones, discarding long edges that cut across sparse regions even when they happen to satisfy the looser Delaunay condition. Despite being sparser, the Gabriel graph is guaranteed to remain connected for any finite point set in general position, so it never fragments into isolated components.
In practice: Delaunay gives denser connectivity and more redundant neighborhood paths; Gabriel gives a sparser graph that more closely tracks local proximity. gtsom supports both via coord_topo='delaunay' or coord_topo='gabriel'. This tutorial uses Gabriel, since with 5 tightly separated clusters it produces a visually cleaner result — exactly one or two "bridge" edges between each pair of nearby clusters, rather than the denser web of inter-cluster triangles a Delaunay triangulation would add.
5. Initializing the GTSOM¶
We initialize with M=100 prototypes — roughly 50 data points per prototype on average, comparable in density to the MNIST tutorial's 25 points/neuron. nbr_topo_alpha_0 and nbr_topo_alpha_f control a separate, independent feature: a blend between pure output-space (graph) neighborhoods and input-space (Euclidean) neighborhoods during training. This blending is available regardless of whether the topology comes from a grid or from data — it isn't specific to from_data.
M = 100
som = GTSOM(
rho_0=10.0,
rho_f=0.5,
halflife_epochs=100,
n_jobs=-1,
nbr_topo_alpha_0=0.5,
nbr_topo_alpha_f=1.0,
random_state=SEED,
compute_dr_metrics=True,
proto_topo='STK_CADJ',
)
som.from_data(
X,
M=M,
coord_dim=2,
coord_init='pca',
W_init='kmeans',
coord_topo='gabriel',
labels=y,
)
print(som)
print(f"Empty RFs at init: {(som.recaller.RFSize == 0).sum()} / {som.M}")
Running FAISS k-means with 100 clusters (niter=20, nredo=1)... K-means complete. Final MQE: 0.276727 Fitting complete using kmeans method. GTSOM(M=100, d=10, embed_dim=2, fitted=False, age=0, snapshots=1, backend='numba', n_jobs=16, nbr_influence_min=0.01, proto_topo='STK_CADJ', alpha_schedule=ExponentialAnneal(initial=0.5, final=1.0, tau=200), compute_dr_metrics=True, train_time=0.000s) Empty RFs at init: 0 / 100
At initialization, prototypes are seeded by k-means on the standardized data, so the initial map already reflects the cluster structure reasonably well — quite different from the MNIST tutorial, where random initialization left the lattice completely disorganized at age 0. This is expected: k-means itself is already finding the same 5 clusters that the SOM will go on to organize topologically.
g = som.plot(
color_by='labels',
title='GTSOM — Blobs (Gabriel topology)',
subtitle='Initial state (age=0)',
)
g.draw()
6. Training¶
We train for 200 epochs using the same exponential bandwidth decay schedule structure as the MNIST tutorial (see that notebook for a full explanation of rho_0, rho_f, and halflife_epochs). A snapshot of the SOM state is captured every 20 epochs.
som.fit(
X,
n_epochs=200,
labels=y,
verbose=True,
plot_every=20,
)
print()
print(som)
print(f"Empty RFs after fit: {(som.recaller.RFSize == 0).sum()} / {som.M}")
Epoch rho alpha MQE delBMU
----- ------ ------ -------- -------
1 10.0000 0.5000 2.1178 0.9396
2 9.8513 0.5017 1.7521 0.9882
3 9.7049 0.5035 1.7616 0.9948
4 9.5606 0.5052 1.7798 0.9968
5 9.4184 0.5070 1.8009 0.9566
6 9.2784 0.5087 1.6857 0.9908
7 9.1405 0.5105 1.7114 0.9824
8 9.0046 0.5123 1.6740 0.9946
9 8.8707 0.5141 1.7128 0.9452
10 8.7388 0.5158 1.5957 0.9988
----- ------ ------ -------- -------
11 8.6089 0.5176 1.5875 0.9786
12 8.4809 0.5194 1.5434 0.9998
13 8.3548 0.5212 1.5885 1.0000
14 8.2306 0.5230 1.5603 1.0000
15 8.1083 0.5249 1.6031 0.9924
16 7.9877 0.5267 1.5469 0.9996
17 7.8690 0.5285 1.5313 0.9952
18 7.7520 0.5303 1.5165 0.9504
19 7.6367 0.5322 1.5175 0.9996
/usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10
20 7.5232 0.5340 1.4964 0.9994
----- ------ ------ -------- -------
21 7.4113 0.5359 1.5005 0.9678
22 7.3012 0.5377 1.4381 0.9998
23 7.1926 0.5396 1.4117 1.0000
24 7.0857 0.5415 1.4520 0.9992
25 6.9803 0.5434 1.4248 0.9842
26 6.8766 0.5453 1.3736 0.9894
27 6.7743 0.5471 1.4180 0.9440
28 6.6736 0.5490 1.3567 0.9896
29 6.5744 0.5510 1.3818 1.0000
30 6.4767 0.5529 1.3678 0.9008
----- ------ ------ -------- -------
31 6.3804 0.5548 1.3220 0.9872
32 6.2855 0.5567 1.3161 0.9908
33 6.1921 0.5586 1.3524 0.9760
34 6.1000 0.5606 1.2834 0.9944
35 6.0093 0.5625 1.2838 0.9948
36 5.9200 0.5645 1.2581 0.9776
37 5.8320 0.5664 1.2918 0.9800
38 5.7453 0.5684 1.2373 0.9992
39 5.6598 0.5704 1.2342 0.9988
/usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10
40 5.5757 0.5724 1.2248 0.9992
----- ------ ------ -------- -------
41 5.4928 0.5743 1.2071 0.9968
42 5.4111 0.5763 1.1914 0.9964
43 5.3307 0.5783 1.2045 0.9968
44 5.2514 0.5804 1.1565 0.9964
45 5.1734 0.5824 1.1708 0.9932
46 5.0965 0.5844 1.1356 0.9946
47 5.0207 0.5864 1.1496 0.9946
48 4.9460 0.5885 1.1242 0.9946
49 4.8725 0.5905 1.1206 0.9928
50 4.8001 0.5925 1.0966 0.9934
----- ------ ------ -------- -------
51 4.7287 0.5946 1.0876 0.9948
52 4.6584 0.5967 1.0663 0.9946
53 4.5891 0.5987 1.0797 0.9920
54 4.5209 0.6008 1.0587 0.9892
55 4.4537 0.6029 1.0434 0.9898
56 4.3875 0.6050 1.0386 0.9898
57 4.3223 0.6071 1.0251 0.8038
58 4.2580 0.6092 1.0266 0.8130
59 4.1947 0.6113 1.0030 0.8400
/usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10
60 4.1323 0.6134 1.0012 0.8458
----- ------ ------ -------- -------
61 4.0709 0.6156 0.9993 0.8526
62 4.0104 0.6177 0.9832 0.8750
63 3.9508 0.6199 0.9761 0.8380
64 3.8920 0.6220 0.9781 0.8492
65 3.8342 0.6242 0.9610 0.7912
66 3.7772 0.6263 0.9707 0.7750
67 3.7210 0.6285 0.9457 0.8014
68 3.6657 0.6307 0.9483 0.7878
69 3.6112 0.6329 0.9411 0.7128
70 3.5575 0.6351 0.9396 0.7032
----- ------ ------ -------- -------
71 3.5046 0.6373 0.9282 0.6982
72 3.4525 0.6395 0.9228 0.7052
73 3.4012 0.6417 0.9096 0.6308
74 3.3506 0.6439 0.9082 0.6464
75 3.3008 0.6462 0.9032 0.4736
76 3.2517 0.6484 0.8914 0.5924
77 3.2034 0.6507 0.8839 0.5604
78 3.1558 0.6529 0.8839 0.5088
79 3.1088 0.6552 0.8764 0.5034
/usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10
80 3.0626 0.6575 0.8751 0.4694
----- ------ ------ -------- -------
81 3.0171 0.6598 0.8629 0.4802
82 2.9722 0.6620 0.8605 0.4456
83 2.9280 0.6643 0.8536 0.4460
84 2.8845 0.6666 0.8504 0.4202
85 2.8416 0.6690 0.8442 0.4108
86 2.7994 0.6713 0.8368 0.4356
87 2.7578 0.6736 0.8298 0.3980
88 2.7168 0.6760 0.8260 0.3734
89 2.6764 0.6783 0.8205 0.3482
90 2.6366 0.6807 0.8172 0.3324
----- ------ ------ -------- -------
91 2.5974 0.6830 0.8098 0.3474
92 2.5588 0.6854 0.8055 0.3030
93 2.5207 0.6878 0.7999 0.2712
94 2.4833 0.6902 0.7955 0.2396
95 2.4463 0.6926 0.7901 0.1974
96 2.4100 0.6950 0.7858 0.1508
97 2.3741 0.6974 0.7785 0.1790
98 2.3388 0.6998 0.7733 0.1444
99 2.3041 0.7022 0.7685 0.1258
/usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10
100 2.2698 0.7047 0.7641 0.0774
----- ------ ------ -------- -------
101 2.2361 0.7071 0.7597 0.0602
102 2.2028 0.7096 0.7551 0.0464
103 2.1701 0.7120 0.7453 0.0938
104 2.1378 0.7145 0.7410 0.0536
105 2.1060 0.7170 0.7372 0.0448
106 2.0747 0.7195 0.7337 0.0414
107 2.0439 0.7220 0.7303 0.0332
108 2.0135 0.7245 0.7273 0.0358
109 1.9836 0.7270 0.7242 0.0398
110 1.9541 0.7295 0.7139 0.1234
----- ------ ------ -------- -------
111 1.9250 0.7320 0.7106 0.0618
112 1.8964 0.7346 0.7075 0.0538
113 1.8682 0.7371 0.7041 0.0464
114 1.8404 0.7397 0.7006 0.0378
115 1.8131 0.7423 0.6979 0.0278
116 1.7861 0.7448 0.6957 0.0254
117 1.7596 0.7474 0.6936 0.0230
118 1.7334 0.7500 0.6862 0.1020
119 1.7076 0.7526 0.6842 0.0326
120 1.6822 0.7552 0.6822 0.0276
----- ------ ------ -------- -------
121 1.6572 0.7579 0.6801 0.0236
122 1.6326 0.7605 0.6782 0.0182
123 1.6083 0.7631 0.6763 0.0156
124 1.5844 0.7658 0.6745 0.0222
125 1.5609 0.7684 0.6725 0.0208
126 1.5376 0.7711 0.6706 0.0240
127 1.5148 0.7738 0.6643 0.0980
128 1.4923 0.7765 0.6619 0.0352
129 1.4701 0.7792 0.6599 0.0302
130 1.4482 0.7819 0.6580 0.0302
----- ------ ------ -------- -------
131 1.4267 0.7846 0.6559 0.0296
132 1.4055 0.7873 0.6539 0.0256
133 1.3846 0.7900 0.6521 0.0260
134 1.3640 0.7928 0.6502 0.0220
135 1.3437 0.7955 0.6485 0.0152
136 1.3237 0.7983 0.6467 0.0154
137 1.3041 0.8011 0.6450 0.0150
138 1.2847 0.8039 0.6406 0.0714
139 1.2656 0.8066 0.6386 0.0222
140 1.2468 0.8094 0.6370 0.0176
----- ------ ------ -------- -------
141 1.2282 0.8123 0.6354 0.0170
142 1.2100 0.8151 0.6339 0.0158
143 1.1920 0.8179 0.6324 0.0128
144 1.1743 0.8207 0.6308 0.0142
145 1.1568 0.8236 0.6294 0.0124
146 1.1396 0.8265 0.6278 0.0136
147 1.1227 0.8293 0.6262 0.0144
148 1.1060 0.8322 0.6246 0.0146
149 1.0895 0.8351 0.6228 0.0182
150 1.0733 0.8380 0.6176 0.0740
----- ------ ------ -------- -------
151 1.0574 0.8409 0.6149 0.0398
152 1.0417 0.8438 0.6128 0.0382
153 1.0262 0.8467 0.6109 0.0316
154 1.0109 0.8497 0.6093 0.0234
155 0.9959 0.8526 0.6078 0.0198
156 0.9811 0.8556 0.6064 0.0168
157 0.9665 0.8586 0.6050 0.0146
158 0.9521 0.8615 0.6037 0.0132
159 0.9380 0.8645 0.6024 0.0158
160 0.9240 0.8675 0.6008 0.0140
----- ------ ------ -------- -------
161 0.9103 0.8706 0.5993 0.0130
162 0.8967 0.8736 0.5980 0.0138
163 0.8834 0.8766 0.5968 0.0148
164 0.8703 0.8796 0.5955 0.0100
165 0.8573 0.8827 0.5913 0.0546
166 0.8446 0.8858 0.5892 0.0320
167 0.8320 0.8888 0.5868 0.0350
168 0.8197 0.8919 0.5844 0.0358
169 0.8075 0.8950 0.5826 0.0318
170 0.7955 0.8981 0.5811 0.0250
----- ------ ------ -------- -------
171 0.7837 0.9013 0.5798 0.0230
172 0.7720 0.9044 0.5786 0.0162
173 0.7605 0.9075 0.5776 0.0150
174 0.7492 0.9107 0.5765 0.0152
175 0.7381 0.9138 0.5755 0.0154
176 0.7271 0.9170 0.5744 0.0152
177 0.7163 0.9202 0.5734 0.0116
178 0.7056 0.9234 0.5724 0.0108
179 0.6952 0.9266 0.5714 0.0108
180 0.6848 0.9298 0.5705 0.0082
----- ------ ------ -------- -------
181 0.6746 0.9330 0.5695 0.0084
182 0.6646 0.9363 0.5686 0.0096
183 0.6547 0.9395 0.5676 0.0114
184 0.6450 0.9428 0.5639 0.0460
185 0.6354 0.9461 0.5624 0.0208
186 0.6260 0.9493 0.5614 0.0124
187 0.6167 0.9526 0.5605 0.0112
188 0.6075 0.9559 0.5597 0.0090
189 0.5985 0.9593 0.5589 0.0072
190 0.5896 0.9626 0.5582 0.0076
----- ------ ------ -------- -------
191 0.5808 0.9659 0.5575 0.0068
192 0.5722 0.9693 0.5569 0.0068
193 0.5637 0.9727 0.5561 0.0088
194 0.5553 0.9760 0.5554 0.0078
195 0.5470 0.9794 0.5547 0.0060
196 0.5389 0.9828 0.5540 0.0048
197 0.5309 0.9862 0.5534 0.0062
198 0.5230 0.9897 0.5527 0.0064
199 0.5152 0.9931 0.5521 0.0078
200 0.5075 0.9965 0.5513 0.0076
----- ------ ------ -------- -------
----- ------ ------ -------- -------
GTSOM(M=100, d=10, embed_dim=2, fitted=True, age=200, snapshots=201, backend='numba', n_jobs=16, nbr_influence_min=0.01, proto_topo='STK_CADJ', alpha_schedule=ExponentialAnneal(initial=0.5, final=1.0, tau=200), compute_dr_metrics=True, train_time=19.945s)
Empty RFs after fit: 6 / 100
7. Saving and Loading¶
Once training is complete, it is good practice to save the fitted SOM to disk. A trained model can take minutes to hours to produce depending on dataset size and the number of epochs — saving it means you never have to re-run training just to regenerate a plot, run additional analysis, or share the result with a collaborator.
GTSOM.save() serializes the complete object state to a single HDF5 file: the prototype matrix, the output topology (embedding coordinates, adjacency graph, and geodesic distances), the full learn_history_ (every snapshot, including MQE, delBMU, receptive field sizes, and DR metrics), the color table, and all hyperparameters needed to reconstruct the learning schedule. Nothing is left out — the loaded object is fully equivalent to the one that was saved.
GTSOM.load() reconstructs the object without any user intervention. The returned instance is immediately usable: you can call plot(), get_snapshot_fig(), transform(), or fit() on it as if training had just finished. Calling fit() on a loaded SOM resumes training from where it left off — the age counter increments from its saved value, the learning schedule continues from the correct position, and new snapshots are appended to the existing history.
# Save the fitted SOM to an HDF5 file
som.save("blobs_som.h5")
print(f"Saved: blobs_som.h5")
# Load it back — fully equivalent to the original
som_loaded = GTSOM.load("blobs_som.h5")
print(f"Loaded: age={som_loaded.age}, snapshots={len(som_loaded.learn_history_)}")
print(som_loaded)
# Resume training for 10 more epochs
# The schedule, age counter, and history all continue seamlessly from the saved state
som_loaded.fit(X, n_epochs=10, labels=y, verbose=True, plot_every=0)
print(f"After resume: age={som_loaded.age}, snapshots={len(som_loaded.learn_history_)}")
# Use the loaded (and further-trained) SOM for all subsequent cells
som = som_loaded
Saved: blobs_som.h5
Loaded: age=200, snapshots=201
GTSOM(M=100, d=10, embed_dim=2, fitted=True, age=200, snapshots=201, backend='numba', n_jobs=16, nbr_influence_min=0.01, proto_topo='STK_CADJ', alpha_schedule=ExponentialAnneal(initial=0.5, final=1.0, tau=200), compute_dr_metrics=True, train_time=19.945s)
Epoch rho alpha MQE delBMU
----- ------ ------ -------- -------
201 0.5000 1.0000 0.5506 0.0074
202 0.5000 1.0000 0.5503 0.0054
203 0.5000 1.0000 0.5502 0.0054
204 0.5000 1.0000 0.5500 0.0034
205 0.5000 1.0000 0.5499 0.0032
206 0.5000 1.0000 0.5499 0.0020
207 0.5000 1.0000 0.5498 0.0020
208 0.5000 1.0000 0.5498 0.0014
209 0.5000 1.0000 0.5497 0.0016
210 0.5000 1.0000 0.5497 0.0030
----- ------ ------ -------- -------
----- ------ ------ -------- -------
After resume: age=210, snapshots=211
8. Learning Curves¶
As in the MNIST tutorial, two quantities are monitored at every epoch: global MQE (root-mean-square distance from each point to its nearest prototype) and delBMU (the proportion of points whose nearest prototype changed since the previous epoch). Because the blobs are already well-separated at initialization (thanks to k-means seeding), expect both curves to settle more quickly and with less dramatic early movement than in the MNIST tutorial, where prototypes started from random positions.
ages_arr = np.array([s['age'] for s in som.learn_history_])
mqes_arr = np.array([s['mqe'] for s in som.learn_history_])
delbmu_arr = np.array([s['delBMU'] for s in som.learn_history_])
fig, (ax_mqe, ax_del) = plt.subplots(1, 2, figsize=(13, 4))
ax_mqe.plot(ages_arr, mqes_arr, 'o-', lw=1.5, ms=3, color='steelblue')
ax_mqe.axvline(0, color='dimgrey', lw=0.8, linestyle='--', label='Init (age=0)')
ax_mqe.set_xlabel('Age (epochs)')
ax_mqe.set_ylabel('Global MQE')
ax_mqe.set_title('SOM Learning\nGlobal MQE')
ax_mqe.legend(fontsize=8)
ax_mqe.grid(True, alpha=0.3)
ax_del.plot(ages_arr, delbmu_arr, 'o-', lw=1.5, ms=3, color='darkorange')
ax_del.axvline(0, color='dimgrey', lw=0.8, linestyle='--', label='Init (age=0)')
ax_del.set_xlabel('Age (epochs)')
ax_del.set_ylabel('delBMU')
ax_del.set_title('SOM Learning\nProportion of changed BMUs')
ax_del.set_ylim(-0.05, 1.05)
ax_del.legend(fontsize=8)
ax_del.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
9. The Final Learned Map¶
The map below shows the trained SOM colored by the plurality label at each neuron. Five tight clusters should be clearly visible, each dominated by a single blob label, connected by a small number of long "bridge" edges — the Gabriel graph's minimal connections between otherwise well-separated regions.
g = som.plot(
color_by='labels',
title='GTSOM — Blobs (Gabriel topology)',
subtitle=f'age={som.age}',
)
g.draw()
Quantization error and receptive field size¶
Coloring by MQE and by receptive field size gives two further diagnostic views. Within each of the 5 clusters, receptive field sizes should be fairly uniform and substantial (tens of points per prototype). A small number of prototypes — typically those that initialized into the sparse space between clusters rather than inside one — may show very small or even empty receptive fields. This is a structural property of fitting a data-driven topology to data with genuine gaps: a fixed grid (from_grid) guarantees every neuron sits inside the data cloud by construction, but a data-driven topology has no such guarantee, since prototype positions are determined by the data itself rather than fixed in advance.
for color_by in ['mqe', 'rfsize']:
g = som.plot(
color_by=color_by,
title='GTSOM — Blobs (Gabriel topology)',
subtitle=f'age={som.age}, color_by={color_by!r}',
)
display(g)
10. A Quick Comparison: Delaunay Topology on the Same Data¶
To make the Delaunay/Gabriel distinction concrete, we re-initialize an identical GTSOM but with coord_topo='delaunay' instead of 'gabriel', using the same random seed and prototype count. Since every Gabriel edge is also a Delaunay edge, expect the Delaunay version to show all the same cluster and bridge structure as before, plus additional edges — most visibly, extra triangulated connections within each cluster and possibly more than one bridge edge between cluster pairs.
som_delaunay = GTSOM(
rho_0=10.0,
rho_f=0.5,
halflife_epochs=100,
n_jobs=-1,
nbr_topo_alpha_0=0.5,
nbr_topo_alpha_f=1.0,
random_state=SEED,
compute_dr_metrics=False,
proto_topo='STK_CADJ',
)
som_delaunay.from_data(
X,
M=M,
coord_dim=2,
coord_init='pca',
W_init='kmeans',
coord_topo='delaunay',
labels=y,
)
g = som_delaunay.plot(
color_by='labels',
title='GTSOM — Blobs (Delaunay topology)',
subtitle='Initial state (age=0), for comparison with the Gabriel graph above',
)
g.draw()
Running FAISS k-means with 100 clusters (niter=20, nredo=1)... K-means complete. Final MQE: 0.276727 Fitting complete using kmeans method.
11. Summary¶
In this tutorial we trained a 100-prototype GTSOM on 5,000 synthetic data points in 10 dimensions, organized into 5 well-separated clusters, using a data-driven output topology built from a PCA projection of the prototypes and a Gabriel graph over those projected positions — GTSOM's namesake "general topology" capability, as opposed to the fixed hexagonal grid used in the MNIST tutorial.
Key parameters and their roles:
| Parameter | Value | Role |
|---|---|---|
M |
100 | Number of prototypes; ~50 points/prototype on average |
coord_init |
'pca' |
Projects prototype vectors to 2-D for output-space positions |
W_init |
'kmeans' |
Prototypes seeded via k-means on the standardized data |
coord_topo |
'gabriel' |
Output topology = Gabriel graph of the projected prototype positions |
rho_0, rho_f, halflife_epochs |
10.0, 0.5, 100 | Neighborhood bandwidth schedule (see MNIST tutorial) |
n_epochs |
200 | Total training epochs |
The Gabriel graph and Delaunay triangulation are both proximity graphs derived from a set of points; the Gabriel graph is always a subgraph of the Delaunay triangulation, retaining a sparser set of "more locally meaningful" connections while remaining guaranteed to stay connected. gtsom supports both via the coord_topo parameter of GTSOM.from_data.
Next steps¶
- 3-D output embeddings:
coord_dim=3produces a 3-D output topology instead of 2-D, useful when the data's intrinsic structure doesn't compress well into a plane. - Laplacian Eigenmaps:
coord_init='le'uses a nonlinear embedding instead of PCA, which can better capture curved or non-linear cluster manifolds at the cost of more computation. - Real-world data: the MNIST tutorial (
GTSOM.from_grid) and this tutorial (GTSOM.from_data) together cover both of GTSOM's topology construction paths — try combining a data-driven topology with a real, messier dataset to see how the Gabriel/Delaunay graph adapts to less artificially clean cluster structure.