Parametric Spectral Map#
spectral_map
#
| CLASS | DESCRIPTION |
|---|---|
SpectralMap |
Spectral map for dimensionality reduction via eigenvalue optimization. |
Classes#
SpectralMap(*, model: ModelType, kernel_fn: Kernel | str = 'gaussian', kernel_kwargs: dict | None = None, distance_fn: PairwiseDistance | str = 'euclidean', distance_kwargs: dict | None = None, loss_fn: Literal['eigenvalue', 'adaptive_eigenvalue'] = 'eigenvalue', loss_kwargs: dict | None = None, loss_weights: dict[str, float] | None = None, additional_loss: list | dict | None = None, additional_loss_weights: list[float] | dict[str, float] | None = None, optimizer_fn: type[torch.optim.Optimizer] | str | None = None, optimizer_kwargs: dict | None = None, lr_scheduler_fn: Any | str | None = None, lr_scheduler_kwargs: dict | None = None, n_eigen: int = 10, symmetric_eigendecomposition: bool = True, device: Literal['cuda', 'cpu'] = 'cuda', store_loss_context: bool = False)
#
Bases: Parametric
Spectral map for dimensionality reduction via eigenvalue optimization.
Learns low-dimensional representations by optimizing spectral properties of kernel matrices computed in the latent space. By default, the method maximizes the spectral gap between leading eigenvalues to identify metastable states or dominant geometric structures in high-dimensional data.
The optimization objective is based on eigenvalue decomposition of a kernel matrix constructed from neural network embeddings, enabling end-to-end learning of spectral properties.
The spectral gap loss is defined as (loss_fn="eigenvalue" with
reduce="gap"): \(\lambda_{n-1} - \lambda_n\), where \(\lambda\) are the
ordered eigenvalues of the kernel matrix. Larger spectral gaps indicate
better separation between leading eigenvalues.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Neural network architecture for learning spectral embeddings. Can be a single model or dictionary of models. See Parametric for supported model types.
TYPE:
|
kernel_fn
|
Kernel function specification.
Available string options:
TYPE:
|
kernel_kwargs
|
Keyword arguments for kernel instantiation when See kernels for available options.
TYPE:
|
distance_fn
|
Distance metric specification.
Available string options:
TYPE:
|
distance_kwargs
|
Keyword arguments for distance instantiation when
TYPE:
|
loss_fn
|
Loss function specification. Only EigenvalueLoss (
TYPE:
|
loss_kwargs
|
Additional keyword arguments for the loss function.
TYPE:
|
loss_weights
|
Weights for built-in loss components. Keys must match names in
For
Example:
TYPE:
|
additional_loss
|
Additional loss functions to combine with the primary spectral loss.
The total loss becomes a weighted sum of primary and additional losses.
Useful for adding regularization (e.g.,
TYPE:
|
additional_loss_weights
|
Weights for additional loss functions.
TYPE:
|
optimizer_fn
|
Optimizer specification for training.
TYPE:
|
optimizer_kwargs
|
Keyword arguments for optimizer instantiation
(e.g.,
TYPE:
|
lr_scheduler_fn
|
Learning rate scheduler specification.
TYPE:
|
lr_scheduler_kwargs
|
Keyword arguments for scheduler instantiation.
TYPE:
|
n_eigen
|
Number of eigenvalues to compute.
TYPE:
|
symmetric_eigendecomposition
|
Whether to use symmetric eigendecomposition.
TYPE:
|
device
|
Computation device. Falls back to "cpu" if CUDA unavailable.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
DEFAULT_LOSS_WEIGHTS |
Default weights for built-in loss components:
TYPE:
|
kernel_fn |
Kernel function instance.
TYPE:
|
distance_fn |
Distance function instance.
TYPE:
|
loss_fn |
Composite loss function containing spectral loss and any additional losses.
TYPE:
|
eigenvalues |
Most recently computed eigenvalues from forward pass, shape
(
TYPE:
|
Examples:
String-based configuration:
>>> import torch
>>> from spectre.parametric import SpectralMap
>>> from spectre.core import Model
>>>
>>> model = Model(in_features=10, out_features=2, multipliers=[0.5])
>>>
>>> sm = SpectralMap(
... model=model,
... kernel_fn="gaussian",
... kernel_kwargs={"bw_method": "median"},
... distance_fn="euclidean",
... loss_kwargs={"n_eigen": 2, "reduce": "gap"},
... device="cpu",
... )
>>>
>>> X = torch.randn(100, 10)
>>> loss = sm.loss(X)
Object-based configuration:
>>> from spectre.kernel import TKernel
>>> from spectre.pairwise_distance import PairwiseDistanceMahalanobis
>>>
>>> sm = SpectralMap(
... model=model,
... kernel_fn=TKernel(alpha=torch.tensor(1.0), beta=torch.tensor(3.0)),
... distance_fn=PairwiseDistanceMahalanobis(),
... loss_kwargs={"n_eigen": 2, "reduce": "gap"},
... device="cpu",
... )
With custom loss weights and additional losses:
>>> from spectre.loss import OrthogonalLoss, DecorrelationLoss
>>>
>>> sm = SpectralMap(
... model=model,
... kernel_fn="gaussian",
... loss_fn="eigenvalue",
... loss_kwargs={"n_eigen": 2, "reduce": "gap"},
... loss_weights={"loss_eigenvalue": 0.5},
... additional_loss={
... "orthogonal": OrthogonalLoss(),
... "decorrelation": DecorrelationLoss(method="correlation"),
... },
... additional_loss_weights={
... "orthogonal": 0.1,
... "decorrelation": 0.05,
... },
... device="cpu",
... )
>>>
>>> # Total 0.5 * spectral_loss + 0.1 * orthogonal + 0.05 * decorrelation
>>> X = torch.randn(100, 10)
>>> loss = sm.loss(X) # Composite loss value
| METHOD | DESCRIPTION |
|---|---|
training_step |
PyTorch Lightning training step for spectral map optimization. |
compute_loss_context |
Compute inputs needed for spectral loss computation. |
forward_step |
Compute forward pass through network. |
loss |
Compute spectral loss based on kernel matrix eigenvalues in latent |
score_step |
Compute spectral loss for evaluation without training status checks. |
Source code in spectre/parametric/spectral_map.py
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 | |
Functions#
training_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
#
PyTorch Lightning training step for spectral map optimization.
Processes a single training batch by computing spectral loss and logging eigenvalue metrics. Automatically logs loss and eigenvalues to the trainer. When additional losses are provided, logs individual loss components.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Training batch.
TYPE:
|
batch_idx
|
Index of current batch within the epoch.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar spectral loss value for backpropagation. If additional losses are provided, returns weighted sum of all components. |
Source code in spectre/parametric/spectral_map.py
compute_loss_context(X: torch.Tensor, weights: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None]
#
Compute inputs needed for spectral loss computation.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
weights
|
Optional sample weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(z_batch, z_kernel, eigenvalues, eigenvectors) |
Source code in spectre/parametric/spectral_map.py
forward_step(X: torch.Tensor) -> torch.Tensor
#
Compute forward pass through network.
Applies the neural network model to input data to obtain low-dimensional representations in the latent space where kernel matrices are computed.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, out_features)
|
Latent space embeddings. |
Source code in spectre/parametric/spectral_map.py
loss(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Compute spectral loss based on kernel matrix eigenvalues in latent space.
When additional losses are provided, computes a composite loss combining the primary spectral loss with additional regularization terms.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
weights
|
Optional sample weights for weighted kernel computation. Applied during kernel normalization if provided.
TYPE:
|
target
|
Not used for loss computation (unsupervised method).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar loss value. If additional losses are provided, returns weighted sum of all loss components. |
Source code in spectre/parametric/spectral_map.py
score_step(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Compute spectral loss for evaluation without training status checks.
Evaluates the spectral map quality by computing eigenvalue-based loss on the kernel matrix in the latent space without requiring the model to be marked as trained.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data for evaluation.
TYPE:
|
weights
|
Sample weights for weighted kernel computation.
TYPE:
|
target
|
Target tensor for supervised scoring. Can be a tensor of reference targets, e.g., reference eigenvalues.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar spectral loss value (negative indicates better spectral gap). |