Kernel Base#
base
#
| CLASS | DESCRIPTION |
|---|---|
Kernel |
Abstract base class for kernel functions used in spectral methods such as diffusion |
| FUNCTION | DESCRIPTION |
|---|---|
initialize_kernel_fn |
Initialize a kernel from an instance or registry name. |
Classes#
Kernel(learnable: bool = False, learnable_log: bool = True, normalization: KernelNormalizer | NormalizationType | dict | None = None, dtype: torch.dtype = torch.float32)
#
Bases: Module, ABC
Abstract base class for kernel functions used in spectral methods such as diffusion maps or spectral maps.
Provides a unified interface for computing similarity matrices from distance matrices, with support for learnable parameters, automatic differentiation, and various normalization schemes. All kernel implementations should inherit from this class.
| PARAMETER | DESCRIPTION |
|---|---|
learnable
|
Whether kernel parameters should be learnable.
TYPE:
|
learnable_log
|
Whether to parameterize learnable parameters in log space for numerical stability and to enforce positivity constraints.
TYPE:
|
normalization
|
Kernel normalization specification. Multiple formats supported:
TYPE:
|
dtype
|
Data type for internal tensor computations.
TYPE:
|
Examples:
Creating a custom kernel by inheriting from Kernel:
>>> import torch
>>> from spectre.kernel import Kernel
>>> from spectre.pairwise_distance import pairwise_distance_euclidean
>>>
>>> class LinearKernel(Kernel):
... def get_kernel_params(self):
... return {}
...
... def forward_step(self, D, weights=None):
... return 1.0 - D / D.max() # Simple linear decay
>>>
>>> X = torch.randn(10, 3)
>>> D = pairwise_distance_euclidean(X)
>>> kernel = LinearKernel()
>>> K = kernel(D)
Using existing kernel implementations:
>>> from spectre.kernel import GaussianKernel, TKernel
>>> gaussian_kernel = GaussianKernel(bw_method=torch.tensor(1.0))
>>> t_kernel = TKernel(alpha=torch.tensor(1.0), beta=torch.tensor(2.0))
Notes
- Learnable parameters enable end-to-end optimization in neural networks
- The normalize_alpha parameter controls anisotropic scaling behavior
| METHOD | DESCRIPTION |
|---|---|
get_kernel_params |
Return current kernel parameters as dictionary. |
get_param_summary |
Return parameter summary for logging. |
freeze_params |
Freeze kernel parameters to prevent recomputation. |
forward_step |
Compute the kernel matrix. |
forward |
Compute the kernel matrix and apply optional normalization to create |
| ATTRIBUTE | DESCRIPTION |
|---|---|
normalization_type |
Get kernel normalization type.
TYPE:
|
param_info |
Return detailed parameter information.
TYPE:
|
Source code in spectre/kernel/base.py
Attributes#
normalization_type: str
property
#
Get kernel normalization type.
param_info: dict[str, dict]
property
#
Return detailed parameter information.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict]
|
Dictionary with parameter names as keys and metadata dicts with:
|
Examples:
Functions#
get_kernel_params() -> dict[str, torch.Tensor]
abstractmethod
#
Return current kernel parameters as dictionary.
Returns dictionary with parameter names as keys and current values
(after applying _get_param transformation for learnable parameters).
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Dictionary of parameter names to current values. |
Examples:
For GaussianKernel:
>>> kernel = GaussianKernel(bw_method=torch.tensor(1.0))
>>> params = kernel.get_kernel_params()
>>> params
{'bandwidth': tensor([1.0])}
For TKernel:
>>> kernel = TKernel(alpha=torch.tensor(1.0), beta=torch.tensor(2.0))
>>> params = kernel.get_kernel_params()
>>> params
{'alpha': tensor([1.0]), 'beta': tensor([2.0])}
Source code in spectre/kernel/base.py
get_param_summary() -> dict[str, float | dict]
#
Return parameter summary for logging.
Returns scalar values as-is, vector/matrix as statistics.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float | dict]
|
For scalars: |
Examples:
Scalar parameter:
>>> kernel = GaussianKernel(bw_method=torch.tensor(1.5))
>>> summary = kernel.get_param_summary()
>>> summary
{'bandwidth': 1.5}
Vector parameter:
>>> kernel = TKernel(alpha=torch.ones(10, 1), beta=torch.tensor(2.0))
>>> summary = kernel.get_param_summary()
>>> summary
{'alpha': {'mean': 1.0, 'std': 0.0, 'min': 1.0, 'max': 1.0, 'shape': (10, 1)},
'beta': 2.0}
Source code in spectre/kernel/base.py
freeze_params() -> Kernel
#
Freeze kernel parameters to prevent recomputation.
Converts dynamic parameter computation (e.g., bandwidth methods like "median") to constant parameters using current values.
The base implementation is a no-op. Subclasses with dynamic parameters
(e.g., GaussianKernel) override this method to freeze their specific
parameters using cached values from previous forward passes.
| RETURNS | DESCRIPTION |
|---|---|
Kernel
|
Returns self for method chaining. |
Source code in spectre/kernel/base.py
forward_step(D: torch.Tensor, weights: torch.Tensor | None = None, **kwargs) -> torch.Tensor
abstractmethod
#
Compute the kernel matrix.
| PARAMETER | DESCRIPTION |
|---|---|
D
|
Pairwise distance matrix of shape (n_samples, n_samples).
TYPE:
|
weights
|
Weights for each sample.
TYPE:
|
**kwargs
|
Additional keyword arguments passed to the kernel.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Kernel matrix of shape (n_samples, n_samples). |
Source code in spectre/kernel/base.py
forward(D: torch.Tensor, weights: torch.Tensor | None = None, **kwargs) -> torch.Tensor
#
Compute the kernel matrix and apply optional normalization to create transition matrices for spectral methods.
| PARAMETER | DESCRIPTION |
|---|---|
D
|
Pairwise distance matrix of shape (n_samples, n_samples).
TYPE:
|
weights
|
Weights for each sample.
TYPE:
|
**kwargs
|
Additional keyword arguments passed to the kernel.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Kernel matrix of shape (n_samples, n_samples). |
Source code in spectre/kernel/base.py
Functions#
initialize_kernel_fn(kernel_fn: Kernel | str | None, kernel_kwargs: dict[str, Any] | None = None) -> Kernel
#
Initialize a kernel from an instance or registry name.
Arguments
kernel_fn : Kernel | str | None Kernel instance or name of registered kernel. kernel_kwargs : dict[str, Any] | None Keyword arguments passed to kernel constructor (only for string names).
| RETURNS | DESCRIPTION |
|---|---|
Kernel
|
Initialized kernel instance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |