fastersom 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastersom-0.1.0/LICENSE +202 -0
- fastersom-0.1.0/PKG-INFO +98 -0
- fastersom-0.1.0/README.md +70 -0
- fastersom-0.1.0/pyproject.toml +91 -0
- fastersom-0.1.0/pyproject.toml.orig +62 -0
- fastersom-0.1.0/src/fastersom/__init__.py +8 -0
- fastersom-0.1.0/src/fastersom/_som.py +258 -0
- fastersom-0.1.0/src/fastersom/py.typed +0 -0
fastersom-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Darius Schaub
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
fastersom-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastersom
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fast batch self-organising maps (SOM) in PyTorch for GPU and CPU
|
|
5
|
+
Keywords: self-organizing map,som,kohonen,clustering,pytorch,gpu,spatial omics
|
|
6
|
+
Author: Darius Schaub
|
|
7
|
+
Author-email: Darius Schaub <schaub.darius@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Dist: numpy>=1.24
|
|
22
|
+
Requires-Dist: torch>=2.3
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Project-URL: Homepage, https://github.com/dschaub95/fastersom
|
|
25
|
+
Project-URL: Issues, https://github.com/dschaub95/fastersom/issues
|
|
26
|
+
Project-URL: Changelog, https://github.com/dschaub95/fastersom/blob/main/CHANGELOG.md
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# fastersom
|
|
30
|
+
|
|
31
|
+
A small, fast batch self-organising map (SOM) in PyTorch. It implements the same algorithm and defaults as
|
|
32
|
+
[XPySom](https://github.com/Manciukic/xpysom) as configured by [spatiomic](https://github.com/complextissue/spatiomic)
|
|
33
|
+
(`so.dimension.som`): rectangular grid, gaussian neighbourhood, exponential sigma decay, XPySom's seeded initialisation.
|
|
34
|
+
Data stays on the device (CUDA, MPS or CPU) and the per-epoch update uses per-node sums, so an epoch costs one BMU
|
|
35
|
+
search plus a (nodes x nodes) matrix product.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
uv add fastersom # or: pip install fastersom
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import numpy as np
|
|
47
|
+
from fastersom import SOM
|
|
48
|
+
|
|
49
|
+
X = np.load("pixels.npy") # (n, d) or (..., d); numpy, array-like or torch
|
|
50
|
+
som = SOM(n_rows=30, n_cols=30, n_epochs=10, random_state=0) # device: cuda > mps > cpu
|
|
51
|
+
som.fit(X)
|
|
52
|
+
som.weights_ # (900, d) node weights, node = row * n_cols + col
|
|
53
|
+
som.labels_ # BMU index per training sample
|
|
54
|
+
labels = som.predict(X) # BMU index per sample
|
|
55
|
+
dist = som.transform(X) # (n, 900) distance to every node
|
|
56
|
+
print(som.quantization_error(X), som.topographic_error(X))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Options:
|
|
60
|
+
|
|
61
|
+
- `metric="cosine"` finds BMUs by cosine similarity. Zero-norm samples have no BMU, get label -1 and are left out of
|
|
62
|
+
the update and the error measures.
|
|
63
|
+
- `init="sample"` initialises the nodes from random samples instead of XPySom's random unit vectors.
|
|
64
|
+
- `sigma_initial` and `sigma_final` set the neighbourhood width schedule; the defaults reproduce spatiomic.
|
|
65
|
+
- `batch_size` bounds memory (about `batch_size x n_nodes` floats) without changing the algorithm.
|
|
66
|
+
|
|
67
|
+
`BatchSOM` is an alias for `SOM`.
|
|
68
|
+
|
|
69
|
+
## Benchmark
|
|
70
|
+
|
|
71
|
+
480,000 x 34 pixels, 30 x 30 nodes, 10 epochs, fit time only (mean of seeds 0-2):
|
|
72
|
+
|
|
73
|
+
| implementation | hardware | fit time | quantization error |
|
|
74
|
+
| ---------------------------- | ----------------- | -------- | ------------------ |
|
|
75
|
+
| fastersom | NVIDIA A100 | 0.085 s | 0.169 |
|
|
76
|
+
| spatiomic (XPySom, CuPy) | NVIDIA A100 | 0.46 s | 0.169 |
|
|
77
|
+
| spatiomic (XPySom, NumPy) | 256-core CPU | 40 s | 0.169 |
|
|
78
|
+
|
|
79
|
+
## Relation to XPySom and spatiomic
|
|
80
|
+
|
|
81
|
+
fastersom is a reimplementation in PyTorch of the batch SOM in XPySom (Mancini et al.), which itself follows
|
|
82
|
+
Kohonen's batch map. Starting from the same weights, one epoch matches XPySom to ~1e-7, for both the euclidean and
|
|
83
|
+
the cosine metric. XPySom's learning rate is omitted because it cancels in the batch update. XPySom's `sigma` is
|
|
84
|
+
twice fastersom's `sigma_initial`, because XPySom scales the gaussian width by `std_coeff=0.5`. Only the rectangular
|
|
85
|
+
topology, gaussian neighbourhood and exponential decay are supported.
|
|
86
|
+
|
|
87
|
+
## Development
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
uv sync # installs the dev group: pytest, ruff, pre-commit, twine, xpysom
|
|
91
|
+
uv run pre-commit install # ruff, uv-lock and file checks on every commit
|
|
92
|
+
uv run pytest
|
|
93
|
+
uv build && uv run twine check --strict dist/*
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
Apache-2.0
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# fastersom
|
|
2
|
+
|
|
3
|
+
A small, fast batch self-organising map (SOM) in PyTorch. It implements the same algorithm and defaults as
|
|
4
|
+
[XPySom](https://github.com/Manciukic/xpysom) as configured by [spatiomic](https://github.com/complextissue/spatiomic)
|
|
5
|
+
(`so.dimension.som`): rectangular grid, gaussian neighbourhood, exponential sigma decay, XPySom's seeded initialisation.
|
|
6
|
+
Data stays on the device (CUDA, MPS or CPU) and the per-epoch update uses per-node sums, so an epoch costs one BMU
|
|
7
|
+
search plus a (nodes x nodes) matrix product.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
uv add fastersom # or: pip install fastersom
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import numpy as np
|
|
19
|
+
from fastersom import SOM
|
|
20
|
+
|
|
21
|
+
X = np.load("pixels.npy") # (n, d) or (..., d); numpy, array-like or torch
|
|
22
|
+
som = SOM(n_rows=30, n_cols=30, n_epochs=10, random_state=0) # device: cuda > mps > cpu
|
|
23
|
+
som.fit(X)
|
|
24
|
+
som.weights_ # (900, d) node weights, node = row * n_cols + col
|
|
25
|
+
som.labels_ # BMU index per training sample
|
|
26
|
+
labels = som.predict(X) # BMU index per sample
|
|
27
|
+
dist = som.transform(X) # (n, 900) distance to every node
|
|
28
|
+
print(som.quantization_error(X), som.topographic_error(X))
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Options:
|
|
32
|
+
|
|
33
|
+
- `metric="cosine"` finds BMUs by cosine similarity. Zero-norm samples have no BMU, get label -1 and are left out of
|
|
34
|
+
the update and the error measures.
|
|
35
|
+
- `init="sample"` initialises the nodes from random samples instead of XPySom's random unit vectors.
|
|
36
|
+
- `sigma_initial` and `sigma_final` set the neighbourhood width schedule; the defaults reproduce spatiomic.
|
|
37
|
+
- `batch_size` bounds memory (about `batch_size x n_nodes` floats) without changing the algorithm.
|
|
38
|
+
|
|
39
|
+
`BatchSOM` is an alias for `SOM`.
|
|
40
|
+
|
|
41
|
+
## Benchmark
|
|
42
|
+
|
|
43
|
+
480,000 x 34 pixels, 30 x 30 nodes, 10 epochs, fit time only (mean of seeds 0-2):
|
|
44
|
+
|
|
45
|
+
| implementation | hardware | fit time | quantization error |
|
|
46
|
+
| ---------------------------- | ----------------- | -------- | ------------------ |
|
|
47
|
+
| fastersom | NVIDIA A100 | 0.085 s | 0.169 |
|
|
48
|
+
| spatiomic (XPySom, CuPy) | NVIDIA A100 | 0.46 s | 0.169 |
|
|
49
|
+
| spatiomic (XPySom, NumPy) | 256-core CPU | 40 s | 0.169 |
|
|
50
|
+
|
|
51
|
+
## Relation to XPySom and spatiomic
|
|
52
|
+
|
|
53
|
+
fastersom is a reimplementation in PyTorch of the batch SOM in XPySom (Mancini et al.), which itself follows
|
|
54
|
+
Kohonen's batch map. Starting from the same weights, one epoch matches XPySom to ~1e-7, for both the euclidean and
|
|
55
|
+
the cosine metric. XPySom's learning rate is omitted because it cancels in the batch update. XPySom's `sigma` is
|
|
56
|
+
twice fastersom's `sigma_initial`, because XPySom scales the gaussian width by `std_coeff=0.5`. Only the rectangular
|
|
57
|
+
topology, gaussian neighbourhood and exponential decay are supported.
|
|
58
|
+
|
|
59
|
+
## Development
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
uv sync # installs the dev group: pytest, ruff, pre-commit, twine, xpysom
|
|
63
|
+
uv run pre-commit install # ruff, uv-lock and file checks on every commit
|
|
64
|
+
uv run pytest
|
|
65
|
+
uv build && uv run twine check --strict dist/*
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
Apache-2.0
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastersom"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Fast batch self-organising maps (SOM) in PyTorch for GPU and CPU"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
keywords = [
|
|
10
|
+
"self-organizing map",
|
|
11
|
+
"som",
|
|
12
|
+
"kohonen",
|
|
13
|
+
"clustering",
|
|
14
|
+
"pytorch",
|
|
15
|
+
"gpu",
|
|
16
|
+
"spatial omics",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Programming Language :: Python :: 3.14",
|
|
27
|
+
"Topic :: Scientific/Engineering :: Bio-Informatics",
|
|
28
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
29
|
+
"Typing :: Typed",
|
|
30
|
+
]
|
|
31
|
+
dependencies = [
|
|
32
|
+
"numpy>=1.24",
|
|
33
|
+
"torch>=2.3",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[[project.authors]]
|
|
37
|
+
name = "Darius Schaub"
|
|
38
|
+
email = "schaub.darius@gmail.com"
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://github.com/dschaub95/fastersom"
|
|
42
|
+
Issues = "https://github.com/dschaub95/fastersom/issues"
|
|
43
|
+
Changelog = "https://github.com/dschaub95/fastersom/blob/main/CHANGELOG.md"
|
|
44
|
+
|
|
45
|
+
[build-system]
|
|
46
|
+
requires = ["uv_build>=0.13.4,<0.14.0"]
|
|
47
|
+
build-backend = "uv_build"
|
|
48
|
+
|
|
49
|
+
[dependency-groups]
|
|
50
|
+
dev = [
|
|
51
|
+
"pre-commit>=4.6.2",
|
|
52
|
+
"pytest>=9.1.1",
|
|
53
|
+
"ruff>=0.17.1",
|
|
54
|
+
"twine>=7.0.0",
|
|
55
|
+
"xpysom>=1.0.7",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
[tool.pytest]
|
|
59
|
+
minversion = "9.0"
|
|
60
|
+
testpaths = ["tests"]
|
|
61
|
+
addopts = [
|
|
62
|
+
"-ra",
|
|
63
|
+
"--import-mode=importlib",
|
|
64
|
+
]
|
|
65
|
+
strict = true
|
|
66
|
+
filterwarnings = ["error"]
|
|
67
|
+
|
|
68
|
+
[tool.ruff]
|
|
69
|
+
line-length = 120
|
|
70
|
+
src = [
|
|
71
|
+
"src",
|
|
72
|
+
"tests",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
[tool.ruff.lint]
|
|
76
|
+
select = [
|
|
77
|
+
"E",
|
|
78
|
+
"W",
|
|
79
|
+
"F",
|
|
80
|
+
"I",
|
|
81
|
+
"B",
|
|
82
|
+
"UP",
|
|
83
|
+
"SIM",
|
|
84
|
+
"C4",
|
|
85
|
+
"NPY",
|
|
86
|
+
"PT",
|
|
87
|
+
"RUF",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
[tool.ruff.lint.per-file-ignores]
|
|
91
|
+
"tests/**" = ["C408"]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastersom"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Fast batch self-organising maps (SOM) in PyTorch for GPU and CPU"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{ name = "Darius Schaub", email = "schaub.darius@gmail.com" }]
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = ["self-organizing map", "som", "kohonen", "clustering", "pytorch", "gpu", "spatial omics"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Science/Research",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Programming Language :: Python :: 3.14",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Bio-Informatics",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"numpy>=1.24",
|
|
26
|
+
"torch>=2.3", # first release built against NumPy 2
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/dschaub95/fastersom"
|
|
31
|
+
Issues = "https://github.com/dschaub95/fastersom/issues"
|
|
32
|
+
Changelog = "https://github.com/dschaub95/fastersom/blob/main/CHANGELOG.md"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["uv_build>=0.13.4,<0.14.0"]
|
|
36
|
+
build-backend = "uv_build"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"pre-commit>=4.6.2",
|
|
41
|
+
"pytest>=9.1.1",
|
|
42
|
+
"ruff>=0.17.1",
|
|
43
|
+
"twine>=7.0.0",
|
|
44
|
+
"xpysom>=1.0.7",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[tool.pytest]
|
|
48
|
+
minversion = "9.0"
|
|
49
|
+
testpaths = ["tests"]
|
|
50
|
+
addopts = ["-ra", "--import-mode=importlib"]
|
|
51
|
+
strict = true
|
|
52
|
+
filterwarnings = ["error"]
|
|
53
|
+
|
|
54
|
+
[tool.ruff]
|
|
55
|
+
line-length = 120
|
|
56
|
+
src = ["src", "tests"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "W", "F", "I", "B", "UP", "SIM", "C4", "NPY", "PT", "RUF"]
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint.per-file-ignores]
|
|
62
|
+
"tests/**" = ["C408"]
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Batch self-organising map (Kohonen's batch map) in PyTorch.
|
|
2
|
+
|
|
3
|
+
Each epoch assigns every sample x_i to its best matching unit c(x_i) and then sets every node to the
|
|
4
|
+
neighbourhood-weighted mean of the samples,
|
|
5
|
+
|
|
6
|
+
w_k = sum_i h(c(x_i), k) x_i / sum_i h(c(x_i), k), h(j, k) = exp(-||r_j - r_k||^2 / (2 sigma(t)^2)),
|
|
7
|
+
|
|
8
|
+
keeping w_k if the denominator is 0. r_j are the node coordinates on the rectangular grid and sigma decays
|
|
9
|
+
exponentially, sigma(t) = sigma_initial * (sigma_final / sigma_initial) ** (t / n_epochs).
|
|
10
|
+
|
|
11
|
+
Grouping samples by BMU gives the same update from per-node sums: with S_j the sum and n_j the count of samples whose
|
|
12
|
+
BMU is j, numerator = H @ S and denominator = H @ n, H the (nodes x nodes) neighbourhood matrix. This costs
|
|
13
|
+
O(nodes^2) per epoch instead of O(n_samples * nodes).
|
|
14
|
+
|
|
15
|
+
References:
|
|
16
|
+
T. Kohonen, Self-Organizing Maps, 3rd ed., Springer, 2001.
|
|
17
|
+
J. Vesanto et al., SOM Toolbox for Matlab 5, Helsinki University of Technology, 2000.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from math import ceil, isfinite
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
import torch
|
|
24
|
+
|
|
25
|
+
_METRICS = ("euclidean", "cosine")
|
|
26
|
+
_INITS = ("random", "sample")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _is_int(value, minimum: int) -> bool:
|
|
30
|
+
return isinstance(value, int | np.integer) and not isinstance(value, bool) and value >= minimum
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _default_device() -> torch.device:
|
|
34
|
+
if torch.cuda.is_available():
|
|
35
|
+
return torch.device("cuda")
|
|
36
|
+
if torch.backends.mps.is_available():
|
|
37
|
+
return torch.device("mps")
|
|
38
|
+
return torch.device("cpu")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SOM:
|
|
42
|
+
"""Batch self-organising map on a rectangular grid with a gaussian neighbourhood.
|
|
43
|
+
|
|
44
|
+
The defaults reproduce the maps of spatiomic's ``so.dimension.som``.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
n_rows: Number of grid rows.
|
|
48
|
+
n_cols: Number of grid columns.
|
|
49
|
+
n_epochs: Number of epochs; each makes one weight update from all samples.
|
|
50
|
+
sigma_initial: Initial gaussian neighbourhood width in grid units. Defaults to
|
|
51
|
+
ceil(min(n_rows, n_cols) / 2) / 2.
|
|
52
|
+
sigma_final: Width the exponential schedule decays towards (reached at t = n_epochs), > 0. Defaults to
|
|
53
|
+
0.1 * sigma_initial.
|
|
54
|
+
init: ``"random"`` draws weights uniformly from [-1, 1]^d with numpy's ``RandomState(random_state)`` and
|
|
55
|
+
normalises them to unit length; ``"sample"`` uses randomly chosen samples (non-zero ones for cosine).
|
|
56
|
+
metric: ``"euclidean"`` or ``"cosine"``. Under cosine, zero-norm samples have no BMU: they get label -1, are
|
|
57
|
+
excluded from the update and the error measures, and have cosine distance 1 to every node.
|
|
58
|
+
random_state: Seed for the initialisation.
|
|
59
|
+
device: Torch device. Defaults to cuda, then mps, then cpu.
|
|
60
|
+
batch_size: Samples processed at once in BMU search, aggregation, predict and transform. Affects memory
|
|
61
|
+
(about batch_size x n_nodes floats) and speed only. Each epoch's update is the same up to float
|
|
62
|
+
summation order, but over several epochs such rounding differences (as between devices) can flip
|
|
63
|
+
near-tied BMUs, so maps agree in quality rather than bit for bit. Defaults to 65536 on GPU and 8192
|
|
64
|
+
on CPU.
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
weights_: Node weights, shape (n_rows * n_cols, n_features), row-major (node = row * n_cols + col).
|
|
68
|
+
labels_: BMU of every training sample under the final weights.
|
|
69
|
+
n_features_in_: Number of features seen in fit.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
n_rows: int = 30,
|
|
75
|
+
n_cols: int = 30,
|
|
76
|
+
n_epochs: int = 10,
|
|
77
|
+
sigma_initial: float | None = None,
|
|
78
|
+
sigma_final: float | None = None,
|
|
79
|
+
init: str = "random",
|
|
80
|
+
metric: str = "euclidean",
|
|
81
|
+
random_state: int | None = None,
|
|
82
|
+
device: str | torch.device | None = None,
|
|
83
|
+
batch_size: int | None = None,
|
|
84
|
+
):
|
|
85
|
+
self.n_rows = n_rows
|
|
86
|
+
self.n_cols = n_cols
|
|
87
|
+
self.n_epochs = n_epochs
|
|
88
|
+
self.sigma_initial = sigma_initial
|
|
89
|
+
self.sigma_final = sigma_final
|
|
90
|
+
self.init = init
|
|
91
|
+
self.metric = metric
|
|
92
|
+
self.random_state = random_state
|
|
93
|
+
self.device = device
|
|
94
|
+
self.batch_size = batch_size
|
|
95
|
+
|
|
96
|
+
def _setup(self) -> None:
|
|
97
|
+
if self.metric not in _METRICS:
|
|
98
|
+
raise ValueError(f"metric must be one of {_METRICS}, got {self.metric!r}")
|
|
99
|
+
if self.init not in _INITS:
|
|
100
|
+
raise ValueError(f"init must be one of {_INITS}, got {self.init!r}")
|
|
101
|
+
for name in ("n_rows", "n_cols", "n_epochs"):
|
|
102
|
+
if not _is_int(getattr(self, name), 1):
|
|
103
|
+
raise ValueError(f"{name} must be an integer >= 1, got {getattr(self, name)!r}")
|
|
104
|
+
if self.batch_size is not None and not _is_int(self.batch_size, 1):
|
|
105
|
+
raise ValueError(f"batch_size must be None or an integer >= 1, got {self.batch_size!r}")
|
|
106
|
+
self._device = torch.device(self.device) if self.device is not None else _default_device()
|
|
107
|
+
self._batch_size = self.batch_size or (8192 if self._device.type == "cpu" else 1 << 16)
|
|
108
|
+
self._sigma0 = ceil(min(self.n_rows, self.n_cols) / 2) / 2 if self.sigma_initial is None else self.sigma_initial
|
|
109
|
+
self._sigma1 = 0.1 * self._sigma0 if self.sigma_final is None else self.sigma_final
|
|
110
|
+
if not all(isfinite(sigma) and sigma > 0 for sigma in (self._sigma0, self._sigma1)):
|
|
111
|
+
raise ValueError("sigma_initial and sigma_final must be finite and > 0")
|
|
112
|
+
self._coords = torch.cartesian_prod(torch.arange(self.n_rows), torch.arange(self.n_cols))
|
|
113
|
+
self._coords = self._coords.to(self._device, torch.float32)
|
|
114
|
+
self._grid_sq_dist = torch.cdist(self._coords, self._coords) ** 2
|
|
115
|
+
|
|
116
|
+
def _check_X(self, X) -> torch.Tensor:
|
|
117
|
+
data = torch.as_tensor(
|
|
118
|
+
X.detach() if isinstance(X, torch.Tensor) else np.ascontiguousarray(X),
|
|
119
|
+
dtype=torch.float32,
|
|
120
|
+
device=self._device,
|
|
121
|
+
)
|
|
122
|
+
if data.ndim < 2 or data.numel() == 0:
|
|
123
|
+
raise ValueError(f"X must have shape (n_samples, n_features) or (..., n_features), got {tuple(data.shape)}")
|
|
124
|
+
data = data.reshape(-1, data.shape[-1])
|
|
125
|
+
if hasattr(self, "n_features_in_") and data.shape[1] != self.n_features_in_:
|
|
126
|
+
raise ValueError(f"X has {data.shape[1]} features, but SOM was fitted with {self.n_features_in_}")
|
|
127
|
+
if not torch.isfinite(data).all():
|
|
128
|
+
raise ValueError("X contains NaN or infinite values")
|
|
129
|
+
return data
|
|
130
|
+
|
|
131
|
+
def _check_fitted(self) -> None:
|
|
132
|
+
if not hasattr(self, "weights_"):
|
|
133
|
+
raise RuntimeError("This SOM instance is not fitted yet, call fit() first")
|
|
134
|
+
|
|
135
|
+
def _init_weights(self, data: torch.Tensor) -> torch.Tensor:
|
|
136
|
+
rng = np.random.RandomState(self.random_state)
|
|
137
|
+
n_nodes = self.n_rows * self.n_cols
|
|
138
|
+
if self.init == "random":
|
|
139
|
+
weights = rng.rand(self.n_rows, self.n_cols, data.shape[1]) * 2 - 1
|
|
140
|
+
weights /= np.linalg.norm(weights, axis=-1, keepdims=True)
|
|
141
|
+
return torch.as_tensor(weights.reshape(n_nodes, -1), dtype=torch.float32, device=self._device)
|
|
142
|
+
candidates = torch.arange(len(data), device=self._device)
|
|
143
|
+
if self.metric == "cosine":
|
|
144
|
+
candidates = candidates[data.norm(dim=1) > 0]
|
|
145
|
+
if len(candidates) == 0:
|
|
146
|
+
raise ValueError("init='sample' with metric='cosine' needs at least one non-zero sample")
|
|
147
|
+
picks = rng.choice(len(candidates), n_nodes, replace=len(candidates) < n_nodes)
|
|
148
|
+
return data[candidates[torch.as_tensor(picks, device=self._device)]].clone()
|
|
149
|
+
|
|
150
|
+
def _scores(self, batch: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
|
|
151
|
+
"""Per-node score to minimise: ||w||^2 - 2 x.w (euclidean, ||x||^2 dropped) or -x.w / ||w|| (cosine)."""
|
|
152
|
+
if self.metric == "euclidean":
|
|
153
|
+
return torch.addmm((weights**2).sum(1), batch, weights.T, alpha=-2)
|
|
154
|
+
return -(batch @ (weights / weights.norm(dim=1, keepdim=True).clamp_min(1e-12)).T)
|
|
155
|
+
|
|
156
|
+
def _bmus(self, data: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
|
|
157
|
+
"""BMU per sample; -1 for zero-norm samples under the cosine metric."""
|
|
158
|
+
bmus = torch.cat([self._scores(batch, weights).argmin(1) for batch in data.split(self._batch_size)])
|
|
159
|
+
if self.metric == "cosine":
|
|
160
|
+
bmus[data.norm(dim=1) == 0] = -1
|
|
161
|
+
return bmus
|
|
162
|
+
|
|
163
|
+
def fit(self, X, y=None) -> "SOM":
|
|
164
|
+
"""Fits the map from a fresh initialisation.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
X: Samples, shape (n_samples, n_features) or (..., n_features); numpy array, array-like or torch tensor.
|
|
168
|
+
Any real values are fine; data is copied to the device once and stays there.
|
|
169
|
+
y: Ignored.
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
self
|
|
173
|
+
"""
|
|
174
|
+
self._setup()
|
|
175
|
+
for attr in ("weights_", "labels_", "n_features_in_"):
|
|
176
|
+
self.__dict__.pop(attr, None)
|
|
177
|
+
data = self._check_X(X)
|
|
178
|
+
weights = self._init_weights(data)
|
|
179
|
+
n_nodes = weights.shape[0]
|
|
180
|
+
for t in range(self.n_epochs):
|
|
181
|
+
sigma = self._sigma0 * (self._sigma1 / self._sigma0) ** (t / self.n_epochs)
|
|
182
|
+
sums, counts = torch.zeros_like(weights), weights.new_zeros(n_nodes)
|
|
183
|
+
for batch in data.split(self._batch_size):
|
|
184
|
+
bmus = self._scores(batch, weights).argmin(1)
|
|
185
|
+
if self.metric == "cosine": # zero-norm samples have no BMU and do not contribute
|
|
186
|
+
keep = batch.norm(dim=1) > 0
|
|
187
|
+
batch, bmus = batch[keep], bmus[keep]
|
|
188
|
+
sums.index_add_(0, bmus, batch)
|
|
189
|
+
counts += torch.bincount(bmus, minlength=n_nodes)
|
|
190
|
+
h = torch.exp(-self._grid_sq_dist / (2 * sigma**2))
|
|
191
|
+
numerator, denominator = h @ sums, h @ counts
|
|
192
|
+
weights = torch.where(denominator[:, None] > 0, numerator / denominator[:, None], weights)
|
|
193
|
+
self._weights = weights
|
|
194
|
+
self.weights_ = weights.cpu().numpy()
|
|
195
|
+
self.n_features_in_ = data.shape[1]
|
|
196
|
+
self.labels_ = self._bmus(data, weights).cpu().numpy()
|
|
197
|
+
return self
|
|
198
|
+
|
|
199
|
+
def predict(self, X) -> np.ndarray:
|
|
200
|
+
"""Returns the BMU index (int64) per sample; -1 for zero-norm samples under the cosine metric."""
|
|
201
|
+
self._check_fitted()
|
|
202
|
+
return self._bmus(self._check_X(X), self._weights).cpu().numpy()
|
|
203
|
+
|
|
204
|
+
def fit_predict(self, X, y=None) -> np.ndarray:
|
|
205
|
+
"""Fits the map and returns labels_."""
|
|
206
|
+
return self.fit(X).labels_
|
|
207
|
+
|
|
208
|
+
def _distances(self, batch: torch.Tensor) -> torch.Tensor:
|
|
209
|
+
if self.metric == "euclidean": # exact, unlike the BMU search, so large offsets do not cancel
|
|
210
|
+
return torch.cdist(batch, self._weights, compute_mode="donot_use_mm_for_euclid_dist")
|
|
211
|
+
cos = -self._scores(batch, self._weights) / batch.norm(dim=1, keepdim=True)
|
|
212
|
+
return torch.where(torch.isfinite(cos), (1 - cos).clamp(0, 2), 1.0)
|
|
213
|
+
|
|
214
|
+
def transform(self, X) -> np.ndarray:
|
|
215
|
+
"""Returns the distance of every sample to every node, shape (n_samples, n_nodes).
|
|
216
|
+
|
|
217
|
+
Euclidean or cosine distances (1 - cosine similarity) depending on the metric. The output is a dense
|
|
218
|
+
n_samples x n_nodes float32 array; for large inputs call it on slices or use predict.
|
|
219
|
+
"""
|
|
220
|
+
self._check_fitted()
|
|
221
|
+
data = self._check_X(X)
|
|
222
|
+
return torch.cat([self._distances(batch) for batch in data.split(self._batch_size)]).cpu().numpy()
|
|
223
|
+
|
|
224
|
+
def fit_transform(self, X, y=None) -> np.ndarray:
|
|
225
|
+
"""Fits the map and returns transform(X)."""
|
|
226
|
+
return self.fit(X).transform(X)
|
|
227
|
+
|
|
228
|
+
def _top2(self, X) -> tuple[torch.Tensor, torch.Tensor]:
|
|
229
|
+
"""Distance to the BMU and indices of the two best nodes, for every sample that has a BMU."""
|
|
230
|
+
self._check_fitted()
|
|
231
|
+
data = self._check_X(X)
|
|
232
|
+
if self.metric == "cosine":
|
|
233
|
+
data = data[data.norm(dim=1) > 0]
|
|
234
|
+
dists, nodes = [], []
|
|
235
|
+
for batch in data.split(self._batch_size):
|
|
236
|
+
best = self._scores(batch, self._weights).topk(min(2, len(self._weights)), dim=1, largest=False)
|
|
237
|
+
if self.metric == "euclidean":
|
|
238
|
+
dists.append((batch - self._weights[best.indices[:, 0]]).norm(dim=1))
|
|
239
|
+
else:
|
|
240
|
+
dists.append((1 + best.values[:, 0] / batch.norm(dim=1)).clamp(0, 2))
|
|
241
|
+
nodes.append(best.indices)
|
|
242
|
+
return torch.cat(dists), torch.cat(nodes)
|
|
243
|
+
|
|
244
|
+
def quantization_error(self, X) -> float:
|
|
245
|
+
"""Mean distance (in the chosen metric) between each sample and its BMU."""
|
|
246
|
+
dist, _ = self._top2(X)
|
|
247
|
+
return float(dist.cpu().double().mean()) # on the CPU because MPS has no float64
|
|
248
|
+
|
|
249
|
+
def topographic_error(self, X) -> float:
|
|
250
|
+
"""Fraction of samples whose first and second BMU are not adjacent on the grid (8-neighbourhood)."""
|
|
251
|
+
_, nodes = self._top2(X)
|
|
252
|
+
if nodes.shape[1] < 2:
|
|
253
|
+
return 0.0
|
|
254
|
+
offset = (self._coords[nodes[:, 0]] - self._coords[nodes[:, 1]]).abs().amax(1)
|
|
255
|
+
return float((offset > 1).cpu().double().mean())
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
BatchSOM = SOM
|
|
File without changes
|