Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How does a self-organizing map (SOM) work in C++?

C++
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedJul 28, 2023
UpdatedNov 17, 2026
12 min read

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.

Table of Contents

  • How a self-organizing map works
  • Choosing the grid, decay and distance
  • A complete SOM in modern C++
    • What the code does
  • Reading and using the trained map
  • Frequently Asked Questions
    • Is a SOM supervised or unsupervised?
    • How is a SOM different from k-means?
    • Why must the learning rate and radius decrease?
    • Should I use SOMs instead of t-SNE or UMAP?
  • Summary

How a self-organizing map works

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:

  1. Find the best matching unit (BMU), the node whose weight vector has the smallest distance to the sample.
  2. Compute, for every node, how close it is to the BMU on the grid (not in data space).
  3. Move each node's weights towards the sample, scaled by the learning rate and a neighbourhood weight.
  4. Shrink the learning rate and the neighbourhood radius as training progresses.

The update rule for node i is:

text

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.

Choosing the grid, decay and distance

SettingTypical choiceEffect
Grid sizeRoughly 5 * sqrt(N) nodes for N samples is a common rule of thumbLarger grids show finer detail but train slower
Initial learning rate0.1 to 0.5Higher values organise the map faster but can be unstable
Initial radiusAbout half the larger grid sideWide at first so the whole map orders itself
DecayExponential or linear over total iterationsA radius that shrinks to about one node lets the map fine tune
DistanceEuclidean on normalised featuresUnscaled 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.

A complete SOM in modern C++

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.

cpp

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.

What the code does

  • 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.
  • The weights live in a single std::vector<double>, which is more cache friendly than a nested vector<vector<vector<double>>>.

Reading and using the trained map

After training, use the map in three common ways:

  • Clustering: map each sample to its BMU. Samples sharing a node or adjacent nodes belong to the same cluster.
  • Visualisation: compute the U-matrix, the average distance between each node's weights and its neighbours. High values mark cluster borders.
  • Quality check: the quantisation error (average distance from each sample to its BMU) and the topographic error (share of samples whose two closest nodes are not adjacent) show how well the map fits.

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.

Frequently Asked Questions

Is a SOM supervised or unsupervised?

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.

How is a SOM different from k-means?

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.

Why must the learning rate and radius decrease?

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.

Should I use SOMs instead of t-SNE or UMAP?

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.

Summary

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.

Share