Skip to main content

KSOM - Simple, but relatively efficient, pytorch-based self organising map

This is a simple implementation of self-organising map training in python, using pytorch for efficiency. This enables to create, train and apply maps of potentially high dimensions on CPU or GPU.

Three model classes are provided:

  • SOM: standard self-organising map
  • WSOM: weighted SOM with learnable per-feature weights, optimised through a combination of distance-based and entropy-based sparsity loss
  • MCWSOM: multi-channel weighted SOM, creating multiple WSOM channels with a diversity loss that pushes each channel toward different feature weightings

To install, use

pip install ksom

Maps are created with a number of rows and columns (SOM(xs, ys, dim)), which don't have to be equal. All the classes, distance functions and neighbourhood functions can be imported directly from ksom.

SOM Example

An example is available in tests/test_img.py for a simple use case creating a square color map of an image. Having loaded the data in a tensor x, the code to initialise and train the SOM looks like this:

from ksom import SOM, cosine_distance, nb_gaussian
...
smodel = SOM(6, 6, 3, # size of the map and dimension of units
             sample_init=samples, # initialised with samples
             dist=cosine_distance, # using cosine distance for BMU
             alpha_init=0.01, # learning rate
             alpha_drate=1e-7, # decay of learning rate
             neighborhood_fct=nb_gaussian, # neighbourhood function
             neighborhood_init=som_size, # initial neighbourhood radius
             neighborhood_drate=0.0001) # decay of neighbourhood radius

perm = torch.randperm(x.size(0)) # to shuffle the data
for i in range(int(x.size()[0]/1000)):
    idx = perm[i*1000:(i+1)*1000]
    time1 = time.time()
    dist,count = smodel.add(x[idx]) # feed the SOM a batch of 1000 pixels
    print(f"{(i+1):06d}K - {dist:.4f} - {(time.time()-time1)*1000:05.2f}ms")

The learning rate and the neighbourhood radius decay for every data point, so their decay rates should be set from the total number of points the map will see: about alpha_init / total for alpha_drate and (neighborhood_init - final_radius) / total for neighborhood_drate. If the rates are too small for the amount of data, the radius barely shrinks and much of the map goes unused.

The results on the image on the left looks like the map on the right, where each unit is represented by the colour corresponding to its weights.

map from image

Another example is included in the tests/test_cheese.py creating a map of cheeses based on various binary attributes. The results is presented below with on the right the map represented by colours for each unit created through PCA with 3 components for the RGB components of the colour. On the left, a frequency map is given that show how many cheese have each unit for BMU (brighter == more cheese) as well as the name of the attribute most different in this unit compared to the average of the whole dataset.

map of chesses

WSOM Example

The WSOM (Weighted SOM) learns per-feature importance weights alongside the map. It requires a PyTorch optimizer. See tests/test_w_cars.py for a full example.

from ksom.ksom import WSOM, cosine_distance
...
smodel = WSOM(5, 5, dim,
              sample_init=samples,
              dist=cosine_distance,
              alpha_init=1e-2, alpha_drate=5e-8,
              sparcity_coeff=1e-2)

optimizer = torch.optim.Adam(smodel.parameters(), lr=1e-2)
smodel.train()
for epoch in range(n_epochs):
    dist, count, loss = smodel.add(batch, optimizer)

The sparsity term is the entropy of the normalised feature weights, and smodel.effective_features() gives roughly how many features carry the weight. Very small values of sparcity_coeff have little effect, and the value needed for a strong one depends on the data, typically between 0.1 and 1.0. On data with one-hot encoded columns, the learned weights tend to concentrate on those columns, and most of the map can then go unused, especially with a strong sparsity term. Check how many units are used as best matches when working with such data.

MCWSOM Example

The MCWSOM (Multi-Channel Weighted SOM) creates multiple WSOM channels, each learning different feature weightings. A diversity loss (cosine similarity between channel weights) encourages complementary views. See tests/test_mcw_cars.py for a full example.

from ksom.ksom import MCWSOM, cosine_distance
...
smodel = MCWSOM(5, 5, dim,
                sample_init=samples,
                dist=cosine_distance,
                alpha_init=1e-2, alpha_drate=5e-8,
                sparcity_coeff=1e-2,
                n_channels=4,
                channel_sim_loss_coef=0.5)

optimizer = torch.optim.Adam(smodel.parameters(), lr=1e-2)
smodel.train()
for epoch in range(n_epochs):
    dist, count, total_loss, diversity_loss = smodel.add(batch, optimizer)

channel_sim_loss_coef controls how different the channels become: with small values such as 1e-2, they stay fairly similar. smodel.channel_wsoms gives access to the individual WSOMs, for example to read their weights or effective_features().

Metadata

Release files for ksom 0.11.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ksom 0.11.0
File Size Uploaded Provenance Actions
ksom-0.11.0.tar.gz 9.2 kB Without provenance Details for ksom-0.11.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ksom 0.11.0
File Interpreter ABI Platform Actions
ksom-0.11.0-py3-none-any.whl Python 3 none any Details for ksom-0.11.0-py3-none-any.whl

Total release size: 19.3 kB

Release files / ksom-0.11.0.tar.gz

Download URL ksom-0.11.0.tar.gz
Size 9.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ce7ce6efb3c3f00a616658ad21e2ed186f2dd419f42580c8b4fc2049e8d05053
BLAKE2b-256 checksum
How to use checksums
b80f50dedfbf9d4706c173969733733b57425857bcc548efe5bacb13177b8d78
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.21 {"installer":{"name":"uv","version":"0.9.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / ksom-0.11.0-py3-none-any.whl

Download URL ksom-0.11.0-py3-none-any.whl
Size 10.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c50abfd7b7518abd782868e5f6948efea9e8b62dce88727f193ba31dfd2f91b5
BLAKE2b-256 checksum
How to use checksums
c4eddf9c213d0d8712998553811db2f5a3dc9b24e6d03dfdd4a86ff813f2a1e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.21 {"installer":{"name":"uv","version":"0.9.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for ksom 0.11.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page