GTSOM Tutorial: Mapping MNIST Handwritten Digits¶
What is a Self-Organizing Map?¶
A Self-Organizing Map (SOM) is an unsupervised learning algorithm that projects high-dimensional data onto a low-dimensional output lattice — typically a 2D grid — while preserving the topological structure of the data. Neurons that are nearby in the output lattice learn to respond to similar inputs, so the map can be read as a kind of 'neighborhood diagram' of the data: regions of the lattice that are close together represent data that are similar in the original high-dimensional space.
Unlike dimensionality reduction methods such as PCA or UMAP, the SOM output is a fixed, structured lattice whose geometry is chosen by the user. This makes the result straightforward to visualize and interpret, and allows the user to impose domain-specific structure on the output space.
GTSOM (General Topology SOM) extends the classical SOM by allowing arbitrary output space geometries, defined by any graph structure — hexagonal grids, rectangular grids, or data-driven Delaunay triangulations built from the data itself. This tutorial demonstrates the hexagonal grid constructor (GTSOM.from_grid) on the MNIST handwritten digits dataset.
What we will do¶
- Load and preprocess MNIST (10,000 images, scaled to [0,1], reduced to 50 principal components)
- Initialize a 20×20 hexagonal GTSOM
- Train for 200 epochs with an exponentially decaying neighborhood bandwidth
- Visualize the learned map: digit organization, quantization error, and prototype images
1. Imports¶
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.patches import Patch
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
from gtsom import GTSOM
%matplotlib inline
plt.rcParams['figure.dpi'] = 120
2. Loading MNIST¶
MNIST contains 70,000 28×28 grayscale images of handwritten digits (0–9), each flattened to a 784-dimensional vector. We use the last 10,000 samples, which form the standard test split and are approximately balanced across all 10 digit classes.
Pixel values are scaled globally to [0, 1] before any further processing. GTSOM does not perform any internal scaling — preprocessing is the user's responsibility, and consistent scaling ensures that all input dimensions contribute equally to the nearest-neighbor search.
# Fetch MNIST from OpenML (downloads ~11 MB on first run, cached thereafter)
mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto')
X_raw = mnist.data.astype(np.float32) # (70000, 784)
y_raw = mnist.target.astype(int) # (70000,)
# Use the last 10,000 samples — the standard balanced test split
N = 10_000
X_raw = X_raw[-N:]
y = y_raw[-N:]
print(f'Dataset: {X_raw.shape}')
print(f'Label counts: { {d: int((y==d).sum()) for d in range(10)} }')
# Scale globally to [0, 1]
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X_raw).astype(np.float32)
print(f'Scaled range: [{X_scaled.min():.3f}, {X_scaled.max():.3f}]')
Dataset: (10000, 784)
Label counts: {0: 980, 1: 1135, 2: 1032, 3: 1010, 4: 982, 5: 892, 6: 958, 7: 1028, 8: 974, 9: 1009}
Scaled range: [0.000, 1.000]
3. Dimensionality Reduction via PCA¶
With d=784 input dimensions, computing nearest-neighbor distances for each data point at every training epoch would be expensive and dominated by uninformative dimensions (the blank border pixels common to all images). We reduce to 50 principal components, which captures approximately 85% of the total variance while dramatically reducing computation time.
This PCA is a preprocessing step applied to the raw pixel data. The SOM then operates in this 50-dimensional PCA score space.
N_PCS = 50
pca = PCA(n_components=N_PCS, svd_solver='randomized', random_state=42)
X = pca.fit_transform(X_scaled).astype(np.float32)
print(f'Reduced: {X_scaled.shape} -> {X.shape}')
print(f'Variance explained by {N_PCS} PCs: {pca.explained_variance_ratio_.sum()*100:.1f}%')
Reduced: (10000, 784) -> (10000, 50) Variance explained by 50 PCs: 83.1%
# Scree plot: cumulative variance explained
fig, ax = plt.subplots(figsize=(7, 3))
cumvar = np.cumsum(pca.explained_variance_ratio_) * 100
ax.plot(range(1, N_PCS + 1), cumvar, 'o-', ms=3, lw=1.5, color='steelblue')
ax.axhline(85, color='dimgrey', lw=0.8, linestyle='--', label='85% variance')
ax.axhline(95, color='coral', lw=0.8, linestyle='--', label='95% variance')
ax.set_xlabel('Number of principal components')
ax.set_ylabel('Cumulative variance explained (%)')
ax.set_title('MNIST PCA — Cumulative Variance Explained')
ax.legend(fontsize=8)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
4. Choosing the Output Lattice¶
Lattice size¶
A common rule of thumb for SOM size is M ≈ 5√N neurons, where N is the number of training samples. For N=10,000 this gives M ≈ 500, suggesting a grid of roughly 22×22. We use a 20×20 grid (M=400), which is slightly more conservative but trains faster and remains visually interpretable. With 400 neurons and 10,000 data points, each neuron will serve on average 25 data points in its receptive field.
Too few neurons: multiple digit classes are forced to share prototypes, blurring the map. Too many neurons: training is slow and many neurons end up with empty receptive fields.
Hexagonal vs rectangular grid¶
We use a hexagonal grid (coord_init='hex') rather than rectangular. In a hex grid every interior neuron has exactly 6 equidistant neighbors, giving a more uniform neighborhood structure than a rectangular grid where diagonal neighbors are further away than axis-aligned ones. This tends to produce smoother, more isotropic maps.
Weight initialization¶
W_init='random' initializes each prototype by sampling a random data point from X. This gives a starting configuration that is well-distributed within the data cloud. The SOM training then moves prototypes from these initial positions into the regions of the data space they will ultimately represent.
5. Initialising the GTSOM¶
SEED = 42
som = GTSOM(
rho_0=10.0,
rho_f=1.0,
halflife_epochs=100,
n_jobs=-1,
nbr_topo_alpha_0=1.0,
nbr_topo_alpha_f=1.0,
random_state=SEED,
compute_dr_metrics=True,
)
som.from_grid(
X,
shape=(20, 20),
coord_init='hex',
W_init='random',
labels=y,
)
print(som)
print(f'Prototypes with empty receptive fields at init: '
f'{(som.recaller.RFSize == 0).sum()} / {som.M}')
GTSOM(M=400, d=50, embed_dim=2, fitted=False, age=0, snapshots=1, backend='numba', n_jobs=16, nbr_influence_min=0.01, proto_topo='CONN_GD', alpha_schedule=ExponentialAnneal(initial=1.0, final=1.0, tau=200, flat=True), compute_dr_metrics=True, train_time=0.000s) Prototypes with empty receptive fields at init: 0 / 400
At initialization, prototypes are placed randomly within the data cloud and the output lattice has no meaningful organization — digit labels are distributed randomly across the hex grid, as the plot below shows.
g = som.plot(
color_by='labels',
title='GTSOM — MNIST (20×20 hex)',
subtitle='Initial state (age=0)',
)
g.draw()
6. The Learning Schedule¶
Before training, we configure the neighborhood bandwidth schedule — the parameter ρ (rho) that controls how widely each prototype update propagates across the lattice.
How the SOM update rule works¶
At each training epoch, every data point is assigned to its nearest prototype (the Best Matching Unit, or BMU). The BMU and its neighbors are then pulled toward the data points assigned to the BMU. The neighborhood influence of prototype j on prototype b's update is determined by a kernel weight h(dist(b,j), ρ) that falls off with geodesic distance on the lattice. A large ρ means a wide neighborhood: many prototypes move together, producing coarse global organization. A small ρ means only immediate neighbors are affected, producing fine local refinement.
Parameter choices¶
rho_0 = 10.0 — initial bandwidth. The 20×20 hex lattice has a diameter of approximately 20 geodesic hops. Starting with ρ=10 means each prototype's neighborhood initially spans roughly half the lattice, ensuring the first training epochs establish global organization rather than local rearrangement.
rho_f = 1.0 — final bandwidth. At ρ=1, only immediately adjacent neurons (6 neighbors in a hex grid) influence each other's updates. This is the standard SOM minimum: the map continues to refine locally but the global topology is fixed.
halflife_epochs = 100. The bandwidth decays exponentially from ρ₀ to ρ_f; halflife_epochs sets the half-life of this decay (the geometric midpoint between ρ₀ and ρ_f is reached at halflife_epochs, and ρ_f is reached at 2 × halflife_epochs). With 200 total epochs and halflife_epochs=100, the bandwidth is actively decaying throughout the first half of training and at its floor for the second half — a natural two-phase structure: global organization followed by local refinement.
n_jobs=-1 enables parallel prototype updates using all available CPU cores via a numba JIT-compiled kernel, significantly accelerating training on large datasets.
# Visualize the bandwidth decay schedule
rho_vals = som.rho_schedule.values(200)
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(range(200), rho_vals, lw=2, color='steelblue')
ax.axhline(1.0, color='coral', lw=0.8, linestyle='--', label='rho_f = 1.0')
ax.axvline(100, color='dimgrey', lw=0.8, linestyle='--', label='halflife_epochs = 100')
ax.set_xlabel('Epoch')
ax.set_ylabel('Neighborhood bandwidth ρ')
ax.set_title('Exponential bandwidth decay schedule')
ax.legend(fontsize=8)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
7. Training¶
We train for 200 epochs. A snapshot of the SOM state is captured every 25 epochs and stored in learn_history_ for retrospective inspection. The verbose output below shows the epoch number, current bandwidth ρ, global mean quantization error (MQE), and the proportion of data points whose nearest prototype changed since the previous epoch (delBMU).
som.fit(
X,
n_epochs=200,
labels=y,
verbose=True,
plot_every=25,
)
print(f'\nFinal state: {som}')
print(f'Empty RFs after training: {(som.recaller.RFSize == 0).sum()} / {som.M}')
Epoch rho alpha MQE delBMU
----- ------ ------ -------- -------
1 10.0000 1.0000 6.5607 0.9437
2 9.8855 1.0000 6.2517 0.5883
3 9.7724 1.0000 6.1914 0.4608
4 9.6605 1.0000 6.1689 0.3789
5 9.5499 1.0000 6.1551 0.3245
6 9.4406 1.0000 6.1417 0.2573
7 9.3325 1.0000 6.1283 0.2614
8 9.2257 1.0000 6.1085 0.3453
9 9.1201 1.0000 6.0842 0.3624
10 9.0157 1.0000 6.0677 0.3029
----- ------ ------ -------- -------
11 8.9125 1.0000 6.0567 0.2463
12 8.8105 1.0000 6.0469 0.2373
13 8.7096 1.0000 6.0378 0.2168
14 8.6099 1.0000 6.0300 0.1981
15 8.5114 1.0000 6.0229 0.1784
16 8.4140 1.0000 6.0162 0.1758
17 8.3176 1.0000 6.0095 0.1618
18 8.2224 1.0000 6.0027 0.1514
19 8.1283 1.0000 5.9961 0.1370
20 8.0353 1.0000 5.9898 0.1299
----- ------ ------ -------- -------
21 7.9433 1.0000 5.9834 0.1219
22 7.8524 1.0000 5.9770 0.1080
23 7.7625 1.0000 5.9708 0.1006
24 7.6736 1.0000 5.9647 0.0933
25 7.5858 1.0000 5.9586 0.0903
26 7.4989 1.0000 5.9525 0.0833
27 7.4131 1.0000 5.9466 0.0693
28 7.3282 1.0000 5.9407 0.0677
29 7.2444 1.0000 5.9349 0.0706
30 7.1614 1.0000 5.9290 0.0660
----- ------ ------ -------- -------
31 7.0795 1.0000 5.9231 0.0677
32 6.9984 1.0000 5.9170 0.0647
33 6.9183 1.0000 5.9108 0.0659
34 6.8391 1.0000 5.9046 0.0554
35 6.7608 1.0000 5.8985 0.0575
36 6.6834 1.0000 5.8923 0.0511
37 6.6069 1.0000 5.8862 0.0463
38 6.5313 1.0000 5.8801 0.0458
39 6.4565 1.0000 5.8740 0.0459
40 6.3826 1.0000 5.8679 0.0427
----- ------ ------ -------- -------
41 6.3096 1.0000 5.8618 0.0433
42 6.2373 1.0000 5.8556 0.0424
43 6.1660 1.0000 5.8495 0.0420
44 6.0954 1.0000 5.8432 0.0436
45 6.0256 1.0000 5.8365 0.0464
46 5.9566 1.0000 5.8302 0.0450
47 5.8884 1.0000 5.8239 0.0406
48 5.8210 1.0000 5.8173 0.0465
49 5.7544 1.0000 5.8109 0.0407
50 5.6885 1.0000 5.8045 0.0381
----- ------ ------ -------- -------
51 5.6234 1.0000 5.7979 0.0445
52 5.5590 1.0000 5.7915 0.0363
53 5.4954 1.0000 5.7851 0.0370
54 5.4325 1.0000 5.7787 0.0395
55 5.3703 1.0000 5.7718 0.0431
56 5.3088 1.0000 5.7652 0.0392
57 5.2481 1.0000 5.7587 0.0408
58 5.1880 1.0000 5.7514 0.0512
59 5.1286 1.0000 5.7446 0.0501
60 5.0699 1.0000 5.7375 0.0480
----- ------ ------ -------- -------
61 5.0119 1.0000 5.7303 0.0513
62 4.9545 1.0000 5.7222 0.0590
63 4.8978 1.0000 5.7149 0.0523
64 4.8417 1.0000 5.7076 0.0516
65 4.7863 1.0000 5.7000 0.0536
66 4.7315 1.0000 5.6913 0.0675
67 4.6774 1.0000 5.6828 0.0603
68 4.6238 1.0000 5.6743 0.0594
69 4.5709 1.0000 5.6662 0.0524
70 4.5186 1.0000 5.6564 0.0543
----- ------ ------ -------- -------
71 4.4668 1.0000 5.6488 0.0420
72 4.4157 1.0000 5.6413 0.0373
73 4.3652 1.0000 5.6338 0.0367
74 4.3152 1.0000 5.6246 0.0417
75 4.2658 1.0000 5.6172 0.0325
76 4.2170 1.0000 5.6098 0.0273
77 4.1687 1.0000 5.6024 0.0301
78 4.1210 1.0000 5.5903 0.0474
79 4.0738 1.0000 5.5831 0.0299
80 4.0272 1.0000 5.5760 0.0275
----- ------ ------ -------- -------
81 3.9811 1.0000 5.5687 0.0294
82 3.9355 1.0000 5.5613 0.0282
83 3.8905 1.0000 5.5503 0.0536
84 3.8459 1.0000 5.5427 0.0332
85 3.8019 1.0000 5.5353 0.0303
86 3.7584 1.0000 5.5278 0.0337
87 3.7154 1.0000 5.5202 0.0333
88 3.6728 1.0000 5.5088 0.0596
89 3.6308 1.0000 5.5005 0.0423
90 3.5892 1.0000 5.4923 0.0389
----- ------ ------ -------- -------
91 3.5481 1.0000 5.4842 0.0372
92 3.5075 1.0000 5.4761 0.0372
93 3.4674 1.0000 5.4647 0.0581
94 3.4277 1.0000 5.4565 0.0345
95 3.3884 1.0000 5.4487 0.0306
96 3.3497 1.0000 5.4408 0.0286
97 3.3113 1.0000 5.4329 0.0304
98 3.2734 1.0000 5.4248 0.0343
99 3.2359 1.0000 5.4131 0.0554
100 3.1989 1.0000 5.4048 0.0371
----- ------ ------ -------- -------
101 3.1623 1.0000 5.3967 0.0304
102 3.1261 1.0000 5.3886 0.0280
103 3.0903 1.0000 5.3805 0.0272
104 3.0549 1.0000 5.3724 0.0264
105 3.0200 1.0000 5.3601 0.0557
106 2.9854 1.0000 5.3514 0.0364
107 2.9512 1.0000 5.3431 0.0292
108 2.9174 1.0000 5.3347 0.0293
109 2.8840 1.0000 5.3263 0.0310
110 2.8510 1.0000 5.3180 0.0283
----- ------ ------ -------- -------
111 2.8184 1.0000 5.3044 0.0533
112 2.7861 1.0000 5.2960 0.0317
113 2.7542 1.0000 5.2879 0.0283
114 2.7227 1.0000 5.2796 0.0279
115 2.6915 1.0000 5.2714 0.0240
116 2.6607 1.0000 5.2633 0.0232
117 2.6303 1.0000 5.2551 0.0224
118 2.6002 1.0000 5.2405 0.0524
119 2.5704 1.0000 5.2318 0.0318
120 2.5410 1.0000 5.2233 0.0280
----- ------ ------ -------- -------
121 2.5119 1.0000 5.2149 0.0265
122 2.4831 1.0000 5.2066 0.0227
123 2.4547 1.0000 5.1983 0.0205
124 2.4266 1.0000 5.1900 0.0230
125 2.3988 1.0000 5.1815 0.0264
126 2.3714 1.0000 5.1658 0.0501
127 2.3442 1.0000 5.1570 0.0345
128 2.3174 1.0000 5.1485 0.0285
129 2.2909 1.0000 5.1399 0.0284
130 2.2646 1.0000 5.1315 0.0254
----- ------ ------ -------- -------
131 2.2387 1.0000 5.1232 0.0220
132 2.2131 1.0000 5.1148 0.0197
133 2.1878 1.0000 5.1065 0.0184
134 2.1627 1.0000 5.0892 0.0431
135 2.1380 1.0000 5.0805 0.0304
136 2.1135 1.0000 5.0721 0.0277
137 2.0893 1.0000 5.0637 0.0265
138 2.0654 1.0000 5.0551 0.0276
139 2.0417 1.0000 5.0465 0.0291
140 2.0184 1.0000 5.0378 0.0271
----- ------ ------ -------- -------
141 1.9953 1.0000 5.0293 0.0272
142 1.9724 1.0000 5.0208 0.0264
143 1.9498 1.0000 5.0014 0.0475
144 1.9275 1.0000 4.9928 0.0394
145 1.9055 1.0000 4.9841 0.0341
146 1.8836 1.0000 4.9754 0.0320
147 1.8621 1.0000 4.9669 0.0271
148 1.8408 1.0000 4.9585 0.0260
149 1.8197 1.0000 4.9501 0.0232
150 1.7989 1.0000 4.9420 0.0213
----- ------ ------ -------- -------
151 1.7783 1.0000 4.9339 0.0200
152 1.7579 1.0000 4.9257 0.0195
153 1.7378 1.0000 4.9176 0.0219
154 1.7179 1.0000 4.8968 0.0424
155 1.6982 1.0000 4.8883 0.0300
156 1.6788 1.0000 4.8802 0.0249
157 1.6596 1.0000 4.8723 0.0241
158 1.6406 1.0000 4.8640 0.0245
159 1.6218 1.0000 4.8556 0.0227
160 1.6032 1.0000 4.8474 0.0192
----- ------ ------ -------- -------
161 1.5849 1.0000 4.8393 0.0183
162 1.5668 1.0000 4.8314 0.0209
163 1.5488 1.0000 4.8232 0.0206
164 1.5311 1.0000 4.8148 0.0206
165 1.5136 1.0000 4.7915 0.0424
166 1.4962 1.0000 4.7826 0.0303
167 1.4791 1.0000 4.7743 0.0246
168 1.4622 1.0000 4.7664 0.0204
169 1.4454 1.0000 4.7588 0.0191
170 1.4289 1.0000 4.7512 0.0176
----- ------ ------ -------- -------
171 1.4125 1.0000 4.7436 0.0148
172 1.3964 1.0000 4.7361 0.0148
173 1.3804 1.0000 4.7286 0.0155
174 1.3646 1.0000 4.7209 0.0146
175 1.3490 1.0000 4.7134 0.0156
176 1.3335 1.0000 4.7058 0.0149
177 1.3183 1.0000 4.6980 0.0140
178 1.3032 1.0000 4.6902 0.0130
179 1.2882 1.0000 4.6654 0.0358
180 1.2735 1.0000 4.6571 0.0232
----- ------ ------ -------- -------
181 1.2589 1.0000 4.6492 0.0195
182 1.2445 1.0000 4.6415 0.0159
183 1.2303 1.0000 4.6339 0.0145
184 1.2162 1.0000 4.6265 0.0124
185 1.2023 1.0000 4.6193 0.0133
186 1.1885 1.0000 4.6118 0.0128
187 1.1749 1.0000 4.6044 0.0130
188 1.1614 1.0000 4.5969 0.0124
189 1.1482 1.0000 4.5895 0.0109
190 1.1350 1.0000 4.5820 0.0120
----- ------ ------ -------- -------
191 1.1220 1.0000 4.5745 0.0119
192 1.1092 1.0000 4.5669 0.0109
193 1.0965 1.0000 4.5596 0.0104
194 1.0839 1.0000 4.5308 0.0352
195 1.0715 1.0000 4.5224 0.0196
196 1.0593 1.0000 4.5150 0.0165
197 1.0471 1.0000 4.5078 0.0139
198 1.0351 1.0000 4.5006 0.0125
199 1.0233 1.0000 4.4936 0.0117
200 1.0116 1.0000 4.4865 0.0118
----- ------ ------ -------- -------
----- ------ ------ -------- -------
Final state: GTSOM(M=400, d=50, embed_dim=2, fitted=True, age=200, snapshots=201, backend='numba', n_jobs=16, nbr_influence_min=0.01, proto_topo='CONN_GD', alpha_schedule=ExponentialAnneal(initial=1.0, final=1.0, tau=200, flat=True), compute_dr_metrics=True, train_time=143.837s)
Empty RFs after training: 0 / 400
8. Learning Curves¶
Two quantities are monitored at every epoch:
Mean Quantization Error (MQE) is the root-mean-square Euclidean distance from each data point to its nearest prototype (i.e. the square root of the mean squared distance, not the mean distance itself — the standard RMSE-based definition of MQE in the SOM literature). It measures how well the prototypes represent the data — lower is better. MQE generally decreases monotonically as training progresses.
delBMU is the proportion of data points whose nearest prototype (BMU) changed from the previous epoch. It measures how much the map is still reorganizing — a value near 0 indicates convergence. The periodic spikes visible in the delBMU curve reflect neighborhood shell collapses: as ρ decays, the kernel weight for prototypes at distance d geodesic hops drops below a minimum threshold, effectively removing that shell from the neighborhood. Each such collapse triggers a brief burst of BMU reassignments before the map re-settles.
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. Lattice Organization Over Time¶
The following four panels show the SOM lattice colored by the plurality digit label at each neuron, captured at ages 0, 50, 100, and 200. At age 0 the labels are randomly distributed. By age 50 a coarse global structure is already visible — similar digits are beginning to cluster spatially. The map continues to sharpen through the remaining epochs as the neighborhood bandwidth narrows and prototypes refine their local territories.
import io
from PIL import Image as PILImage
target_ages = [0, 50, 100, 200]
snap_by_age = {s['age']: s for s in som.learn_history_ if s['fig'] is not None}
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
fig.suptitle('GTSOM — MNIST lattice organization over training',
fontsize=13, fontweight='bold', y=1.01)
for ax, age in zip(axes.flat, target_ages):
snap_fig = snap_by_age[age]['fig'] # plotnine ggplot object
# Save ggplot to an in-memory PNG, then display with imshow
buf = io.BytesIO()
snap_fig.save(buf, format='png', dpi=100, width=6, height=5)
buf.seek(0)
img = PILImage.open(buf)
ax.imshow(img)
ax.axis('off')
ax.set_title(f'Age = {age}', fontsize=12, pad=6)
plt.tight_layout()
plt.show()
/usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 6 x 5 in image. /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: <_io.BytesIO object at 0x13fd887c0> /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 6 x 5 in image. /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: <_io.BytesIO object at 0x13fdd67c0> /usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10 /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 6 x 5 in image. /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: <_io.BytesIO object at 0x13fdbeef0> /usr/local/lib/python3.9/site-packages/pandas/core/arraylike.py:396: RuntimeWarning: divide by zero encountered in log10 /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 6 x 5 in image. /usr/local/lib/python3.9/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: <_io.BytesIO object at 0x13fbceb80>
10. Final Learned Map¶
Digit organization¶
The map below shows the final trained SOM colored by the plurality digit label at each neuron. The SOM has learned a spatially coherent organization of the digit classes — similar-looking digits occupy neighboring regions of the lattice.
The topology reflects the visual similarity structure of the digits: curved digits (0, 6, 8, 9) tend to cluster together, as do straight-stroked digits (1, 4, 7). Digits with high intra-class variability (notably 5, which can resemble 3, 6, or 8 depending on the writer) may appear scattered or occupy boundary regions between other digit clusters.
g = som.plot(
color_by='labels',
title='GTSOM — MNIST (20×20 hex)',
subtitle=f'age={som.age}, color_by=\'labels\'',
)
g.draw()
Quantization error and receptive field size¶
Two further diagnostic views of the trained map:
Mean Quantization Error per neuron (color_by='mqe') shows where the map fits the data well (low MQE, dark) and where prototypes are further from their assigned data points (high MQE, bright). High-MQE regions often correspond to class boundaries where a single prototype must represent data from multiple nearby clusters.
Receptive field size (color_by='rfsize') shows how many data points are assigned to each neuron. A uniform distribution across neurons is ideal; neurons with very large receptive fields are 'overloaded' and may benefit from a larger lattice.
for color_by in ['mqe', 'rfsize']:
g = som.plot(
color_by=color_by,
title='GTSOM — MNIST',
subtitle=f'color_by=\'{color_by}\'',
)
g.draw()
11. Prototype Images¶
Each neuron's weight vector W[j] is a point in 50-dimensional PCA score space. By applying the inverse PCA transform, we can reconstruct the 28×28 pixel image that each neuron has learned to represent — the 'template' for its region of the digit space. Arranging these prototype images on the hex lattice produces a visual summary of the entire learned map.
Prototypes in the interior of a digit cluster should resemble that digit clearly; prototypes at boundaries between clusters will show blended or ambiguous forms — a natural consequence of the SOM's smooth topographic mapping.
# Back-project W from PCA score space to pixel space
W_pixels = pca.inverse_transform(som.W) # (M, 784)
W_pixels = scaler.inverse_transform(W_pixels) # undo [0,1] scaling
W_pixels = np.clip(W_pixels, 0, 255).astype(np.uint8)
coords = som.embed.coords # (M, 2) hex lattice positions
tile = 28
x_min, x_max = coords[:, 0].min(), coords[:, 0].max()
y_min, y_max = coords[:, 1].min(), coords[:, 1].max()
x_range = x_max - x_min
y_range = y_max - y_min
canvas_w = int(20 * tile * 1.15)
canvas_h = int(20 * tile * 1.25)
canvas = np.ones((canvas_h, canvas_w), dtype=np.uint8) * 255
for m in range(som.M):
px = int((coords[m, 0] - x_min) / x_range * (canvas_w - tile))
py = int((coords[m, 1] - y_min) / y_range * (canvas_h - tile))
py = canvas_h - tile - py # flip y
py = max(0, min(py, canvas_h - tile))
px = max(0, min(px, canvas_w - tile))
canvas[py:py+tile, px:px+tile] = W_pixels[m].reshape(28, 28)
fig, ax = plt.subplots(figsize=(12, 10))
ax.imshow(canvas, cmap='gray_r', vmin=0, vmax=255)
ax.axis('off')
ax.set_title(
'GTSOM — MNIST Prototype Images\n'
'(each neuron\'s weight vector back-projected to pixel space)',
fontsize=11,
)
plt.tight_layout()
plt.show()
12. Summary¶
In this tutorial we trained a 20×20 hexagonal GTSOM on 10,000 MNIST digit images reduced to 50 principal components. The trained map shows clear topographic organization: digit classes occupy contiguous regions of the lattice, and the spatial relationships between regions reflect the visual similarity of the digits.
Key parameters and their roles:
| Parameter | Value | Role |
|---|---|---|
| Grid shape | 20×20 hex | M=400 neurons; balanced coverage for N=10,000 |
W_init |
'random' |
Prototypes initialized from random data points |
rho_0 |
10.0 | Initial bandwidth ≈ half the lattice diameter |
rho_f |
1.0 | Final bandwidth = single-neighbor influence |
halflife_epochs |
100 | Bandwidth half-life; ρ_f reached at epoch 200 |
n_epochs |
200 | Total training epochs |
Next steps¶
- Data-driven topology:
GTSOM.from_databuilds the output lattice via Delaunay triangulation of prototype positions in PCA or Laplacian Eigenmap space, allowing the topology to adapt to the data rather than being fixed in advance. See the companion notebook, GTSOM Tutorial: General Topology Learning on Synthetic Blobs, for a worked example. - Larger grids: For exploratory analysis of large datasets, a 30×30 or 40×40 grid provides finer spatial resolution at the cost of longer training time.
- Parallelism:
n_jobs, set in theGTSOMconstructor, controls the number of CPU threads used for prototype updates. On multi-core machines,n_jobs=-1(all cores) can reduce training time substantially for large N and d.