A self-organizing map (SOM), also called a Kohonen map, is an unsupervised neural network that projects high-dimensional data onto a low-dimensional grid, usually two-dimensional, while keeping similar inputs close together. Each grid cell holds a weight vector; training pulls the best matching cell and its neighbours towards every input. In C++ you implement it with a flat array of weight vectors, a best matching unit search, and a neighbourhood function whose learning rate and radius shrink over time.
SOMs are used for clustering, visualising datasets such as customer segments, and exploratory analysis before heavier models. They were introduced by Teuvo Kohonen in the 1980s and remain a compact way to see structure in data without labels.
A SOM has a grid of nodes (neurons). Every node stores a weight vector with the same dimension as the input. Unlike a classic feed-forward network there are no hidden layers or gradients: training is competitive learning.
For each training sample, the algorithm repeats these steps:
The update rule for node i is:
Here alpha(t) is the learning rate, sigma(t) the neighbourhood radius, and d_i the grid distance between node i and the BMU. Because neighbours move together, nearby nodes end up representing similar inputs. That is what preserves the topology.
| Setting | Typical choice | Effect |
|---|---|---|
| Grid size | Roughly 5 * sqrt(N) nodes for N samples is a common rule of thumb | Larger grids show finer detail but train slower |
| Initial learning rate | 0.1 to 0.5 | Higher values organise the map faster but can be unstable |
| Initial radius | About half the larger grid side | Wide at first so the whole map orders itself |
| Decay | Exponential or linear over total iterations | A radius that shrinks to about one node lets the map fine tune |
| Distance | Euclidean on normalised features | Unscaled features dominate the BMU search |
Always normalise features (for example to the range 0 to 1) before training, otherwise one large-valued feature decides every BMU.
The original version of this answer had several bugs: DBL_MAX was used without <cfloat>, the neighbourhood function divided the distance instead of its square, and the learning rate and radius never decayed. The version below fixes those, uses <random> instead of rand(), and stores weights in one contiguous vector. It needs C++17 or newer.
Compile and run it with g++ -std=c++20 -O2 som.cpp -o som && ./som. The weights are random-seeded but deterministic, so you get the same map on every run; the exact numbers depend on your standard library's shuffle implementation, but the printed grid should show weights spread smoothly across the unit square.
bmu scans every node and returns the one with the smallest squared distance. Comparing squared distances avoids a sqrt per node and gives the same winner.train computes alpha and sigma from the global step counter, so both decay smoothly across all epochs, and shuffles the sample order each epoch to avoid order bias.update applies the Gaussian neighbourhood to every node. For large grids you can skip nodes where h is negligible, for example when the grid distance exceeds 3 * sigma.std::vector<double>, which is more cache friendly than a nested vector<vector<vector<double>>>.After training, use the map in three common ways:
For production workloads on large data, consider batch SOM training, a hexagonal grid, or an existing library, since the plain online algorithm is O(samples x nodes x dimension) per epoch.
Unsupervised. It learns structure from unlabeled inputs. You can label nodes afterwards using a few labeled samples if you want to use the map as a classifier.
K-means assigns points to independent centroids. A SOM also arranges its prototypes on a grid and updates neighbours together, so the result keeps topological order and can be visualised in two dimensions.
Large values early let the map unfold and order itself globally. Small values late let each node settle on a local region. Without decay the weights keep jumping and never converge.
They solve similar visualisation problems. SOMs give a fixed grid of prototypes that you can reuse to place new points; t-SNE and UMAP typically give better-looking embeddings but have no fixed codebook.
A self-organizing map learns a grid of weight vectors by finding the best matching unit for each input and pulling it and its grid neighbours towards that input. A correct implementation needs a Gaussian neighbourhood on squared grid distance, a decaying learning rate and radius, normalised inputs and randomised sample order. The C++ example above is a compact, runnable baseline you can extend with a U-matrix or batch training.