API Reference
GTSOM
gtsom.GTSOM
GTSOM(
rho_0,
rho_f,
tau=None,
halflife_epochs=None,
anneal="exponential",
n_jobs=None,
nbr_topo_alpha_0=1.0,
nbr_topo_alpha_f=None,
proto_topo="CONN_GD",
compute_dr_metrics=False,
nbr_influence_min=0.01,
random_state=None,
)
General Topology Self-Organizing Map.
The constructor sets all learning parameters (schedules, parallelism,
diagnostics). After construction, call :meth:from_grid or
:meth:from_data to set the output topology and initialize prototypes,
then call :meth:fit to train.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rho_0
|
float
|
Initial neighborhood bandwidth. |
required |
rho_f
|
float
|
Final (minimum) neighborhood bandwidth. |
required |
tau
|
float
|
Exponential decay time constant in epochs. Mutually exclusive with
|
None
|
halflife_epochs
|
float
|
Epoch at which each annealed parameter reaches the geometric midpoint
between its initial and final values. Mutually exclusive with |
None
|
anneal
|
exponential
|
Annealing schedule type. Currently only exponential decay is supported. |
'exponential'
|
n_jobs
|
int or None
|
Number of parallel threads for prototype updates. |
None
|
nbr_topo_alpha_0
|
float
|
Initial value of the topology-blending parameter, in [0, 1]. When
1.0, pure lattice-based neighborhood (classical SOM). When < 1.0,
a blend of lattice and CONN-graph neighborhood is used. See
:meth: |
1.0
|
nbr_topo_alpha_f
|
float
|
Final value of the topology-blending parameter, in [0, 1]. Defaults
to |
None
|
compute_dr_metrics
|
bool
|
Whether to compute dimensionality reduction quality metrics at each
snapshot. When True, each entry in |
False
|
nbr_influence_min
|
float
|
Neighbourhood kernel activation floor. Kernel weights below this value are zeroed. Shared across all architecture configurations built on this instance. |
0.01
|
proto_topo
|
(CONN_GD, STK_CADJ, STK_dense)
|
Input-space (prototype) topology used to compute the high-dimensional
neighborhood signal when
|
'CONN_GD'
|
random_state
|
int or None
|
Seed for all random operations. |
None
|
Notes
GTSOM does not perform any internal scaling of X. It is the caller's responsibility to whiten, standardize, or otherwise preprocess X before passing it to any method.
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither or both of |
Source code in src/gtsom/gtsom.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
M
property
M
Number of prototypes (neurons).
d
property
d
Dimensionality of the high-dimensional feature space.
from_grid
from_grid(
X,
shape,
coord_init="hex",
W_init="random",
labels=None,
ctab=None,
)
Set a regular grid output topology and initialize prototypes.
Wipes any existing architecture (W, embed, recaller, learn_history_,
etc.) and builds a fresh grid-based configuration. All learning
parameters (rho schedules, nbr_influence_min, etc.) are inherited from the
values set in __init__ and are not changed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Training data. Used for prototype initialisation; not stored. |
required |
shape
|
tuple of int
|
Grid dimensions, e.g. |
required |
coord_init
|
(hex, rect)
|
Grid layout. |
'hex'
|
W_init
|
(random, pca)
|
How to initialize prototype vectors W.
|
'random'
|
labels
|
(array - like, shape(N))
|
Optional observation labels. If provided, prototype-level label
summaries (WL, WL_Dist, WL_Purity) are computed during the
initial recall and stored on |
None
|
ctab
|
dict or None
|
Optional |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
GTSOM
|
Returns self for optional method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/gtsom/gtsom.py
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
from_data
from_data(
X,
M,
coord_dim=2,
coord_init="pca",
W_init="kmeans",
coord_topo="delaunay",
labels=None,
ctab=None,
)
Set a data-driven output topology and initialize prototypes.
Wipes any existing architecture (W, embed, recaller, learn_history_,
etc.) and builds a fresh data-driven configuration. All learning
parameters (rho schedules, nbr_influence_min, etc.) are inherited from the
values set in __init__ and are not changed.
Prototype vectors are found via vector quantisation of X, projected
to coord_dim dimensions to define neuron positions, and either
a Delaunay triangulation or Gabriel graph of those positions defines
the output topology.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Training data. |
required |
M
|
int
|
Number of prototypes (neurons). Must be >= 3 (required for Delaunay triangulation) and <= N. |
required |
coord_dim
|
(2, 3)
|
Dimensionality of the output embedding. |
2
|
coord_init
|
(pca, le, random, random_proj)
|
Dimensionality reduction method for computing neuron coordinates from the initial prototype vectors.
|
'pca'
|
W_init
|
(kmeans, random)
|
How to find initial prototype vectors.
|
'kmeans'
|
coord_topo
|
(delaunay, gabriel)
|
Graph used to define the output-space topology from the projected prototype coordinates.
|
'delaunay'
|
labels
|
(array - like, shape(N))
|
Optional observation labels. If provided, prototype-level label
summaries (WL, WL_Dist, WL_Purity) are computed during the
initial recall and stored on |
None
|
ctab
|
dict or None
|
Optional |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
GTSOM
|
Returns self for optional method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If |
Source code in src/gtsom/gtsom.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | |
fit
fit(X, n_epochs, labels=None, verbose=True, plot_every=5)
Fit the GTSOM to data X using batch SOM learning.
:meth:from_grid or :meth:from_data must be called before
:meth:fit. The rho annealing schedule advances based on
self.age, so successive calls to :meth:fit continue from
where the previous call left off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Training data. Should be the same dataset passed to
:meth: |
required |
n_epochs
|
int
|
Number of training epochs to run in this call. |
required |
labels
|
(array - like, shape(N))
|
Observation labels. If labels were provided at
:meth: |
None
|
verbose
|
bool
|
If True, print a formatted table of training metrics after each epoch. |
True
|
plot_every
|
int
|
Display a SOM plot every this many epochs during training. Set to 0 to disable in-training plotting. |
5
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
Notes
GTSOM does not perform any internal scaling of X.
Source code in src/gtsom/gtsom.py
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
transform
transform(X)
Map data points to output coordinates via BMU lookup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
coords |
(ndarray, shape(N, dim))
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the model has not been fitted yet. |
Source code in src/gtsom/gtsom.py
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | |
fit_transform
fit_transform(X, n_epochs, **fit_kwargs)
Fit the GTSOM and return output coordinates.
Equivalent to calling :meth:fit followed by :meth:transform.
n_epochs must be supplied explicitly; it is passed through to
:meth:fit along with any additional keyword arguments. Example::
coords = som.fit_transform(X, n_epochs=100, labels=y, verbose=False)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
|
required |
n_epochs
|
int
|
Number of training epochs. Passed to :meth: |
required |
**fit_kwargs
|
Additional keyword arguments forwarded to :meth: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
coords |
(ndarray, shape(N, dim))
|
|
Source code in src/gtsom/gtsom.py
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 | |
plot
plot(
color_by="auto",
cmap="viridis",
rf_size_log_threshold=10,
legend_pos="right",
title="GTSOM",
subtitle=None,
xlab="SOM$_1$",
ylab="SOM$_2$",
)
Plot the SOM in output (lattice) space using plotnine.
Delegates to :func:~gtsom.vis_tools.vis_embedding_discrete when
labels are available, and to
:func:~gtsom.vis_tools.vis_embedding_continuous otherwise (coloring
by MQE). Neurons are drawn at their embed.coords positions,
connected by edges from embed.adjacency. Point size is mapped to
receptive field size (RFSize), with the size transform (linear or
log10) chosen automatically based on the distribution of RFSize values.
If DR metrics have been computed for the current snapshot, they are
formatted and shown as a plot caption.
Returns a plotnine.ggplot object — nothing is displayed
automatically. Call .save(path) to write to disk, or evaluate
the object in a notebook to display it inline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color_by
|
(auto, mqe, rfsize, labels)
|
Quantity used to color neurons.
|
'auto'
|
cmap
|
str
|
Colormap name for continuous quantities ('mqe', 'rfsize'). Any matplotlib-compatible string is accepted (e.g. 'plasma', 'magma'). Ignored for label plots. |
'viridis'
|
rf_size_log_threshold
|
float
|
Controls whether RFSize is mapped to point size on a linear
or log10 scale. If |
10
|
legend_pos
|
str
|
Legend / colorbar position. One of |
'right'
|
title
|
str or None
|
Main title line. |
'GTSOM'
|
subtitle
|
str or None
|
Subtitle line. If None, auto-generates |
None
|
xlab
|
str
|
Label for the horizontal axis. |
'SOM$_1$'
|
ylab
|
str
|
Label for the vertical axis. |
'SOM$_2$'
|
Returns:
| Type | Description |
|---|---|
ggplot
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
NotImplementedError
|
If |
ValueError
|
If |
Source code in src/gtsom/gtsom.py
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 | |
get_snapshot_fig
get_snapshot_fig(
index,
cmap="viridis",
rf_size_log_threshold=10,
legend_pos="right",
title="GTSOM",
subtitle=None,
xlab="SOM$_1$",
ylab="SOM$_2$",
)
Reconstruct a live, modifiable plotnine figure from a historical
snapshot stored in self.learn_history_.
Unlike :meth:plot, which generates a figure from the current live
GTSOM state, this method rebuilds a figure from the coordinates,
adjacency, and color data that were recorded at a specific training
epoch. The returned object is a fully live plotnine.ggplot that
supports the + operator for theme overrides, relabeling, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Index into |
required |
cmap
|
str
|
Colormap for continuous quantities ( |
'viridis'
|
rf_size_log_threshold
|
float
|
Controls the point-size transform for receptive field sizes.
See :meth: |
10
|
legend_pos
|
str
|
Legend position: |
'right'
|
title
|
str or None
|
Main title line. |
'GTSOM'
|
subtitle
|
str or None
|
Subtitle. If None, auto-generates |
None
|
xlab
|
str
|
Horizontal axis label. |
'SOM$_1$'
|
ylab
|
str
|
Vertical axis label. |
'SOM$_2$'
|
Returns:
| Type | Description |
|---|---|
ggplot
|
A live, modifiable figure. Supports |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
RuntimeError
|
If :meth: |
NotImplementedError
|
If the snapshot embedding is not 2-D. |
Source code in src/gtsom/gtsom.py
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 | |
update_embedding
update_embedding(coords)
Replace the output-space embedding coordinates and refresh the neighborhood weight matrix atomically.
Calls self.embed.update_coords(coords) to validate the new
positions, rebuild adjacency, and recompute geodesic distances.
Then immediately recomputes self.nbr_W from the updated
topology using the current annealing bandwidth
self.rho_schedule(self.age), so that the next :meth:fit
call starts with a consistent neighborhood structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
(array - like, shape(M, dim))
|
New low-dimensional prototype positions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
GTSOM
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
ValueError
|
Propagated from :meth: |
Source code in src/gtsom/gtsom.py
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 | |
save
save(path)
Save this GTSOM to an HDF5 file.
Serializes all learning parameters, architecture state (W, Embedding,
VQRecaller), training history (learn_history_), and the color
table (ctab). The file can be reloaded with :meth:load to
resume training, run :meth:transform, or reproduce any historical
plot via :meth:get_snapshot_fig — no retraining required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination file path. Created or overwritten. |
required |
See Also
GTSOM.load : Reconstruct a GTSOM from a saved file.
Examples:
>>> som.fit(X, n_epochs=100)
>>> som.save("som.h5")
>>> som2 = GTSOM.load("som.h5")
>>> som2.plot()
>>> som2.fit(X, n_epochs=50) # resume training
Source code in src/gtsom/gtsom.py
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 | |
load
classmethod
load(path)
Load a GTSOM from an HDF5 file created by :meth:save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to an HDF5 file previously created by :meth: |
required |
Returns:
| Type | Description |
|---|---|
GTSOM
|
Fully reconstructed instance, ready for :meth: |
See Also
GTSOM.save : Save a GTSOM to an HDF5 file.
Examples:
>>> som = GTSOM.load("som.h5")
>>> som.age
100
>>> som.plot()
>>> som.fit(X, n_epochs=50)
Source code in src/gtsom/gtsom.py
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 | |
Utilities
gtsom.utils.ExponentialAnneal
ExponentialAnneal(initial, final, tau)
Exponential annealing schedule for a scalar parameter.
Computes the annealed value at a given age (epoch count) as::
value(age) = initial * (final / initial) ** (age / tau)
The result is clipped at final once the schedule reaches it,
ensuring the final value is respected exactly regardless of how many
epochs have elapsed.
Supports both decreasing schedules (final < initial, e.g. annealing
a neighborhood bandwidth from broad to narrow) and increasing schedules
(final > initial, e.g. shifting neighborhood influence from
lattice-dominated toward CONN-dominated over training). The direction
is inferred automatically from the relationship between initial
and final; the formula and clipping behavior adapt accordingly.
initial and final may be zero. If either is zero it is replaced
internally by a small positive floor (_ANNEAL_EPS = 1e-8) before
the formula is applied, keeping the exponential well-defined. The
reported self.initial / self.final always reflect the values
as supplied by the caller; only the internal computation is clipped.
The resulting schedule is a true exponential in value space — not
in a translated space — so the curve shape is never distorted by
the zero-handling.
Intended for use with any parameter that requires monotonic change during training — neighborhood bandwidth (rho), topology-blending weight (nbr_topo_alpha), learning rate, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial
|
float
|
Starting value of the parameter (at age=0). Must be >= 0. |
required |
final
|
float
|
Target value of the parameter. Must be >= 0. If |
required |
tau
|
float
|
Time constant in epochs. Controls how quickly the parameter moves
from |
required |
Examples:
Decreasing schedule (decay):
>>> schedule = ExponentialAnneal(initial=5.0, final=0.3, tau=20)
>>> schedule(0)
5.0
>>> schedule(10) # half a tau — midway through the decay
1.2247...
>>> schedule(20) # one full tau — reaches final exactly
0.3
>>> schedule(1000) # beyond tau — clipped at final
0.3
Decreasing to zero:
>>> schedule = ExponentialAnneal(initial=1.0, final=0.0, tau=20)
>>> schedule(0)
1.0
>>> schedule(1000) # clipped at final
0.0
Increasing schedule (ramp):
>>> schedule = ExponentialAnneal(initial=0.0, final=1.0, tau=20)
>>> schedule(0)
0.0
>>> schedule(1000) # clipped at final
1.0
Construction from a half-life epoch count:
>>> schedule = ExponentialAnneal.from_halflife(initial=5.0, final=0.3,
... halflife_epochs=50)
>>> round(schedule(50), 6) # geometric midpoint of 5.0 and 0.3
1.2247...
>>> round(schedule(100), 6) # clipped at final
0.3
Source code in src/gtsom/utils.py
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |
from_halflife
classmethod
from_halflife(initial, final, halflife_epochs)
Construct a schedule where halflife_epochs is the geometric half-life.
halflife_epochs is the epoch at which the parameter reaches the
geometric mean of initial and final::
value(halflife_epochs) = sqrt(initial * final)
This is a half-life in log space (the schedule is linear in
log space, and the geometric mean is the arithmetic midpoint of
log(initial) and log(final)), not in linear space.
.. note:: Geometric vs arithmetic midpoint
The geometric midpoint ``sqrt(initial * final)`` is always
closer to ``final`` than the arithmetic midpoint
``(initial + final) / 2`` when ``initial != final``. For
example, with ``initial=10, final=0.1``:
- Arithmetic midpoint: 5.05 (barely moved from initial)
- Geometric midpoint: 1.0 (already close to final)
This means the schedule will feel "fast then slow" in linear
space — the parameter drops quickly early on and then settles
gradually. If you expect to be "halfway there" in the ordinary
(arithmetic) sense at ``halflife_epochs``, you will find the
parameter has already moved further than that.
.. note:: Relationship to tau and total training epochs
``tau = 2 * halflife_epochs``, and the schedule is clipped at
``final`` at age ``2 * halflife_epochs``. This means:
- Setting ``halflife_epochs ≈ n_epochs / 4`` places the
geometric midpoint at the first quarter of training, giving
a steep initial drop followed by a long flat tail — the
classic exponential shape.
- Setting ``halflife_epochs ≈ n_epochs / 2`` places the
geometric midpoint at the halfway point, so the schedule is
still actively decaying at the end of training and the curve
looks nearly linear over the training window.
As a rule of thumb, set ``halflife_epochs`` to roughly a
quarter of your total training epochs to get a visually
exponential decay with a clear knee and flat tail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial
|
float
|
Starting value at age=0. |
required |
final
|
float
|
Floor value; clipped at this value from age
|
required |
halflife_epochs
|
float
|
The epoch at which the parameter reaches the geometric mean
|
required |
Returns:
| Type | Description |
|---|---|
ExponentialAnneal
|
|
Examples:
>>> s = ExponentialAnneal.from_halflife(initial=3.0, final=0.3,
... halflife_epochs=50)
>>> round(s(0), 4)
3.0
>>> round(s(50), 4) # geometric midpoint sqrt(3.0 * 0.3) ≈ 0.9487
0.9487
>>> round(s(100), 4) # clipped at final
0.3
With halflife_epochs = n_epochs / 4 for a classic exponential shape:
>>> s = ExponentialAnneal.from_halflife(initial=10.0, final=0.1,
... halflife_epochs=25)
>>> round(s(25), 4) # geometric midpoint sqrt(10 * 0.1) = 1.0
1.0
>>> round(s(50), 4) # clipped at final well before end of training
0.1
Source code in src/gtsom/utils.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 | |
__call__
__call__(age)
Return the annealed parameter value at the given age.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
age
|
int or float
|
Current epoch count (0-based). |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in src/gtsom/utils.py
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 | |
values
values(n_epochs)
Return the annealed values for epochs 0 through n_epochs - 1.
Useful for inspecting or plotting the planned schedule before training begins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_epochs
|
int
|
|
required |
Returns:
| Type | Description |
|---|---|
(ndarray, shape(n_epochs))
|
|
Source code in src/gtsom/utils.py
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |
to_dict
to_dict()
Return a plain dict representation of this schedule.
Returns:
| Type | Description |
|---|---|
dict with keys: initial (float), final (float), tau (float)
|
|
Source code in src/gtsom/utils.py
697 698 699 700 701 702 703 704 705 706 707 708 709 | |
from_dict
classmethod
from_dict(d)
Reconstruct an ExponentialAnneal from a dict produced by
:meth:to_dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
ExponentialAnneal
|
|
Source code in src/gtsom/utils.py
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | |
gtsom.utils.DataValidator
DataValidator(X, labels=None)
Validates a data matrix X (and optionally observation labels) and stores lightweight fingerprints for consistency checking across subsequent calls.
Construction validates X (must be 2-D) and records its fingerprint, along
with an optional label fingerprint derived from labels. The
:meth:check method warns whenever a later (X, labels) pair does not
match what was seen at construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array - like
|
Data matrix to validate and fingerprint. |
required |
labels
|
array - like or None
|
Observation labels. If provided, a label fingerprint is stored as a
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If X is not 2-D after conversion to ndarray. |
Examples:
>>> import numpy as np
>>> validator = DataValidator(np.ones((100, 5)))
>>> validator.shape
(100, 5)
>>> validator.check(np.ones((100, 5))) # silent — matches
>>> validator.check(np.ones((200, 5)), context="fit") # warns: X mismatch
With labels:
>>> y = np.array([0, 0, 1, 1, 2, 2])
>>> validator = DataValidator(np.ones((6, 3)), labels=y)
>>> validator.check(np.ones((6, 3)), labels=y) # silent — matches
>>> validator.check(np.ones((6, 3)), labels=None, context="fit") # warns: labels missing
Source code in src/gtsom/utils.py
62 63 64 65 66 67 68 69 70 71 72 73 74 | |
shape
property
shape
Shape (N, d) of the validated dataset.
dtype
property
dtype
dtype of the validated dataset.
has_labels
property
has_labels
True if labels were provided at construction.
check
check(X, labels=None, context='')
Warn if X or labels do not match the stored fingerprints.
Four distinct warning cases are handled:
- X mismatch — the incoming
Xhas a different shape, dtype, or summary statistics from the dataset seen at construction. - Labels missing at check time — labels were provided at
construction but
labels=Nonehere;recaller.WLwill be stale after this call. - Label universe / count mismatch — both construction and this
call provided labels, but the set of unique values or their per-class
counts differ;
ctaband snapshotWLmay be inconsistent. - Labels provided only at check time — labels were not provided at construction; re-initialize the SOM with labels to enable label coloring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array - like
|
Incoming data matrix to check. |
required |
labels
|
array - like or None
|
Incoming observation labels to check. |
None
|
context
|
str
|
Caller name included in warning messages for traceability
(e.g. |
''
|
Source code in src/gtsom/utils.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
to_dict
to_dict()
Return a plain dict representation of this validator's fingerprints.
The training data X is not stored — only the summary statistics
needed to detect mismatches in subsequent :meth:check calls.
The dtype is stored as a string and cast back to np.dtype on load.
Returns:
| Type | Description |
|---|---|
dict with keys:
|
shape list of int dtype str mean float std float min float max float has_labels bool label_keys np.ndarray of object (str labels) or None label_counts np.ndarray of int64 or None |
Source code in src/gtsom/utils.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
from_dict
classmethod
from_dict(d)
Reconstruct a DataValidator from a dict produced by :meth:to_dict.
Bypasses __init__ so that the stored fingerprint is restored
exactly without requiring the original data X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
DataValidator
|
|
Source code in src/gtsom/utils.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
Embedding
gtsom.embedding.Embedding
Embedding(
coords, adj_metric, dist_metric="geodesic", _shape=None
)
Low-dimensional embedding of SOM prototype positions, including graph topology and pairwise distances.
Stores the output-space coordinates of M prototypes, a sparse adjacency matrix defining their topological connections, and a dense pairwise distance matrix derived from that adjacency.
Attributes:
| Name | Type | Description |
|---|---|---|
coords |
(ndarray, shape(M, dim))
|
Low-dimensional positions of the prototypes. Mutable — can be updated externally (e.g. by a tSNE/UMAP step), followed by a call to compute_topo() to rebuild adjacency and distances. |
dim |
int
|
Dimensionality of the embedding space (2 or 3). Inferred from coords. |
adjacency |
(csr_matrix, shape(M, M))
|
Sparse symmetric adjacency matrix. Entry (i, j) = 1 if prototypes i and j are graph neighbors, 0 otherwise. Populated by compute_topo(). |
adj_metric |
str
|
Algorithm used to construct the adjacency. One of: 'delaunay', 'gabriel', 'grid_rect', 'grid_hex'. |
dist |
np.ndarray, shape (M, M), dtype float32
|
Dense pairwise distance matrix. Populated by compute_topo(). |
dist_metric |
str
|
Distance type used to populate dist. Currently supported: 'geodesic' (unweighted hop-count shortest path). |
M |
int(property)
|
Number of prototypes. |
Base constructor. Stores coords and metric specs, then calls compute_topo() to build adjacency and dist.
Prefer the classmethods (from_delaunay, from_gabriel, from_grid) over calling this directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
(array - like, shape(M, dim))
|
Low-dimensional prototype positions. dim must be 2 or 3. |
required |
adj_metric
|
str
|
Algorithm to use for adjacency construction. |
required |
dist_metric
|
str
|
Distance type for computing dist. |
'geodesic'
|
_shape
|
tuple of int
|
Grid shape — stored internally by from_grid() so that compute_topo() can reconstruct exact grid adjacency. |
None
|
Source code in src/gtsom/embedding.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
M
property
M
Number of prototypes.
dim
property
dim
Dimensionality of the embedding space (2 or 3).
compute_topo
compute_topo()
Recompute adjacency from current coords (using adj_metric), then recompute dist (using dist_metric).
Call this after updating coords externally (e.g. after a tSNE/UMAP coordinate update step). For grid-based embeddings this is called once at construction and rarely thereafter.
Returns:
| Name | Type | Description |
|---|---|---|
self |
Embedding
|
Returns self for method chaining. |
Source code in src/gtsom/embedding.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
update_coords
update_coords(coords)
Replace the embedding coordinates and atomically rebuild topology.
Sets self.coords to the provided array and immediately calls
self.compute_topo() to rebuild self.adjacency and
self.dist from the new positions. Callers do not need to
trigger compute_topo() manually after changing coords.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
(array - like, shape(M, dim))
|
New low-dimensional prototype positions. Must match the current
shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
Embedding
|
Returns self for method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shape of |
Source code in src/gtsom/embedding.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
from_delaunay
classmethod
from_delaunay(coords, dist_metric='geodesic')
Construct an Embedding from the Delaunay triangulation of coords.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
(array - like, shape(M, dim))
|
Low-dimensional prototype positions. dim must be 2 or 3. |
required |
dist_metric
|
str
|
Distance type for computing dist. |
'geodesic'
|
Returns:
| Type | Description |
|---|---|
Embedding
|
|
Source code in src/gtsom/embedding.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
from_gabriel
classmethod
from_gabriel(coords, dist_metric='geodesic')
Construct an Embedding from the Gabriel graph of coords.
The Gabriel graph is a subgraph of the Delaunay triangulation: edge (i, j) is retained only if no other point lies within the open ball whose diameter is the segment from coords[i] to coords[j]. This produces a sparser topology than Delaunay, more closely reflecting local proximity structure, while remaining guaranteed to be connected for any finite point set in general position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
(array - like, shape(M, dim))
|
Low-dimensional prototype positions. dim must be 2 or 3. |
required |
dist_metric
|
str
|
Distance type for computing dist. |
'geodesic'
|
Returns:
| Type | Description |
|---|---|
Embedding
|
|
Source code in src/gtsom/embedding.py
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
from_grid
classmethod
from_grid(shape, kind='hex', dist_metric='geodesic')
Construct an Embedding from a regular grid.
Coordinates are generated analytically from the grid shape and type. For hexagonal grids, adjacency is derived via Delaunay triangulation (which correctly recovers 6-connectivity in 2D and richer inter-layer connectivity in 3D). For rectangular grids, an explicit 8-connected adjacency is constructed directly to avoid the diagonal ambiguity of Delaunay on regular square grids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple of int
|
Grid dimensions. (nrows, ncols) for 2D grids, or (nrows, ncols, ndepth) for 3D grids. |
required |
kind
|
str
|
Grid type: 'hex' for hexagonal, 'rect' for rectangular. |
'hex'
|
dist_metric
|
str
|
Distance type for computing dist. |
'geodesic'
|
Returns:
| Type | Description |
|---|---|
Embedding
|
|
Source code in src/gtsom/embedding.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
to_dict
to_dict()
Return a plain dict representation of this Embedding.
All values are Python/numpy primitives (arrays, sparse matrices,
scalars, or None) — no HDF5 types. Intended for use with
:class:~gtsom.io.GTSOMio, which handles the HDF5 encoding.
Returns:
| Type | Description |
|---|---|
dict with keys:
|
coords np.ndarray (M, dim) adj_metric str dist_metric str _shape list of int or None adjacency scipy.sparse.csr_matrix or None dist np.ndarray (M, M) or None |
Source code in src/gtsom/embedding.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
from_dict
classmethod
from_dict(d)
Reconstruct an Embedding from a dict produced by :meth:to_dict.
Bypasses __init__ (and therefore compute_topo()) so that the
exact saved adjacency and distance matrix are restored rather than
being recomputed from coords.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
Embedding
|
|
Source code in src/gtsom/embedding.py
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
NeighborKernel
gtsom.kernel.NeighborKernel
NeighborKernel(kind='exp', h_min=0.01)
Computes sparse neighborhood activation weights for SOM prototype updates.
At each learning step, the kernel takes the pairwise distance matrix between prototypes (from Embedding.dist) and a per-prototype bandwidth vector rho, and returns a sparse matrix of neighborhood influence weights.
The kernel function is set at construction and applied uniformly via compute(). Per-prototype rho values allow spatially adaptive bandwidths, though in practice a single global rho (broadcast to length M) is typical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
Kernel function to use. Currently supported: 'exp' (exponential decay). Future options: 'gaussian'. |
'exp'
|
h_min
|
float
|
Minimum activation threshold. Weights below this value are set to zero and excluded from the sparse output. Controls the sparsity of nbr_w — lower h_min means broader (denser) neighborhoods. |
0.01
|
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Kernel function identifier. |
h_min |
float
|
Activation threshold. |
Examples:
>>> kernel = NeighborKernel(kind='exp', h_min=0.01)
>>> nbr_w = kernel.compute(embedding.dist, rho=3.0)
>>> nbr_w.shape
(M, M)
Source code in src/gtsom/kernel.py
47 48 49 50 51 52 53 54 55 56 57 58 | |
compute
compute(dist, rho)
Compute sparse neighborhood activation weights.
For each prototype i, computes the activation weight for every other prototype j using the kernel function applied to dist[i, j] and rho[i]. Weights below h_min are zeroed out, and the result is returned as a sparse CSR matrix.
Row i of the returned matrix contains the nonzero activation weights of prototype i's neighborhood. The nonzero column indices give the active neighbor prototypes, making a separate nbr_idx array unnecessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
(ndarray, shape(M, M))
|
Pairwise prototype distance matrix (from Embedding.dist). |
required |
rho
|
float or array-like of shape (M,)
|
Neighborhood bandwidth. A scalar is broadcast to all M prototypes. An array allows per-prototype bandwidths. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
nbr_w |
(csr_matrix, shape(M, M))
|
Sparse matrix of neighborhood activation weights. nbr_w[i] gives the activation weights for prototype i's active neighbors. Self-activation (diagonal) is included. |
Source code in src/gtsom/kernel.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
Visualization
gtsom.vis_tools.vis_embedding_discrete
vis_embedding_discrete(
x,
y,
z=None,
ctab=None,
point_size=2,
point_color="black",
point_size_wts=None,
point_size_wts_trans="identity",
point_shape="o",
graph=None,
edge_size=0.25,
edge_color="antiquewhite3",
xrev=False,
yrev=False,
xlim=None,
ylim=None,
xlab="x",
ylab="y",
title=None,
subtitle=None,
caption=None,
legend_pos="none",
legend_title=None,
legend_nlines=1,
legend_key_size=5,
text_color="black",
show_grid=True,
seed=None,
)
Scatter / embedding plot with a discrete (categorical) color scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Point coordinates. |
required |
y
|
array - like
|
Point coordinates. |
required |
z
|
array - like or None
|
Categorical labels for each point. If None, all points are
drawn in |
None
|
ctab
|
dict or None
|
Label->hex-color mapping (as returned by |
None
|
point_size
|
float
|
Maximum point size. The actual size is scaled by |
2
|
point_color
|
str
|
Fallback color when both z and ctab are None. |
'black'
|
point_size_wts
|
array - like or None
|
Per-point size weights. If None all points get the same size. |
None
|
point_size_wts_trans
|
str
|
Scale transformation applied to size weights (e.g. "identity", "sqrt", "log10"). |
'identity'
|
point_shape
|
str
|
Matplotlib marker string (e.g. "o", "s", "^"). |
'o'
|
graph
|
array - like(N, N) or None
|
Adjacency matrix. When provided, edges are drawn before points. |
None
|
edge_size
|
float
|
Line width for graph edges. |
0.25
|
edge_color
|
str
|
Color for graph edges. |
'antiquewhite3'
|
xrev
|
bool
|
Reverse the x or y axis. |
False
|
yrev
|
bool
|
Reverse the x or y axis. |
False
|
xlim
|
tuple or None
|
Axis limits (min, max). |
None
|
ylim
|
tuple or None
|
Axis limits (min, max). |
None
|
xlab
|
str
|
Axis labels. |
'x'
|
ylab
|
str
|
Axis labels. |
'x'
|
title
|
str or None
|
Plot annotations. |
None
|
subtitle
|
str or None
|
Plot annotations. |
None
|
caption
|
str or None
|
Plot annotations. |
None
|
legend_pos
|
str
|
"none", "right", or "bottom". |
'none'
|
legend_title
|
str or None
|
Legend title. |
None
|
legend_nlines
|
int
|
Number of columns (right legend) or rows (bottom legend). |
1
|
legend_key_size
|
float
|
Override size of legend color keys. |
5
|
text_color
|
str
|
Color for all text elements (passed to |
'black'
|
show_grid
|
bool
|
If False, panel grid lines are removed. |
True
|
seed
|
int or None
|
Random seed for |
None
|
Returns:
| Type | Description |
|---|---|
ggplot
|
|
Source code in src/gtsom/vis_tools.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | |
gtsom.vis_tools.vis_embedding_continuous
vis_embedding_continuous(
x,
y,
z,
cmap="viridis",
point_size=2,
point_size_wts=None,
point_size_wts_trans="identity",
point_shape="o",
graph=None,
edge_size=0.25,
edge_color="antiquewhite3",
xrev=False,
yrev=False,
xlim=None,
ylim=None,
xlab="x",
ylab="y",
title=None,
subtitle=None,
caption=None,
legend_pos="none",
legend_title=None,
text_color="black",
show_grid=True,
)
Scatter / embedding plot with a continuous color scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Point coordinates. |
required |
y
|
array - like
|
Point coordinates. |
required |
z
|
array - like
|
Continuous values mapped to color. |
required |
cmap
|
str
|
Colormap name (any matplotlib-compatible string, e.g. "viridis", "plasma", "magma"). |
'viridis'
|
point_size
|
float
|
Maximum point size. |
2
|
point_size_wts
|
array - like or None
|
Per-point size weights. If None all points get the same size. |
None
|
point_size_wts_trans
|
str
|
Scale transformation for size weights. |
'identity'
|
point_shape
|
str
|
Matplotlib marker string. |
'o'
|
graph
|
array - like(N, N) or None
|
Adjacency matrix for optional edge layer. |
None
|
edge_size
|
float
|
Line width for graph edges. |
0.25
|
edge_color
|
str
|
Color for graph edges. |
'antiquewhite3'
|
xrev
|
bool
|
Reverse x or y axis. |
False
|
yrev
|
bool
|
Reverse x or y axis. |
False
|
xlim
|
tuple or None
|
Axis limits. |
None
|
ylim
|
tuple or None
|
Axis limits. |
None
|
xlab
|
str
|
Axis labels. |
'x'
|
ylab
|
str
|
Axis labels. |
'x'
|
title
|
str or None
|
Plot annotations. |
None
|
subtitle
|
str or None
|
Plot annotations. |
None
|
caption
|
str or None
|
Plot annotations. |
None
|
legend_pos
|
str
|
"none", "right", or "bottom". |
'none'
|
legend_title
|
str or None
|
Colorbar title. |
None
|
text_color
|
str
|
Color for all text elements. |
'black'
|
show_grid
|
bool
|
If False, panel grid lines are removed. |
True
|
Returns:
| Type | Description |
|---|---|
ggplot
|
|
Source code in src/gtsom/vis_tools.py
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 | |
gtsom.vis_tools.build_ctab
build_ctab(labels, seed=None)
Automatically generate a label->color mapping for a set of category labels.
Uses matplotlib's Tab10 palette for the first 10 labels (perceptually well-tuned for categorical data), then extends with distinctipy for any additional labels, ensuring new colors are visually distinct from the Tab10 colors already assigned.
Labels are sorted before color assignment so that the mapping is deterministic and stable across calls with the same label set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
array - like
|
Category labels. Duplicates are ignored; labels are sorted before color assignment. |
required |
seed
|
int or None
|
Random seed passed to distinctipy for reproducibility when more than 10 labels are present. If None, results may vary between calls. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
{label: hex_color_string} |
Raises:
| Type | Description |
|---|---|
ImportError
|
If more than 10 labels are provided and distinctipy is not installed. |
Notes
distinctipy is an optional dependency. Install with: pip install distinctipy
Source code in src/gtsom/vis_tools.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
gtsom.vis_tools.parse_ctab
parse_ctab(labels, colors)
Build a label->color mapping dict, accepting colors as hex strings or as an RGB array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
array - like
|
Category labels. |
required |
colors
|
array - like
|
Either a list of hex strings (e.g. ["#FF0000", "#00FF00"]) or an (N, 3) array of RGB values. RGB values are auto-detected as uint8 (0-255) if any value exceeds 1, otherwise treated as float (0-1). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
{label: hex_color_string} |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are inconsistent or malformed. |
Source code in src/gtsom/vis_tools.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
gtsom.vis_tools.theme_minimal_bold
theme_minimal_bold(text_color='black', **kwargs)
Plotnine equivalent of theme_minimal_bold() from R/VisTools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_color
|
str
|
Color applied to all axis text, titles, and legend labels. |
'black'
|
**kwargs
|
Additional theme() keyword arguments forwarded verbatim, allowing the caller to override or extend any theme element. |
{}
|
Returns:
| Type | Description |
|---|---|
theme
|
A composable theme object; add it to any ggplot with +. |
Source code in src/gtsom/vis_tools.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
DRMetrics
gtsom.dr_metrics.compute_dr_metrics
compute_dr_metrics(
X,
Y,
embed_geodesic_dist=None,
CONN=None,
compute_coranking=True,
)
Compute dimensionality reduction quality metrics for a (high-d, low-d) pair.
Evaluates how faithfully the low-dimensional embedding Y preserves the
structure of the high-dimensional point set X. Designed for use with
SOM prototype vectors and their 2-D output-space coordinates, but
applicable to any matched (high-d, low-d) pair.
Two families of metrics are available:
Co-ranking family (requires pyDRMetrics): measures of neighborhood
preservation at local scales, global scales, and across all scales, plus a
chance-corrected summary (LCMC_AUC) and a trustworthiness summary
(Trust_AUC). Set compute_coranking=False to skip if pyDRMetrics
is not installed.
CONN_WAFL (requires embed_geodesic_dist and CONN): a CONN-weighted measure of
embedding folding — how many embedding hops are needed, on average, to
span each high-d CONN neighborhood. Requires only numpy/scipy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(M, d))
|
High-dimensional coordinates (e.g. SOM prototype vectors |
required |
Y
|
(array - like, shape(M, dim))
|
Low-dimensional coordinates (e.g. SOM embedding coords
|
required |
embed_geodesic_dist
|
(ndarray, shape(M, M))
|
Pairwise geodesic hop-count distances in the embedding graph.
Required for CONN_WAFL. In GTSOM, this is |
None
|
CONN
|
scipy.sparse matrix, shape (M, M)
|
Prototype co-adjacency matrix. Required for CONN_WAFL. In GTSOM,
this is |
None
|
compute_coranking
|
bool
|
Whether to compute co-ranking family metrics via |
True
|
Returns:
| Type | Description |
|---|---|
DRMetricsResult
|
Dataclass with the following fields. Fields that were not computed are None. ================ ========== ============= ======================= Field Range Better Requires ================ ========== ============= ======================= Q_local [0, 1] higher pyDRMetrics Q_global [0, 1] higher pyDRMetrics Q_AUC [0, 1] higher pyDRMetrics LCMC_AUC [0, 1] higher pyDRMetrics Trust_AUC [0, 1] higher pyDRMetrics CONN_WAFL [1, ∞) lower (→ 1) embed_geodesic_dist + CONN CONN_WAFL_SE [0, ∞) lower embed_geodesic_dist + CONN ================ ========== ============= ======================= See :class: |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
ValueError
|
If |
Examples:
Full metrics (requires pyDRMetrics and a CONN matrix):
>>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
... CONN=recaller.CONN)
>>> result.LCMC_AUC
0.812...
>>> result.CONN_WAFL
1.043...
Co-ranking only (no CONN needed):
>>> result = compute_dr_metrics(X=W, Y=coords)
>>> result.Q_local
0.734...
>>> result.Trust_AUC
0.891...
CONN_WAFL only (no pyDRMetrics needed):
>>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
... CONN=recaller.CONN,
... compute_coranking=False)
>>> result.CONN_WAFL
1.043...
Notes
X and Y must have the same number of rows M (one row per point).
No internal scaling is applied — pass pre-processed arrays if needed.
Source code in src/gtsom/dr_metrics.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
gtsom.dr_metrics.DRMetricsResult
dataclass
DRMetricsResult(
Q_local: Optional[float] = None,
Q_global: Optional[float] = None,
Q_AUC: Optional[float] = None,
LCMC_AUC: Optional[float] = None,
Trust_AUC: Optional[float] = None,
CONN_WAFL: Optional[float] = None,
CONN_WAFL_SE: Optional[float] = None,
)
Container for dimensionality reduction quality metrics.
All values are floats. Fields that could not be computed (e.g. CONN_WAFL
when no CONN was provided, or co-ranking metrics when pyDRMetrics is not
installed) are stored as None.
The co-ranking metrics (Q_local through Trust_AUC) are derived from the co-ranking matrix of the (high-d, low-d) point pair. They measure how well the embedding preserves neighborhood structure at various scales. All co-ranking metrics are in [0, 1]; higher is better.
Attributes:
| Name | Type | Description |
|---|---|---|
Q_local |
float or None
|
Local neighborhood preservation, averaged over neighborhood sizes k ≤ kmax, where kmax is the scale at which LCMC is maximized (a data-driven split between local and global scales). Measures whether the nearest neighbors in high-d are also near neighbors in low-d. Higher is better. |
Q_global |
float or None
|
Global neighborhood preservation, averaged over neighborhood sizes k > kmax. Measures whether points that are far apart in high-d are also far apart in low-d. Complements Q_local: an embedding can score well locally but fold or compress at larger scales (or vice versa). Higher is better. |
Q_AUC |
float or None
|
Mean QNN over all neighborhood sizes k — the area under the QNN(k) curve (computed as a simple mean, mirroring pyDRMetrics). Summarises neighborhood preservation across all scales simultaneously. Higher is better. |
LCMC_AUC |
float or None
|
Chance-corrected AUC of the Local Continuity Meta-Criterion (LCMC). LCMC(k) = QNN(k) - k / (M - 1) The subtracted term is the expected QNN under a random embedding, so LCMC(k) measures how much better than chance the embedding is at scale k. LCMC_AUC integrates LCMC over all k and normalizes by the theoretical maximum AUC (integral of 1 - k/K), giving a score in [0, 1] where 1 = perfect preservation and 0 = chance level. This is the most interpretable single scalar summary of embedding quality. |
Trust_AUC |
float or None
|
Trustworthiness, averaged over all neighborhood sizes k. T(k) measures the absence of false neighbors introduced by the embedding: points that appear as k-nearest neighbors in low-d but are not k-nearest neighbors in high-d. T(k) = 1 is perfect (no false neighbors at scale k); T(k) < 1 indicates intrusions. T(k) is typically monotonically decreasing with k (intrusions become inevitable at large k), so no local/global split is applied — the mean over all k is the natural summary. Higher is better. |
CONN_WAFL |
float or None
|
Weighted Average Folding Length, computed over the CONN prototype co-adjacency graph. Measures how many hops in the embedding (low-d geodesic distance) are needed, on average, to span each pair of prototypes that are neighbors in high-d according to CONN: where embed_geodesic_dist[i,j] is the geodesic hop-count distance between prototypes i and j in the embedding graph. CONN_WAFL = 1 is ideal (every high-d CONN-neighbor pair is also a direct embedding neighbor). Values > 1 indicate folding: high-d neighbors are separated in the embedding, requiring multiple hops to connect them. Only computed when embed_geodesic_dist and CONN are provided. |
CONN_WAFL_SE |
float or None
|
Weighted standard error of the CONN_WAFL estimate. None when CONN_WAFL is None. |
as_dict
as_dict()
Return metric values as a plain dict.
Source code in src/gtsom/dr_metrics.py
149 150 151 | |
to_dict
to_dict()
Return a serialization-ready dict of this result.
None values are stored as float('nan') so that the dict
contains only plain Python floats (no None), which HDF5 attrs
can store directly. Reconstructed by :meth:from_dict.
Returns:
| Type | Description |
|---|---|
dict mapping field name → float (nan where the field is None)
|
|
Source code in src/gtsom/dr_metrics.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
from_dict
classmethod
from_dict(d)
Reconstruct a DRMetricsResult from a dict produced by
:meth:to_dict.
nan values are converted back to None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
DRMetricsResult
|
|
Source code in src/gtsom/dr_metrics.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |