Kernel T#
t
#
| CLASS | DESCRIPTION |
|---|---|
TKernelResult |
Result container for t-kernel. |
| FUNCTION | DESCRIPTION |
|---|---|
t_kernel |
Compute T-distribution kernel matrix from distance matrix. |
Classes#
TKernelResult
#
Bases: NamedTuple
Result container for t-kernel.
| ATTRIBUTE | DESCRIPTION |
|---|---|
kernel |
Computed T-distribution kernel matrix.
TYPE:
|
alpha |
Alpha parameter value used in computation.
TYPE:
|
beta |
Beta parameter value used in computation.
TYPE:
|
TKernel(alpha: torch.Tensor = torch.tensor(1.0), beta: torch.Tensor = torch.tensor(1.0), learnable: bool = False, learnable_log: bool = True, normalization: KernelNormalizer | None = None, dtype: torch.dtype = torch.float32)
#
Bases: Kernel
T-distribution kernel for computing pairwise similarity matrices.
Implements the t-distribution kernel function widely used in manifold learning and dimensionality reduction [1]. The kernel provides robust handling of outliers compared to Gaussian kernels due to its heavier tails, making it particularly suitable for datasets with non-uniform density or noise.
The kernel transforms pairwise distances into similarity values using the formula: \(K(d_{kl}) = (1 + \alpha d_{kl}^2)^{-\beta}\) where \(d_{kl}\) is the distance between samples \(k\) and \(l\), \(\alpha > 0\) controls the kernel bandwidth (scale), and \(\beta > 0\) controls the tail heaviness (shape).
| PARAMETER | DESCRIPTION |
|---|---|
alpha
|
Scale parameter \(\alpha > 0\) controlling kernel bandwidth. Higher values produce narrower kernels with faster decay.
TYPE:
|
beta
|
Shape parameter \(\beta > 0\) controlling tail behavior. Higher values produce Gaussian-like behavior with exponential decay, while lower values emphasize heavy tails with polynomial decay.
TYPE:
|
learnable
|
Whether
TYPE:
|
learnable_log
|
Whether to parameterize learnable parameters in log space for numerical stability and to ensure positivity constraints.
TYPE:
|
normalization
|
Kernel normalization to apply after computing the kernel matrix. Use to create transition matrices for spectral methods (e.g., diffusion maps). If None, returns unnormalized kernel values.
TYPE:
|
dtype
|
Data type for internal tensor computations.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
alpha_constant |
Constant alpha value when
TYPE:
|
beta_constant |
Constant beta value when
TYPE:
|
alpha_learnable |
Learnable alpha parameter when
TYPE:
|
beta_learnable |
Learnable beta parameter when
TYPE:
|
Examples:
Basic usage with fixed parameters:
>>> import torch
>>> from spectre.kernel import TKernel
>>> # Compute distance matrix
>>> X = torch.randn(100, 10)
>>> D = torch.cdist(X, X)
>>>
>>> # Create kernel and compute similarity matrix
>>> kernel = TKernel(alpha=1.0, beta=2.0)
>>> K = kernel(D)
>>> K.shape
torch.Size([100, 100])
Using normalization for spectral methods:
>>> from spectre.kernel import TKernel, KernelNormalizer
>>> normalization = KernelNormalizer(norm_type="markov_symmetric")
>>> kernel = TKernel(alpha=1.0, beta=1.5, normalization=normalization)
>>> K_normalized = kernel(D)
>>> # Row sums are approximately 1
>>> K_normalized.sum(dim=1)
tensor([1.0000, 1.0000, ..., 1.0000])
Learnable parameters for neural networks:
>>> kernel = TKernel(alpha=0.5, beta=1.5, learnable=True, learnable_log=True)
>>> K = kernel(D)
>>> loss = K.sum()
>>> loss.backward()
>>> # Gradients are computed for alpha and beta
>>> kernel.alpha_learnable.grad is not None
True
Tensor-valued parameters for adaptive kernels:
>>> # Different alpha for each sample
>>> alpha_tensor = torch.ones(100, 1) * 0.5
>>> kernel = TKernel(alpha=alpha_tensor, beta=1.0, learnable=True)
>>> K = kernel(D)
>>> kernel.alpha_learnable.shape # (100, 1) - per-sample alpha
Comparing different parameter settings:
>>> # Heavy-tailed kernel (robust to outliers)
>>> kernel_heavy = TKernel(alpha=1.0, beta=0.5)
>>> # Gaussian-like kernel (sensitive to outliers)
>>> kernel_light = TKernel(alpha=1.0, beta=5.0)
Notes
- The t-distribution kernel is particularly effective for noisy datasets with outliers due to its heavy-tailed behavior
- Higher \(eta\) values produce Gaussian-like exponential decay:
:math:
K \approx \exp(-\alpha \beta d^2)for large :math:\beta - Lower \(eta\) values emphasize polynomial decay with heavier tails
- The Cauchy kernel is a special case: \(lpha=1, eta=1\)
- Unlike Gaussian kernels, t-distribution kernels maintain non-zero similarity even for large distances, providing better connectivity in sparse data
| METHOD | DESCRIPTION |
|---|---|
forward_step |
Compute unnormalized T-distribution kernel matrix. |
get_kernel_params |
Return current alpha and beta parameters. |
Source code in spectre/kernel/t.py
Functions#
forward_step(D: torch.Tensor, weights: torch.Tensor | None = None, **kwargs) -> torch.Tensor
#
Compute unnormalized T-distribution kernel matrix.
Delegates to t_kernel() function for computation.
| PARAMETER | DESCRIPTION |
|---|---|
D
|
Pairwise distance matrix of shape (n_samples, n_samples) or (n_samples, m_samples).
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
**kwargs
|
Additional keyword arguments passed to the kernel.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
T-distribution kernel (similarity) matrix with same shape as input. |
Source code in spectre/kernel/t.py
get_kernel_params() -> dict[str, torch.Tensor]
#
Return current alpha and beta parameters.
For compact scalar statistics, use get_param_summary() instead.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Dictionary with |
Examples:
Basic usage with constant parameters:
>>> kernel = TKernel(alpha=torch.tensor(1.0), beta=torch.tensor(2.0))
>>> params = kernel.get_kernel_params()
>>> params
{'alpha': tensor(1.), 'beta': tensor(2.)}
Learnable parameters:
>>> kernel = TKernel(
... alpha=torch.tensor(1.0),
... beta=torch.tensor(2.0),
... learnable=True,
... )
>>> params = kernel.get_kernel_params()
>>> "alpha" in params and "beta" in params
True
Logging kernel parameters during training with PyTorch Lightning:
>>> import torch
>>> from spectre.parametric import SpectralMap
>>> from spectre.kernel import TKernel
>>> from spectre.utils.callbacks import MetricsCallback, kernel_params_extractor
>>> from pytorch_lightning import Trainer
>>>
>>> # Create spectral map with learnable T-kernel
>>> kernel = TKernel(
... alpha=torch.tensor(0.5),
... beta=torch.tensor(1.5),
... learnable=True,
... )
>>> spectral_map = SpectralMap(model=my_encoder, kernel_fn=kernel, n_states=3)
>>>
>>> # Create callback to log kernel parameters
>>> callback = MetricsCallback(
... extractors=[kernel_params_extractor],
... log_every_n_epochs=1,
... )
>>>
>>> # Train with callback
>>> trainer = Trainer(callbacks=[callback], max_epochs=100)
>>> trainer.fit(spectral_map, train_dataloader)
>>>
>>> # For scalar parameters, logged metrics will include:
>>> # - alpha: scalar alpha value
>>> # - beta: scalar beta value
>>> # - kernel_type: "TKernel"
>>> # - kernel_learnable: True
>>>
>>> # For vector/matrix parameters, logged metrics will include:
>>> # - alpha_mean, alpha_std, alpha_min, alpha_max
>>> # - beta_mean, beta_std, beta_min, beta_max
>>> # - kernel_type: "TKernel"
>>> # - kernel_learnable: True
Source code in spectre/kernel/t.py
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 | |
Functions#
t_kernel(D: torch.Tensor, alpha: torch.Tensor = torch.tensor(1.0), beta: torch.Tensor = torch.tensor(1.0), dtype: torch.dtype = torch.float32) -> TKernelResult
#
Compute T-distribution kernel matrix from distance matrix.
Core T-distribution kernel computation - single source of truth for parameter logic. Returns the kernel matrix along with the parameter values used in computation.
This is a pure function that computes the unnormalized T-distribution kernel.
For normalized kernels, use the TKernel class with a normalization.
Applies the t-distribution kernel formula: \(K(d) = (1+\alpha d^2)^{-\beta}\).
| PARAMETER | DESCRIPTION |
|---|---|
D
|
Pairwise distance matrix of shape (n_samples, n_samples) or (n_samples, m_samples).
TYPE:
|
alpha
|
Scale parameter :math:
TYPE:
|
beta
|
Shape parameter :math:
TYPE:
|
dtype
|
Data type for computations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TKernelResult
|
NamedTuple containing:
|
Examples:
Basic computation:
>>> import torch
>>> from spectre.kernel import t_kernel
>>> X = torch.randn(50, 5)
>>> D = torch.cdist(X, X)
>>> result = t_kernel(D, alpha=torch.tensor(1.0), beta=torch.tensor(2.0))
>>> result.kernel.shape
torch.Size([50, 50])
>>> result.alpha
tensor(1.)
>>> result.beta
tensor(2.)
Comparing different parameter settings:
>>> # Heavy-tailed kernel (robust to outliers)
>>> result_heavy = t_kernel(D, alpha=torch.tensor(1.0), beta=torch.tensor(0.5))
>>> # Gaussian-like kernel (sensitive to outliers)
>>> result_light = t_kernel(D, alpha=torch.tensor(1.0), beta=torch.tensor(5.0))
Source code in spectre/kernel/t.py
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 | |