Status: Needs Review
This page has not been reviewed for accuracy and completeness. Content may be outdated or contain errors.
Nodes API¶
Complete API documentation for all node classes and implementations.
Overview¶
Nodes are the building blocks of CUVIS.AI pipelines. This page documents all available node implementations organized by functional category.
Anomaly Detection Nodes¶
Statistical and deep learning methods for detecting anomalies in hyperspectral data.
RX Detector¶
rx_detector
¶
RX anomaly detection nodes for hyperspectral imaging.
This module implements the Reed-Xiaoli (RX) anomaly detection algorithm, a widely used statistical method for detecting anomalies in hyperspectral images. The RX algorithm computes squared Mahalanobis distance from the background distribution, treating pixels with large distances as potential anomalies.
The module provides two variants:
-
RXGlobal: Uses global statistics (mean, covariance) estimated from training data. Supports two-phase training: statistical initialization followed by optional gradient-based fine-tuning via unfreeze().
-
RXPerBatch: Computes statistics independently for each batch on-the-fly without requiring initialization. Useful for real-time processing or when training data is unavailable.
Reference: Reed, I. S., & Yu, X. (1990). "Adaptive multiple-band CFAR detection of an optical pattern with unknown spectral distribution." IEEE Transactions on Acoustics, Speech, and Signal Processing, 38(10), 1760-1770.
RXBase
¶
RXGlobal
¶
Bases: RXBase
RX anomaly detector with global background statistics.
Uses global mean (μ) and covariance (Σ) estimated from training data to compute Mahalanobis distance scores. Supports two-phase training: statistical initialization followed by optional gradient-based fine-tuning.
The detector computes anomaly scores as:
RX(x) = (x - μ)ᵀ Σ⁻¹ (x - μ)
where x is a pixel spectrum, μ is the background mean, and Σ is the covariance matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_channels
|
int
|
Number of spectral channels in input data |
required |
eps
|
float
|
Small constant added to covariance diagonal for numerical stability (default: 1e-6) |
1e-06
|
cache_inverse
|
bool
|
If True, precompute and cache Σ⁻¹ for faster inference (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
mu |
Tensor or Parameter
|
Background mean spectrum, shape (C,). Initially a buffer, becomes Parameter after unfreeze() |
cov |
Tensor or Parameter
|
Background covariance matrix, shape (C, C) |
cov_inv |
Tensor or Parameter
|
Cached pseudo-inverse of covariance (if cache_inverse=True) |
_statistically_initialized |
bool
|
Flag indicating whether statistical_initialization() has been called |
Examples:
>>> from cuvis_ai.anomaly.rx_detector import RXGlobal
>>> from cuvis_ai_core.training import StatisticalTrainer
>>>
>>> # Create RX detector
>>> rx = RXGlobal(num_channels=61, eps=1.0e-6)
>>>
>>> # Phase 1: Statistical initialization
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes μ and Σ from training data
>>>
>>> # Inference with frozen statistics
>>> output = rx.forward(data=hyperspectral_cube)
>>> scores = output["scores"] # [B, H, W, 1]
>>>
>>> # Phase 2: Optional gradient-based fine-tuning
>>> rx.unfreeze() # Convert buffers to nn.Parameters
>>> # Now μ and Σ can be updated with gradient descent
See Also
RXPerBatch : Per-batch RX variant without training MinMaxNormalizer : Recommended preprocessing before RX ScoreToLogit : Convert scores to logits for classification docs/tutorials/rx-statistical.md : Complete RX pipeline tutorial
Notes
After statistical_initialization(), mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to trainable nn.Parameters for gradient-based optimization.
Source code in cuvis_ai/anomaly/rx_detector.py
statistical_initialization
¶
Initialize mu and Sigma from data iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/anomaly/rx_detector.py
unfreeze
¶
Convert mu and cov buffers to trainable nn.Parameters.
Call this method after fit() to enable gradient-based optimization of the mean and covariance statistics. They will be converted from buffers to nn.Parameters, allowing gradient updates during training.
Example
rx.fit(input_stream) # Statistical initialization rx.unfreeze() # Enable gradient training
Now RX statistics can be fine-tuned with gradient descent¶
Source code in cuvis_ai/anomaly/rx_detector.py
update
¶
Update streaming statistics with a new batch using Welford's algorithm.
This method incrementally computes mean and covariance from batches of data using Welford's numerically stable online algorithm. Multiple batches can be processed sequentially before calling finalize() to compute final statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_bhwc
|
Tensor
|
Input batch in BHWC format, shape (B, H, W, C) |
required |
Notes
The algorithm maintains running accumulators (_mean, _M2, _n) in float64 for numerical stability. Batches with ≤1 samples are ignored. After update(), call finalize() to compute mu and cov from the accumulated statistics.
Source code in cuvis_ai/anomaly/rx_detector.py
finalize
¶
Compute final mean and covariance from accumulated streaming statistics.
This method converts the running accumulators (_mean, _M2) into the final mean (mu) and covariance (cov) matrices. The covariance is regularized with eps * I for numerical stability, and optionally caches the pseudo-inverse.
Returns:
| Type | Description |
|---|---|
RXGlobal
|
Returns self for method chaining |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 samples were accumulated (insufficient for covariance estimation) |
Notes
After finalization, mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to nn.Parameters for gradient-based training.
Source code in cuvis_ai/anomaly/rx_detector.py
reset
¶
Reset all statistics and accumulators to empty state.
Clears mu, cov, cov_inv, and all streaming accumulators (_mean, _M2, _n). After reset, the detector must be re-initialized via statistical_initialization() before it can be used for inference.
Notes
Use this method when you need to re-initialize the detector with different training data or when switching between different dataset distributions.
Source code in cuvis_ai/anomaly/rx_detector.py
forward
¶
Forward pass computing anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/anomaly/rx_detector.py
RXPerBatch
¶
Bases: RXBase
Computes μ, Σ per image in the batch on the fly; no fit/finalize.
Source code in cuvis_ai/anomaly/rx_detector.py
forward
¶
Forward pass computing per-batch anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/anomaly/rx_detector.py
LAD Detector¶
lad_detector
¶
Laplacian Anomaly Detector (LAD) for hyperspectral anomaly detection.
This module implements the Laplacian Anomaly Detector, a graph-based approach for detecting spectral anomalies in hyperspectral images. LAD constructs a spectral graph using Cauchy similarity weights and computes anomaly scores based on the graph Laplacian.
The LAD algorithm identifies anomalies by measuring how unusual a pixel's spectral signature is within the spectral manifold learned from background data. Unlike RX detectors that assume Gaussian distributions, LAD captures nonlinear manifold structures through graph construction.
Reference: Gu, Y., Liu, Y., & Zhang, Y. (2008). "A selective KPCA algorithm based on high-order statistics for anomaly detection in hyperspectral imagery." IEEE Geoscience and Remote Sensing Letters, 5(1), 43-47.
LADGlobal
¶
Bases: Node
Laplacian Anomaly Detector (global), variant 'C' (Cauchy), port-based.
This is the new cuvis.ai v3 implementation of the LAD detector. It follows the
same mathematical definition as the legacy v2 LADGlobal, but exposes a
port-based interface compatible with CuvisPipeline, StatisticalTrainer,
and GradientTrainer.
Ports
INPUT_SPECS
data : float32, shape (-1, -1, -1, -1)
Input hyperspectral cube in BHWC format.
OUTPUT_SPECS
scores : float32, shape (-1, -1, -1, 1)
Per pixel anomaly scores in BHW1 format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small epsilon value for numerical stability in Laplacian construction. |
1e-8
|
normalize_laplacian
|
bool
|
If True, applies symmetric normalization: L = D^{-½} (D - A) D^{-½}. If False, uses unnormalized Laplacian: L = D - A. |
True
|
use_numpy_laplacian
|
bool
|
If True, constructs the Laplacian matrix using NumPy (float64, 1e-12 eps) for parity with reference implementations. If False, uses pure PyTorch. |
True
|
Training
After statistical initialization via statistical_initialization(), the node can be made trainable
by calling unfreeze(). This converts the mean M and Laplacian L buffers
to trainable nn.Parameter objects, enabling gradient-based fine-tuning.
Example
lad = LADGlobal(num_channels=61) stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule) stat_trainer.fit() # Statistical initialization lad.unfreeze() # Enable gradient training grad_trainer = GradientTrainer(pipeline=pipeline, datamodule=datamodule, ...) grad_trainer.fit() # Gradient-based fine-tuning
Source code in cuvis_ai/anomaly/lad_detector.py
statistical_initialization
¶
Compute global mean M and Laplacian L from a port-based input stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS.
Expected format: |
required |
Source code in cuvis_ai/anomaly/lad_detector.py
update
¶
Update running mean statistics from a BHWC batch.
Source code in cuvis_ai/anomaly/lad_detector.py
finalize
¶
Finalize mean and Laplacian from accumulated statistics.
Source code in cuvis_ai/anomaly/lad_detector.py
reset
¶
Reset all statistics and model parameters to initial state.
Clears the streaming mean accumulator (_mean_run), sample count (_count), global mean (M), and Laplacian matrix (L). After reset, the detector must be re-initialized via statistical_initialization() before inference.
Notes
Use this method to re-initialize the detector with different training data or when switching between different spectral distributions.
Source code in cuvis_ai/anomaly/lad_detector.py
unfreeze
¶
Convert M and L buffers to trainable nn.Parameters.
Source code in cuvis_ai/anomaly/lad_detector.py
forward
¶
Compute LAD anomaly scores for a BHWC cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with key |
Source code in cuvis_ai/anomaly/lad_detector.py
Deep SVDD¶
deep_svdd
¶
Deep SVDD encoder for the port-based cuvis.ai stack.
SpectralNet
¶
Bases: Module
Simple 2-layer MLP used by DeepSVDD to produce latent embeddings.
Source code in cuvis_ai/anomaly/deep_svdd.py
forward
¶
Forward pass through two-layer spectral network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input features [B, C]. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Projected features [B, rep_dim]. |
Source code in cuvis_ai/anomaly/deep_svdd.py
RFFLayer
¶
Bases: Module
Random Fourier feature encoder for RBF kernels.
Source code in cuvis_ai/anomaly/deep_svdd.py
forward
¶
Compute random Fourier features for RBF kernel approximation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input features [B, input_dim]. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Random Fourier features [B, n_features]. |
Notes
Approximates RBF kernel via random Fourier features using: z(x) = sqrt(2/D) * cos(Wx + b) where W ~ N(0, 2*gamma*I).
Source code in cuvis_ai/anomaly/deep_svdd.py
DeepSVDDProjection
¶
DeepSVDDProjection(
*,
in_channels,
rep_dim=32,
hidden=128,
kernel="linear",
n_rff=2048,
gamma=None,
mlp_forward_batch_size=65536,
**kwargs,
)
Bases: Node
Projection head that maps per-pixel features to Deep SVDD embeddings.
Source code in cuvis_ai/anomaly/deep_svdd.py
forward
¶
Project BHWC features into a latent embedding space.
Source code in cuvis_ai/anomaly/deep_svdd.py
ZScoreNormalizerGlobal
¶
Bases: Node
Port-based Deep SVDD z-score normalizer for BHWC cubes.
Source code in cuvis_ai/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for Z-score normalization. |
statistical_initialization
¶
Estimate per-band z-score statistics from the provided stream.
Source code in cuvis_ai/anomaly/deep_svdd.py
forward
¶
Apply per-channel Z-score normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input feature tensor [B, H, W, C]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "normalized" key containing Z-score normalized data [B, H, W, C]. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If input channel count doesn't match initialized num_channels. |
Source code in cuvis_ai/anomaly/deep_svdd.py
DeepSVDDScores
¶
Bases: Node
Convert Deep SVDD embeddings + center vector into anomaly scores.
forward
¶
Compute anomaly scores as squared distance from center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D] from projection network. |
required |
center
|
Tensor
|
Center vector [D] from DeepSVDDCenterTracker. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing squared distances [B, H, W, 1]. |
Source code in cuvis_ai/anomaly/deep_svdd.py
DeepSVDDCenterTracker
¶
Bases: Node
Track and expose Deep SVDD center statistics with optional logging.
Source code in cuvis_ai/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for center tracking initialization. |
statistical_initialization
¶
Initialize the Deep SVDD center from training embeddings.
Computes the mean embedding across all training samples to initialize the hypersphere center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with embeddings [B, H, W, D]. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no embeddings are received from the input stream. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/anomaly/deep_svdd.py
forward
¶
Track and output the Deep SVDD center with exponential moving average.
Updates the center using EMA during training (and optionally during eval), then outputs the current center and center norm metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D]. |
required |
context
|
Context
|
Execution context determining whether to update center. |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with: - "center" : torch.Tensor [D] - Current tracked center - "metrics" : list[Metric] - Center norm metric |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/anomaly/deep_svdd.py
Binary Decision Nodes¶
Nodes that convert anomaly scores into binary decisions (anomaly/normal).
Binary Decider¶
binary_decider
¶
Binary decision nodes for thresholding anomaly scores and logits.
This module provides threshold-based decision nodes that convert continuous anomaly scores or logits into binary decisions (anomaly/normal). Two strategies are available:
- BinaryDecider: Fixed threshold applied globally to sigmoid-transformed logits
- QuantileBinaryDecider: Adaptive per-batch thresholding using quantile statistics
Decision nodes are typically placed at the end of anomaly detection pipelines to convert detector outputs into actionable binary masks for visualization or evaluation.
BinaryDecider
¶
Bases: BinaryDecider
Simple decider node using a static threshold to classify data.
Accepts logits as input, applies sigmoid transformation to convert to probabilities [0, 1], then applies threshold to produce binary decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
The threshold to use for classification after sigmoid. Values >= threshold are classified as anomalies (True). Default: 0.5 |
0.5
|
Examples:
>>> from cuvis_ai.deciders.binary_decider import BinaryDecider
>>> import torch
>>>
>>> # Create decider with default threshold
>>> decider = BinaryDecider(threshold=0.5)
>>>
>>> # Apply to RX anomaly logits
>>> logits = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=logits)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Use in pipeline
>>> pipeline.connect(
... (logit_head.logits, decider.logits),
... (decider.decisions, visualizer.mask),
... )
See Also
QuantileBinaryDecider : Adaptive per-batch thresholding ScoreToLogit : Convert scores to logits before decisioning
Source code in cuvis_ai/deciders/binary_decider.py
forward
¶
Apply sigmoid and threshold-based decisioning on channels-last data.
Args: logits: Tensor shaped (B, H, W, C) containing logits.
Returns: Dictionary with "decisions" key containing (B, H, W, 1) decision mask.
Source code in cuvis_ai/deciders/binary_decider.py
QuantileBinaryDecider
¶
Bases: BinaryDecider
Quantile-based thresholding node operating on BHWC logits or scores.
This decider computes a tensor-valued threshold per batch item using the requested quantile over one or more non-batch dimensions, then produces a binary mask where values greater than or equal to that threshold are marked as anomalies. Useful for adaptive thresholding when score distributions vary across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantile
|
float
|
Quantile in the closed interval [0, 1] used for the threshold computation (default: 0.995). Higher values (e.g., 0.99, 0.995) are typical for anomaly detection to capture rare events. |
0.995
|
reduce_dims
|
Sequence[int] | None
|
Axes (relative to the input tensor) over which to compute the quantile.
When |
None
|
Examples:
>>> from cuvis_ai.deciders.binary_decider import QuantileBinaryDecider
>>> import torch
>>>
>>> # Create quantile-based decider (99.5th percentile)
>>> decider = QuantileBinaryDecider(quantile=0.995)
>>>
>>> # Apply to anomaly scores
>>> scores = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=scores)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Per-channel thresholding (reduce H, W only)
>>> decider_perchannel = QuantileBinaryDecider(
... quantile=0.99,
... reduce_dims=[1, 2], # Compute threshold per channel
... )
See Also
BinaryDecider : Fixed threshold decisioning
Source code in cuvis_ai/deciders/binary_decider.py
forward
¶
Apply quantile-based thresholding to produce binary decisions.
Computes per-batch thresholds using the specified quantile over reduce_dims, then classifies values >= threshold as anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Input logits or anomaly scores, shape (B, H, W, C) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary containing: - "decisions" : Tensor Binary decision mask, shape (B, H, W, 1) |
Source code in cuvis_ai/deciders/binary_decider.py
Two-Stage Decider¶
two_stage_decider
¶
Two-Stage Binary Decision Module.
This module provides a two-stage binary decision node that first applies an image-level anomaly gate based on top-k statistics, then applies pixel-level quantile thresholding only for images that pass the gate.
This approach reduces false positives by filtering out images with low overall anomaly scores before applying pixel-level decisions.
See Also
cuvis_ai.deciders.binary_decider : Simple threshold-based binary decisions
TwoStageBinaryDecider
¶
TwoStageBinaryDecider(
image_threshold=0.5,
top_k_fraction=0.001,
quantile=0.995,
reduce_dims=None,
**kwargs,
)
Bases: BinaryDecider
Two-stage binary decider: image-level gate + pixel quantile mask.
Source code in cuvis_ai/deciders/two_stage_decider.py
forward
¶
Apply two-stage binary decision: image-level gate + pixel quantile.
Stage 1: Compute image-level anomaly score from top-k pixel scores. If below threshold, return blank mask (no anomalies).
Stage 2: For images passing the gate, apply pixel-level quantile thresholding to create binary anomaly mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Anomaly scores [B, H, W, C] or [B, H, W, 1]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "decisions" key containing binary masks [B, H, W, 1]. |
Notes
The image-level score is computed as the mean of the top-k% highest pixel scores. For multi-channel inputs, the max across channels is used for each pixel.
Source code in cuvis_ai/deciders/two_stage_decider.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 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 159 160 161 162 163 164 165 166 167 168 169 170 | |
Data & Preprocessing Nodes¶
Nodes for data loading, normalization, and preprocessing.
Data Loader¶
data
¶
Data loading nodes for hyperspectral anomaly detection pipelines.
This module provides specialized data nodes that convert multi-class segmentation datasets into binary anomaly detection tasks. Data nodes handle type conversions, label mapping, and format transformations required for pipeline processing.
LentilsAnomalyDataNode
¶
Bases: Node
Data node for Lentils anomaly detection dataset with binary label mapping.
Converts multi-class Lentils segmentation data to binary anomaly detection format. Maps specified class IDs to normal (0) or anomaly (1) labels, and handles type conversions from uint16 to float32 for hyperspectral cubes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normal_class_ids
|
list[int]
|
List of class IDs to treat as normal background (e.g., [0, 1] for unlabeled and black lentils) |
required |
anomaly_class_ids
|
list[int] | None
|
List of class IDs to treat as anomalies. If None, all classes not in normal_class_ids are treated as anomalies (default: None) |
None
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
_binary_mapper |
BinaryAnomalyLabelMapper
|
Internal label mapper for converting multi-class to binary masks |
Examples:
>>> from cuvis_ai.node.data import LentilsAnomalyDataNode
>>> from cuvis_ai_core.data.datasets import SingleCu3sDataModule
>>>
>>> # Create datamodule for Lentils dataset
>>> datamodule = SingleCu3sDataModule(
... data_dir="data/lentils",
... batch_size=4,
... )
>>>
>>> # Create data node with normal class specification
>>> data_node = LentilsAnomalyDataNode(
... normal_class_ids=[0, 1], # Unlabeled and black lentils are normal
... )
>>>
>>> # Use in pipeline
>>> pipeline.add_node(data_node)
>>> pipeline.connect(
... (data_node.cube, normalizer.data),
... (data_node.mask, metrics.targets),
... )
See Also
BinaryAnomalyLabelMapper : Label mapping utility used internally SingleCu3sDataModule : DataModule for loading CU3S hyperspectral data docs/tutorials/rx-statistical.md : Complete example with LentilsAnomalyDataNode
Notes
The node performs the following transformations: - Converts hyperspectral cube from uint16 to float32 - Maps multi-class mask [B, H, W] to binary mask [B, H, W, 1] - Extracts wavelengths from first batch element (assumes consistent wavelengths)
Source code in cuvis_ai/node/data.py
forward
¶
Process hyperspectral cube and convert labels to binary anomaly format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube, shape (B, H, W, C), dtype uint16 |
required |
mask
|
Tensor | None
|
Multi-class segmentation mask, shape (B, H, W), dtype int32. If None, only cube is returned (default: None) |
None
|
wavelengths
|
Tensor | None
|
Wavelengths for each channel, shape (B, C), dtype int32. If None, wavelengths are not included in output (default: None) |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor | ndarray]
|
Dictionary containing: - "cube" : torch.Tensor Converted hyperspectral cube, shape (B, H, W, C), dtype float32 - "mask" : torch.Tensor (optional) Binary anomaly mask, shape (B, H, W, 1), dtype bool. Only included if input mask is provided. - "wavelengths" : np.ndarray (optional) Wavelength array, shape (C,), dtype int32. Only included if input wavelengths are provided. |
Source code in cuvis_ai/node/data.py
Normalization¶
normalization
¶
Differentiable normalization nodes for BHWC hyperspectral data.
This module provides a collection of normalization nodes designed for hyperspectral imaging pipelines. All normalizers operate on BHWC format ([batch, height, width, channels]) and maintain gradient flow for end-to-end training.
Normalization strategies:
- MinMaxNormalizer: Scales data to [0, 1] range using min-max statistics
- ZScoreNormalizer: Standardizes data to zero mean and unit variance
- SigmoidNormalizer: Applies sigmoid transformation with median centering
- PerPixelUnitNorm: L2 normalization per pixel across channels
- IdentityNormalizer: No-op passthrough for testing or baseline comparisons
- SigmoidTransform: General-purpose sigmoid for logits→probabilities
Why Normalize?
Normalization is critical for stable anomaly detection and deep learning:
- Stable covariance estimation: RX detectors require well-conditioned covariance matrices
- Gradient stability: Prevents exploding/vanishing gradients during training
- Comparable scales: Ensures different spectral ranges contribute equally
- Faster convergence: Accelerates gradient-based optimization
BHWC Format Requirement
All normalizers expect BHWC input format. For HWC tensors, add batch dimension:
hwc_tensor = torch.randn(256, 256, 61) # [H, W, C] bhwc_tensor = hwc_tensor.unsqueeze(0) # [1, H, W, C]
IdentityNormalizer
¶
MinMaxNormalizer
¶
Bases: _ScoreNormalizerBase
Min-max normalization per sample and channel (keeps gradients).
Scales data to [0, 1] range using (x - min) / (max - min) transformation. Can operate in two modes:
- Per-sample normalization (use_running_stats=False): min/max computed per batch
- Global normalization (use_running_stats=True): uses running statistics from statistical initialization
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small constant for numerical stability, prevents division by zero (default: 1e-6) |
1e-06
|
use_running_stats
|
bool
|
If True, use global min/max from statistical_initialization(). If False, compute min/max per batch during forward pass (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
running_min |
Tensor
|
Global minimum value computed during statistical initialization |
running_max |
Tensor
|
Global maximum value computed during statistical initialization |
Examples:
>>> from cuvis_ai.node.normalization import MinMaxNormalizer
>>> from cuvis_ai_core.training import StatisticalTrainer
>>> import torch
>>>
>>> # Mode 1: Global normalization with statistical initialization
>>> normalizer = MinMaxNormalizer(eps=1.0e-6, use_running_stats=True)
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes global min/max from training data
>>>
>>> # Inference uses global statistics
>>> output = normalizer.forward(data=hyperspectral_cube)
>>> normalized = output["normalized"] # [B, H, W, C], values in [0, 1]
>>>
>>> # Mode 2: Per-sample normalization (no initialization required)
>>> normalizer_local = MinMaxNormalizer(use_running_stats=False)
>>> output = normalizer_local.forward(data=hyperspectral_cube)
>>> # Each sample normalized independently using its own min/max
See Also
ZScoreNormalizer : Z-score standardization SigmoidNormalizer : Sigmoid-based normalization docs/tutorials/rx-statistical.md : RX pipeline with MinMaxNormalizer
Notes
Global normalization (use_running_stats=True) is recommended for RX detectors to ensure consistent scaling between training and inference. Per-sample normalization can be useful for real-time processing when training data is unavailable.
Source code in cuvis_ai/node/normalization.py
statistical_initialization
¶
Compute global min/max from data iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is the scores/data |
required |
Source code in cuvis_ai/node/normalization.py
SigmoidNormalizer
¶
Bases: _ScoreNormalizerBase
Median-centered sigmoid squashing per sample and channel.
Applies sigmoid transformation centered at the median with standard deviation scaling:
sigmoid((x - median) / std)
Produces values in [0, 1] range with median mapped to 0.5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
std_floor
|
float
|
Minimum standard deviation threshold to prevent division by zero (default: 1e-6) |
1e-06
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Examples:
>>> from cuvis_ai.node.normalization import SigmoidNormalizer
>>> import torch
>>>
>>> # Create sigmoid normalizer
>>> normalizer = SigmoidNormalizer(std_floor=1.0e-6)
>>>
>>> # Apply to hyperspectral data
>>> data = torch.randn(4, 256, 256, 61) # [B, H, W, C]
>>> output = normalizer.forward(data=data)
>>> normalized = output["normalized"] # [4, 256, 256, 61], values in [0, 1]
See Also
MinMaxNormalizer : Min-max scaling to [0, 1] ZScoreNormalizer : Z-score standardization
Notes
Sigmoid normalization is robust to outliers because extreme values are squashed asymptotically to 0 or 1. This makes it suitable for data with heavy-tailed distributions or sporadic anomalies.
Source code in cuvis_ai/node/normalization.py
ZScoreNormalizer
¶
Bases: _ScoreNormalizerBase
Z-score (standardization) normalization along specified dimensions.
Computes: (x - mean) / (std + eps) along specified dims. Per-sample normalization with no statistical initialization required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
list[int]
|
Dimensions to compute statistics over (default: [1,2] for H,W in BHWC format) |
None
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
keepdim
|
bool
|
Whether to keep reduced dimensions (default: True) |
True
|
Examples:
>>> # Normalize over spatial dimensions (H, W)
>>> zscore = ZScoreNormalizer(dims=[1, 2])
>>>
>>> # Normalize over all spatial and channel dimensions
>>> zscore_all = ZScoreNormalizer(dims=[1, 2, 3])
Source code in cuvis_ai/node/normalization.py
SigmoidTransform
¶
Bases: Node
Applies sigmoid transformation to convert logits to probabilities [0,1].
General-purpose sigmoid node for converting raw scores/logits to probability space. Useful for visualization or downstream nodes that expect bounded [0,1] values.
Examples:
>>> sigmoid = SigmoidTransform()
>>> # Route logits to both loss (raw) and visualization (sigmoid)
>>> graph.connect(
... (rx.scores, loss_node.predictions), # Raw logits to loss
... (rx.scores, sigmoid.data), # Logits to sigmoid
... (sigmoid.transformed, viz.scores), # Probabilities to viz
... )
Source code in cuvis_ai/node/normalization.py
forward
¶
Apply sigmoid transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "transformed" key containing sigmoid output |
Source code in cuvis_ai/node/normalization.py
PerPixelUnitNorm
¶
Bases: _ScoreNormalizerBase
Per-pixel mean-centering and L2 normalization across channels.
Source code in cuvis_ai/node/normalization.py
Preprocessors¶
preprocessors
¶
Preprocessing Nodes.
This module provides nodes for preprocessing hyperspectral data, including wavelength-based band selection and filtering. These nodes help reduce dimensionality and focus analysis on specific spectral regions of interest.
See Also
cuvis_ai.node.band_selection : Advanced band selection methods cuvis_ai.node.normalization : Normalization and standardization nodes
BandpassByWavelength
¶
Bases: Node
Select channels by wavelength interval from BHWC tensors.
This node filters hyperspectral data by keeping only channels within a specified wavelength range. Wavelengths must be provided via the input port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_wavelength_nm
|
float
|
Minimum wavelength (inclusive) to keep, in nanometers |
required |
max_wavelength_nm
|
float | None
|
Maximum wavelength (inclusive) to keep. If None, selects all wavelengths
|
None
|
Examples:
>>> # Create bandpass node
>>> bandpass = BandpassByWavelength(
... min_wavelength_nm=500.0,
... max_wavelength_nm=700.0,
... )
>>> # Filter cube in BHWC format with wavelengths from input port
>>> wavelengths_tensor = torch.from_numpy(wavelengths).float()
>>> filtered = bandpass.forward(data=cube_bhwc, wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # For single HWC images, add a batch dimension first:
>>> # filtered = bandpass.forward(data=cube_hwc.unsqueeze(0), wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # Use with wavelengths from upstream node
>>> pipeline.connect(
... (data_node.outputs.cube, bandpass.data),
... (data_node.outputs.wavelengths, bandpass.wavelengths),
... )
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Filter cube by wavelength range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelengths tensor [C] in nanometers. |
required |
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "filtered" key containing filtered cube [B, H, W, C_filtered] |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no channels are selected by the provided wavelength range |
Source code in cuvis_ai/node/preprocessors.py
Conversion¶
conversion
¶
RX Logit Head for Anomaly Detection
This module provides a trainable head that converts RX anomaly scores into logits for binary anomaly classification. It can be trained end-to-end with binary cross-entropy loss.
ScoreToLogit
¶
Bases: Node
Trainable head that converts RX scores to anomaly logits.
This node takes RX anomaly scores (typically Mahalanobis distances) and applies a learned affine transformation to produce logits suitable for binary classification with BCEWithLogitsLoss.
The transformation is: logit = scale * (score - bias)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_scale
|
float
|
Initial value for the scale parameter |
1.0
|
init_bias
|
float
|
Initial value for the bias parameter (threshold) |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
scale |
Parameter or Tensor
|
Scale factor applied to scores |
bias |
Parameter or Tensor
|
Bias (threshold) subtracted from scores before scaling |
Examples:
>>> # After RX detector
>>> rx = RXGlobal(eps=1e-6)
>>> logit_head = ScoreToLogit(init_scale=1.0, init_bias=5.0)
>>> logit_head.unfreeze() # Enable gradient training
>>> graph.connect(rx.scores, logit_head.scores)
Source code in cuvis_ai/node/conversion.py
unfreeze
¶
Convert scale and bias buffers to trainable nn.Parameters.
Call this method to enable gradient-based optimization of the scale and bias parameters. They will be converted from buffers to nn.Parameters, allowing gradient updates during training.
Example
logit_head = ScoreToLogit(init_scale=1.0, init_bias=5.0) logit_head.unfreeze() # Enable gradient training
Now scale and bias can be optimized¶
Source code in cuvis_ai/node/conversion.py
statistical_initialization
¶
Initialize bias from statistics of RX scores using streaming approach.
Uses Welford's algorithm for numerically stable online computation of mean and standard deviation, similar to RXGlobal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"scores": tensor} where tensor is the RX scores |
required |
Source code in cuvis_ai/node/conversion.py
update
¶
Update running statistics with a batch of scores.
Uses Welford's online algorithm for numerically stable computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Batch of RX scores in BHWC format |
required |
Source code in cuvis_ai/node/conversion.py
finalize
¶
Finalize statistics and set bias to mean + 2*std.
This threshold (mean + 2*std) is a common heuristic for anomaly detection, capturing ~95% of normal data under Gaussian assumption.
Source code in cuvis_ai/node/conversion.py
reset
¶
Reset all statistics and accumulators.
Source code in cuvis_ai/node/conversion.py
forward
¶
Transform RX scores to logits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Input RX scores with shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "logits" key containing transformed scores |
Source code in cuvis_ai/node/conversion.py
get_threshold
¶
Get the current anomaly threshold (bias value).
Returns:
| Type | Description |
|---|---|
float
|
Current threshold value |
set_threshold
¶
Set the anomaly threshold (bias value).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
New threshold value |
required |
predict_anomalies
¶
Convert logits to binary anomaly predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits from forward pass, shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Binary predictions (0=normal, 1=anomaly), shape (B, H, W, 1) |
Source code in cuvis_ai/node/conversion.py
Channel & Band Selection Nodes¶
Nodes for selecting and transforming spectral channels.
Band Selection¶
band_selection
¶
Band selection nodes for HSI to RGB conversion.
This module provides port-based nodes for selecting spectral bands from hyperspectral cubes and composing RGB images for downstream processing (e.g., with AdaCLIP).
BandSelectorBase
¶
Bases: Node
Base class for hyperspectral band selection strategies.
This base class defines the common input/output ports for band selection nodes.
Subclasses should implement the forward() method to perform specific
band selection strategies.
Ports
INPUT_SPECS
cube : float32, shape (-1, -1, -1, -1)
Hyperspectral cube in BHWC format.
wavelengths : float32, shape (-1,)
Wavelength array in nanometers.
OUTPUT_SPECS
rgb_image : float32, shape (-1, -1, -1, 3)
Composed RGB image in BHWC format (0-1 range).
band_info : dict
Metadata about selected bands.
BaselineFalseRGBSelector
¶
Bases: BandSelectorBase
Fixed wavelength band selection (e.g., 650, 550, 450 nm).
Selects bands nearest to the specified target wavelengths for R, G, B channels. This is the simplest band selection strategy that produces "true color-ish" images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_wavelengths
|
tuple[float, float, float]
|
Target wavelengths for R, G, B channels in nanometers. Default: (650.0, 550.0, 450.0) |
(650.0, 550.0, 450.0)
|
Source code in cuvis_ai/node/band_selection.py
forward
¶
Select bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/band_selection.py
HighContrastBandSelector
¶
Bases: BandSelectorBase
Data-driven band selection using spatial variance + Laplacian energy.
For each wavelength window, selects the band with the highest score based on: score = variance + alpha * Laplacian_energy
This produces "high contrast" images that may work better for visual anomaly detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows
|
Sequence[tuple[float, float]]
|
Wavelength windows for Blue, Green, Red channels. Default: ((440, 500), (500, 580), (610, 700)) for visible spectrum. |
((440, 500), (500, 580), (610, 700))
|
alpha
|
float
|
Weight for Laplacian energy term. Default: 0.1 |
0.1
|
Source code in cuvis_ai/node/band_selection.py
forward
¶
Select high-contrast bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/band_selection.py
CIRFalseColorSelector
¶
Bases: BandSelectorBase
Color Infrared (CIR) false color composition.
Maps NIR to Red, Red to Green, Green to Blue for false-color composites. This is useful for highlighting vegetation and certain anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nir_nm
|
float
|
Near-infrared wavelength in nm. Default: 860.0 |
860.0
|
red_nm
|
float
|
Red wavelength in nm. Default: 670.0 |
670.0
|
green_nm
|
float
|
Green wavelength in nm. Default: 560.0 |
560.0
|
Source code in cuvis_ai/node/band_selection.py
forward
¶
Select CIR bands and compose false-color image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/band_selection.py
SupervisedBandSelectorBase
¶
SupervisedBandSelectorBase(
num_spectral_bands,
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: BandSelectorBase
Base class for supervised band selection strategies.
This class adds an optional mask input port and implements common
logic for statistical initialization via :meth:fit.
The mask is assumed to be binary (0/1), where 1 denotes the positive class (e.g. stone) and 0 denotes the negative class (e.g. lentil/background).
Source code in cuvis_ai/node/band_selection.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for supervised band selectors. |
SupervisedCIRBandSelector
¶
SupervisedCIRBandSelector(
windows=(
(840.0, 910.0),
(650.0, 720.0),
(500.0, 570.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedBandSelectorBase
Supervised CIR/NIR band selection with window constraints.
Windows are typically set to: - NIR: 840-910 nm - Red: 650-720 nm - Green: 500-570 nm
The selector chooses one band per window using a supervised score (Fisher + AUC + MI) with an mRMR-style redundancy penalty.
Source code in cuvis_ai/node/band_selection.py
statistical_initialization
¶
Initialize band selection using supervised scoring with CIR windows.
Computes Fisher, AUC, and MI scores for each band, applies mRMR selection within CIR-specific wavelength windows, and stores the 3 selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with cube, mask, and wavelengths. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mRMR selection doesn't return exactly 3 bands. |
Source code in cuvis_ai/node/band_selection.py
forward
¶
Generate false-color RGB from selected CIR bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
ndarray
|
Wavelengths for each channel [C]. |
required |
mask
|
Tensor
|
Ground truth mask (unused in forward, required for initialization). |
None
|
context
|
Context
|
Pipeline execution context (unused). |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info" metadata. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been statistically initialized. |
Source code in cuvis_ai/node/band_selection.py
SupervisedWindowedFalseRGBSelector
¶
SupervisedWindowedFalseRGBSelector(
windows=(
(440.0, 500.0),
(500.0, 580.0),
(610.0, 700.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedBandSelectorBase
Supervised band selection constrained to visible RGB windows.
Similar to :class:HighContrastBandSelector, but uses label-driven scores.
Default windows:
- Blue: 440–500 nm
- Green: 500–580 nm
- Red: 610–700 nm
Source code in cuvis_ai/node/band_selection.py
statistical_initialization
¶
Initialize band selection using supervised scoring with RGB windows.
Computes Fisher, AUC, and MI scores for each band, applies mRMR selection within RGB wavelength windows (blue/green/red), and stores the 3 selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with cube, mask, and wavelengths. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mRMR selection doesn't return exactly 3 bands. |
Source code in cuvis_ai/node/band_selection.py
forward
¶
Generate false-color RGB from selected windowed bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
ndarray
|
Wavelengths for each channel [C]. |
required |
mask
|
Tensor
|
Ground truth mask (unused in forward, required for initialization). |
None
|
context
|
Context
|
Pipeline execution context (unused). |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info" metadata. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been statistically initialized. |
Source code in cuvis_ai/node/band_selection.py
SupervisedFullSpectrumBandSelector
¶
Bases: SupervisedBandSelectorBase
Supervised selection without window constraints.
Picks the top-3 discriminative bands globally with an mRMR-style redundancy penalty applied over the full spectrum.
Source code in cuvis_ai/node/band_selection.py
statistical_initialization
¶
Initialize band selection using supervised scoring across full spectrum.
Computes Fisher, AUC, and MI scores for each band, applies mRMR selection globally without wavelength window constraints, and stores the 3 selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with cube, mask, and wavelengths. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mRMR selection doesn't return exactly 3 bands. |
Source code in cuvis_ai/node/band_selection.py
forward
¶
Generate false-color RGB from globally selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
ndarray
|
Wavelengths for each channel [C]. |
required |
mask
|
Tensor
|
Ground truth mask (unused in forward, required for initialization). |
None
|
context
|
Context
|
Pipeline execution context (unused). |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info" metadata. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been statistically initialized. |
Source code in cuvis_ai/node/band_selection.py
Channel Mixer¶
channel_mixer
¶
Learnable channel mixer node for DRCNN-style spectral data reduction.
This module implements a learnable channel mixer based on the Data Reduction CNN (DRCNN) approach from Zeegers et al. (2020). The mixer performs spectral pixel-wise 1x1 convolutions to reduce hyperspectral data to a smaller number of channels (e.g., 61 → 3 for RGB compatibility).
Reference: Zeegers et al., "Task-Driven Learned Hyperspectral Data Reduction Using End-to-End Supervised Deep Learning," J. Imaging 6(12):132, 2020.
LearnableChannelMixer
¶
LearnableChannelMixer(
input_channels,
output_channels,
leaky_relu_negative_slope=0.01,
use_bias=True,
use_activation=True,
normalize_output=True,
init_method="xavier",
eps=1e-06,
reduction_scheme=None,
**kwargs,
)
Bases: Node
Learnable channel mixer for hyperspectral data reduction (DRCNN-style).
This node implements a learnable linear combination layer that reduces the number of spectral channels through spectral pixel-wise 1x1 convolutions. Based on the DRCNN approach, it uses: - 1x1 convolution (linear combination across spectral dimension) - Leaky ReLU activation (a=0.01) - Bias parameters - Optional PCA-based initialization
The mixer is designed to be trained end-to-end with a downstream model (e.g., AdaClip) while keeping the downstream model frozen. This allows the mixer to learn optimal spectral combinations for the specific task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube) |
required |
output_channels
|
int
|
Number of output channels (e.g., 3 for RGB compatibility) |
required |
leaky_relu_negative_slope
|
float
|
Negative slope for Leaky ReLU activation (default: 0.01, as per DRCNN paper) |
0.01
|
use_bias
|
bool
|
Whether to use bias parameters (default: True, as per DRCNN paper) |
True
|
use_activation
|
bool
|
Whether to apply Leaky ReLU activation (default: True, as per DRCNN paper) |
True
|
normalize_output
|
bool
|
Whether to apply per-channel min-max normalization to [0, 1] range (default: True). This matches the behavior of band selectors and ensures compatibility with AdaClip. When True, each output channel is normalized independently using per-batch statistics. |
True
|
init_method
|
('xavier', 'kaiming', 'pca', 'zeros')
|
Weight initialization method (default: "xavier") - "xavier": Xavier/Glorot uniform initialization - "kaiming": Kaiming/He uniform initialization - "pca": Initialize from PCA components (requires statistical_initialization) - "zeros": Zero initialization (weights and bias start at zero) |
"xavier"
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
reduction_scheme
|
list[int] | None
|
Multi-layer reduction scheme for gradual channel reduction (default: None). If None, uses single-layer reduction (input_channels → output_channels). If provided, must start with input_channels and end with output_channels. Example: [61, 16, 8, 3] means: - Layer 1: 61 → 16 channels - Layer 2: 16 → 8 channels - Layer 3: 8 → 3 channels This matches the DRCNN paper's multi-layer architecture for better optimization. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
conv |
Conv2d
|
1x1 convolutional layer performing spectral mixing |
activation |
LeakyReLU or None
|
Leaky ReLU activation function (if use_activation=True) |
Examples:
>>> # Create mixer: 61 channels → 3 channels (single-layer)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Create mixer with multi-layer reduction (matches DRCNN paper)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... reduction_scheme=[61, 16, 8, 3], # Gradual reduction
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Optional: Initialize from PCA
>>> # mixer.statistical_initialization(input_stream)
>>>
>>> # Enable gradient training
>>> mixer.unfreeze()
>>>
>>> # Forward pass: [B, H, W, 61] → [B, H, W, 3]
>>> output = mixer.forward(data=hsi_cube)
>>> rgb_like = output["rgb"] # [B, H, W, 3]
Source code in cuvis_ai/node/channel_mixer.py
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 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 | |
requires_initial_fit
property
¶
Whether this node requires statistical initialization.
statistical_initialization
¶
Initialize mixer weights from PCA components.
This method computes PCA on the input data and initializes the mixer weights to the top principal components. This provides a good starting point for gradient-based optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is [B, H, W, C_in] |
required |
Notes
This method is only used when init_method="pca". For other initialization methods, weights are set in init.
Source code in cuvis_ai/node/channel_mixer.py
unfreeze
¶
Enable gradient-based training of mixer weights.
Call this method to allow gradient updates during training. The mixer weights and biases will be optimized via backpropagation.
Example
mixer = LearnableChannelMixer(input_channels=61, output_channels=3) mixer.unfreeze() # Enable gradient training
Now mixer weights can be optimized with gradient descent¶
Source code in cuvis_ai/node/channel_mixer.py
forward
¶
Apply learnable channel mixing to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format |
required |
context
|
Context
|
Execution context with epoch, batch_idx, stage info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "rgb" key containing reduced channels [B, H, W, C_out] |
Source code in cuvis_ai/node/channel_mixer.py
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 | |
Concrete Selector¶
concrete_selector
¶
Concrete/Gumbel-Softmax band selector node for hyperspectral data.
This module implements a learnable band selector using the Concrete / Gumbel-Softmax relaxation, suitable for end-to-end training with AdaClip.
The selector learns K categorical distributions over T input bands,
and during training uses the Gumbel-Softmax trick to produce differentiable
approximate one-hot selection weights that become increasingly peaked as the
temperature :math:\tau is annealed.
For each output channel :math:c \in {1, \dots, K}, we learn logits
L_c in R^T and sample:
.. math::
w_c = \text{softmax}\left( \frac{L_c + g}{\tau} \right), \quad
g \sim \text{Gumbel}(0, 1)
The resulting weights are used to form K-channel RGB-like images:
.. math::
Y[:, :, c] = \sum_{t=1}^T w_c[t] \cdot X[:, :, t]
where X is the input hyperspectral cube in [0, 1].
ConcreteBandSelector
¶
ConcreteBandSelector(
input_channels,
output_channels=3,
tau_start=10.0,
tau_end=0.1,
max_epochs=20,
use_hard_inference=True,
eps=1e-06,
**kwargs,
)
Bases: Node
Concrete/Gumbel-Softmax band selector for hyperspectral cubes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube). |
required |
output_channels
|
int
|
Number of output channels (default: 3 for RGB/AdaClip compatibility). |
3
|
tau_start
|
float
|
Initial temperature for Gumbel-Softmax (default: 10.0). |
10.0
|
tau_end
|
float
|
Final temperature for Gumbel-Softmax (default: 0.1). |
0.1
|
max_epochs
|
int
|
Number of epochs over which to exponentially anneal :math: |
20
|
use_hard_inference
|
bool
|
If True, uses hard argmax selection at inference/validation time (one-hot weights). If False, uses softmax over logits (default: True). |
True
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6). |
1e-06
|
Notes
- During training (
context.stage == 'train'), the node samples Gumbel noise and uses the Concrete relaxation with the current temperature :math:\tau(\text{epoch}). - During validation/test/inference, it uses deterministic weights without Gumbel noise.
- The node exposes
selection_weightsso that repulsion penalties (e.g., DistinctnessLoss) can be attached in the pipeline.
Source code in cuvis_ai/node/concrete_selector.py
get_selection_weights
¶
Return current selection weights without data dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deterministic
|
bool
|
If True, uses softmax over logits (no Gumbel noise) at a
"midpoint" temperature (geometric mean of start/end). If False,
uses current logits with |
True
|
Source code in cuvis_ai/node/concrete_selector.py
get_selected_bands
¶
forward
¶
Apply Concrete/Gumbel-Softmax band selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format. |
required |
context
|
Context
|
Execution context with stage and epoch information. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with:
- |
Source code in cuvis_ai/node/concrete_selector.py
Channel Selector¶
selector
¶
Soft channel selector node for learnable channel selection.
SoftChannelSelector
¶
SoftChannelSelector(
n_select,
input_channels,
init_method="uniform",
temperature_init=5.0,
temperature_min=0.1,
temperature_decay=0.9,
hard=False,
eps=1e-06,
**kwargs,
)
Bases: Node
Soft channel selector with temperature-based Gumbel-Softmax selection.
This node learns to select a subset of input channels using differentiable channel selection with temperature annealing. Supports: - Statistical initialization (uniform or importance-based) - Gradient-based optimization with temperature scheduling - Entropy and diversity regularization - Hard selection at inference time
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_select
|
int
|
Number of channels to select |
required |
input_channels
|
int
|
Number of input channels |
required |
init_method
|
('uniform', 'variance')
|
Initialization method for channel weights (default: "uniform") |
"uniform"
|
temperature_init
|
float
|
Initial temperature for Gumbel-Softmax (default: 5.0) |
5.0
|
temperature_min
|
float
|
Minimum temperature (default: 0.1) |
0.1
|
temperature_decay
|
float
|
Temperature decay factor per epoch (default: 0.9) |
0.9
|
hard
|
bool
|
If True, use hard selection at inference (default: False) |
False
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Attributes:
| Name | Type | Description |
|---|---|---|
channel_logits |
Parameter or Tensor
|
Unnormalized channel importance scores [n_channels] |
temperature |
float
|
Current temperature for Gumbel-Softmax |
Source code in cuvis_ai/node/selector.py
statistical_initialization
¶
Initialize channel selection weights from data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/node/selector.py
unfreeze
¶
Convert channel logits buffer to trainable nn.Parameter.
Call this method to enable gradient-based optimization of channel selection weights. The logits will be converted from a buffer to an nn.Parameter, allowing gradient updates during training.
Example
selector = SoftChannelSelector(n_select=10, input_channels=100) selector.unfreeze() # Enable gradient training
Now channel selection weights can be optimized¶
Source code in cuvis_ai/node/selector.py
update_temperature
¶
Update temperature with decay schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current epoch number (used for per-epoch decay) |
None
|
step
|
int
|
Current training step (for more granular control) |
None
|
Source code in cuvis_ai/node/selector.py
get_selection_weights
¶
Get current channel selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hard
|
bool
|
If True, use hard selection (top-k). If None, uses self.hard. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Selection weights [n_channels] summing to n_select |
Source code in cuvis_ai/node/selector.py
forward
¶
Apply soft channel selection to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "selected" key containing reweighted channels and optional "weights" key containing selection weights |
Source code in cuvis_ai/node/selector.py
TopKIndices
¶
Bases: Node
Utility node that surfaces the top-k channel indices from selector weights.
This node extracts the indices of the top-k weighted channels from a selector's weight vector. Useful for introspection and reporting which channels were selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of top indices to return |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
k |
int
|
Number of top indices to return |
Source code in cuvis_ai/node/selector.py
forward
¶
Return the indices of the top-k weighted channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "indices" key containing top-k indices |
Source code in cuvis_ai/node/selector.py
Deep Learning Nodes¶
Nodes implementing deep learning components.
AdaCLIP¶
adaclip
¶
AdaCLIP Anomaly Detection Nodes.
This module provides nodes for zero-shot anomaly detection using the AdaCLIP (Adaptive CLIP) model. Two implementations are available:
- AdaCLIPLocalNode: Loads and runs the CLIP vision model locally for inference
- AdaCLIPAPINode: Calls the AdaCLIP HuggingFace Space API for inference
AdaCLIP uses CLIP's vision features to detect anomalies based on text prompts, enabling zero-shot anomaly detection without training data.
See Also
cuvis_ai_core.node.huggingface : Base classes for HuggingFace model nodes
AdaCLIPLocalNode
¶
AdaCLIPLocalNode(
model_name="AdaCLIP",
cache_dir=None,
text_prompt="normal: lentils, anomaly: stones",
revision=None,
**kwargs,
)
Bases: HuggingFaceLocalNode
AdaCLIP anomaly detection with local HF loading.
Source code in cuvis_ai/node/adaclip.py
forward
¶
Run AdaCLIP anomaly detection with local CLIP model.
Processes images through CLIP vision encoder and generates anomaly scores based on feature norms. Supports gradient passthrough for training pipelines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
RGB image [B, H, W, 3] in range [0, 1] or [0, 255]. |
required |
text_prompt
|
str
|
Text description for anomaly detection. If None, uses self.text_prompt. Note: Current implementation uses feature norms; text prompts will be integrated in future versions. |
None
|
context
|
Any
|
Pipeline execution context (unused, for compatibility). |
None
|
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary containing: - "anomaly_mask" : Tensor [B, 1, 1, 1] - Binary anomaly predictions - "anomaly_scores" : Tensor [B, 1, 1, 1] - Normalized anomaly scores [0, 1] |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If CLIP inference fails or model is not properly loaded. |
Source code in cuvis_ai/node/adaclip.py
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 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 | |
AdaCLIPAPINode
¶
AdaCLIPAPINode(
space_url="Caoyunkang/AdaCLIP",
dataset_option="All",
text_prompt="normal: lentils, anomaly: stones",
**kwargs,
)
Bases: HuggingFaceAPINode
AdaCLIP anomaly detection via HuggingFace Spaces API.
This node calls the AdaCLIP Space for zero-shot anomaly detection. API backend is non-differentiable and suitable for inference only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
space_url
|
str
|
AdaCLIP Space URL (default: "Caoyunkang/AdaCLIP") |
'Caoyunkang/AdaCLIP'
|
dataset_option
|
str
|
Dataset selection option (default: "All") |
'All'
|
text_prompt
|
str
|
Text prompt for anomaly detection (default: "normal: lentils, anomaly: stones") |
'normal: lentils, anomaly: stones'
|
**kwargs
|
Additional arguments passed to HuggingFaceAPINode |
{}
|
Examples:
>>> # Create node
>>> adaclip = AdaCLIPAPINode()
>>>
>>> # Run inference
>>> rgb_image = torch.rand(1, 224, 224, 3) # BHWC format
>>> result = adaclip.forward(image=rgb_image)
>>> anomaly_mask = result["anomaly_mask"] # [B, H, W, 1]
Source code in cuvis_ai/node/adaclip.py
forward
¶
Run AdaCLIP anomaly detection via API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
RGB image [B, H, W, 3] in BHWC format |
required |
text_prompt
|
str
|
Text description of anomaly to detect. If None, uses self.text_prompt. |
None
|
**kwargs
|
Any
|
Additional arguments (unused) |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "anomaly_mask" and optionally "anomaly_scores" |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If API call fails |
ValueError
|
If image format is invalid |
Source code in cuvis_ai/node/adaclip.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 | |
Analysis & Dimensionality Reduction¶
Nodes for dimensionality reduction and feature extraction.
PCA¶
pca
¶
Trainable PCA node for dimensionality reduction with gradient-based optimization.
TrainablePCA
¶
Bases: Node
Trainable PCA node with orthogonality regularization.
This node performs Principal Component Analysis (PCA) for dimensionality reduction and can be trained end-to-end with gradient descent. It supports: - Statistical initialization from data - Gradient-based fine-tuning with orthogonality constraints - Explained variance tracking
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int
|
Number of principal components to retain |
required |
whiten
|
bool
|
If True, scale components by explained variance (default: False) |
False
|
init_method
|
('svd', 'random')
|
Initialization method for components (default: "svd") |
"svd"
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Attributes:
| Name | Type | Description |
|---|---|---|
components |
Parameter or Tensor
|
Principal components matrix [n_components, n_features] |
mean |
Tensor
|
Feature-wise mean [n_features] |
explained_variance |
Tensor
|
Variance explained by each component [n_components] |
Source code in cuvis_ai/node/pca.py
statistical_initialization
¶
Initialize PCA components from data using SVD.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Input stream yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/node/pca.py
unfreeze
¶
Convert components buffer to trainable nn.Parameter.
Call this method after fit() to enable gradient-based training of the principal components. The components will be converted from a buffer to an nn.Parameter, allowing gradient updates during training.
Example
pca.statistical_initialization(input_stream) # Statistical initialization pca.unfreeze() # Enable gradient training
Now PCA components can be fine-tuned with gradient descent¶
Source code in cuvis_ai/node/pca.py
forward
¶
Project data onto principal components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "projected" key containing PCA-projected data |
Source code in cuvis_ai/node/pca.py
Visualization Nodes¶
Nodes for creating visualizations and TensorBoard logging.
Visualizations¶
visualizations
¶
Visualization sink nodes for monitoring training progress (port-based architecture).
CubeRGBVisualizer
¶
Bases: Node
Creates false-color RGB images from hyperspectral cube using channel weights.
Selects 3 channels with highest weights for R, G, B channels and creates a false-color visualization with wavelength annotations.
Source code in cuvis_ai/node/visualizations.py
forward
¶
Generate false-color RGB visualizations from hyperspectral cube.
Selects the 3 channels with highest weights and creates RGB images with wavelength annotations. Also generates a bar chart showing channel weights with the selected channels highlighted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
weights
|
Tensor
|
Channel selection weights [C] indicating importance of each channel. |
required |
wavelengths
|
Tensor
|
Wavelengths for each channel [C] in nanometers. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of visualization artifacts. |
Source code in cuvis_ai/node/visualizations.py
PCAVisualization
¶
Bases: Node
Visualize PCA-projected data with scatter and image plots.
Creates visualizations for each batch element showing: 1. Scatter plot of H*W points in 2D PC space (using first 2 PCs) 2. Image representation of the 2D projection reshaped to [H, W, 2]
Points in scatter plot are colored by spatial position. Returns artifacts for monitoring systems.
Executes only during validation stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of batch elements to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> pca_viz = PCAVisualization(up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (pca.projected, pca_viz.data),
... (pca_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/visualizations.py
forward
¶
Create PCA projection visualizations as Artifact objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
PCA-projected data tensor [B, H, W, C] (uses first 2 components) |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/visualizations.py
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 230 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 | |
AnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks.
Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on hyperspectral cube images. The overlay shows: - Green: True Positives (correct anomaly detection) - Red: False Positives (false alarms) - Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
int
|
Channel index to use for cube visualization (required) |
required |
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = AnomalyMask(channel=30, up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (logit_head.logits, decider.data),
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (data_node.cube, viz_mask.cube),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/visualizations.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
cube
|
Tensor
|
Original cube [B, H, W, C] for visualization |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/visualizations.py
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 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 644 645 646 647 648 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 | |
ScoreHeatmapVisualizer
¶
Bases: Node
Log LAD/RX score heatmaps as TensorBoard artifacts.
Source code in cuvis_ai/node/visualizations.py
forward
¶
Generate heatmap visualizations of anomaly scores.
Creates color-mapped heatmaps of anomaly scores for visualization in TensorBoard. Optionally normalizes scores to [0, 1] range for consistent visualization across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Anomaly scores [B, H, W, 1] from detection nodes (e.g., RX, LAD). |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of heatmap artifacts. |
Source code in cuvis_ai/node/visualizations.py
RGBAnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks on RGB images.
Similar to AnomalyMask but designed for RGB images (e.g., from band selectors). Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on RGB images. The overlay shows: - Green: True Positives (correct anomaly detection) - Red: False Positives (false alarms) - Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = RGBAnomalyMask(up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (band_selector.rgb_image, viz_mask.rgb_image),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Initialize RGBAnomalyMask visualizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int | None
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Source code in cuvis_ai/node/visualizations.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison on RGB images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
rgb_image
|
Tensor
|
RGB image [B, H, W, 3] for visualization |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
context
|
Context | None
|
Execution context with stage, epoch, batch_idx |
None
|
scores
|
Tensor | None
|
Optional anomaly logits/scores [B, H, W, 1] |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/visualizations.py
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 990 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 | |
TensorBoard Visualization¶
drcnn_tensorboard_viz
¶
TensorBoard visualization node for DRCNN-AdaClip training.
This node creates image artifacts for TensorBoard logging to visualize: - Input HSI cube (false-color RGB visualization) - Mixer output (what AdaClip sees as input) - Ground truth anomaly masks - AdaClip anomaly scores (as heatmap)
DRCNNTensorBoardViz
¶
Bases: Node
TensorBoard visualization node for DRCNN-AdaClip pipeline.
Creates image artifacts for logging to TensorBoard: - Input HSI cube visualization (false-color RGB from selected channels) - Mixer output (3-channel RGB-like image that AdaClip sees) - Ground truth anomaly mask - AdaClip anomaly scores (as heatmap)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_channels
|
list[int]
|
Channel indices to use for false-color RGB visualization of HSI input (default: [0, 20, 40] for a simple false-color representation) |
None
|
max_samples
|
int
|
Maximum number of samples to log per batch (default: 4) |
4
|
log_every_n_batches
|
int
|
Log images every N batches to reduce TensorBoard size (default: 1, log every batch) |
1
|
Source code in cuvis_ai/node/drcnn_tensorboard_viz.py
forward
¶
Create image artifacts for TensorBoard logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_cube
|
Tensor
|
Input HSI cube [B, H, W, C] |
required |
mixer_output
|
Tensor
|
Mixer output (RGB-like) [B, H, W, 3] |
required |
ground_truth_mask
|
Tensor
|
Ground truth anomaly mask [B, H, W, 1] |
required |
adaclip_scores
|
Tensor
|
AdaClip anomaly scores [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/drcnn_tensorboard_viz.py
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 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 189 190 191 192 193 194 195 196 197 198 199 200 | |
Monitor¶
monitor
¶
TensorBoard Monitoring Nodes.
This module provides nodes for logging artifacts and metrics to TensorBoard during pipeline execution. The monitoring nodes are sink nodes that accept artifacts (visualizations) and metrics from upstream nodes and write them to TensorBoard logs for visualization and analysis.
The primary use case is logging training and validation metrics, along with visualizations like heatmaps, RGB renderings, and PCA plots during model training.
See Also
cuvis_ai.node.visualizations : Nodes that generate artifacts for monitoring
TensorBoardMonitorNode
¶
Bases: Node
TensorBoard monitoring node for logging artifacts and metrics.
This is a SINK node that logs visualizations (artifacts) and metrics to TensorBoard. Accepts optional inputs for artifacts and metrics, allowing predecessors to be filtered by execution_stage without causing errors.
Executes during all stages (ALWAYS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory for TensorBoard logs (default: "./runs") |
'./runs'
|
comment
|
str
|
Comment to append to log directory name (default: "") |
''
|
flush_secs
|
int
|
How often to flush pending events to disk (default: 120) |
120
|
Examples:
>>> heatmap_viz = AnomalyHeatmap(cmap='hot', up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (heatmap_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/monitor.py
forward
¶
Log artifacts and metrics to TensorBoard.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
Execution context with stage, epoch, batch_idx, global_step |
None
|
artifacts
|
list[Artifact]
|
List of artifacts to log (default: None) |
None
|
metrics
|
list[Metric]
|
List of metrics to log (default: None) |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node has no outputs) |
Source code in cuvis_ai/node/monitor.py
log
¶
Log a scalar value to TensorBoard.
This method provides a simple interface for external trainers to log metrics directly, complementing the port-based logging. Used by GradientTrainer to log train/val losses to the same TensorBoard directory as graph metrics and artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name/tag for the scalar (e.g., "train/loss", "val/accuracy") |
required |
value
|
float
|
Scalar value to log |
required |
step
|
int
|
Global step number |
required |
Examples:
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> # From external trainer
>>> tensorboard_node.log("train/loss", 0.5, step=100)
Source code in cuvis_ai/node/monitor.py
Label Processing¶
Nodes for label conversion and manipulation.
Labels¶
labels
¶
Label Mapping Nodes.
This module provides nodes for converting multi-class segmentation masks to binary anomaly labels. These nodes are useful when training with datasets that have multi-class annotations but the task requires binary anomaly detection.
The main node remaps class IDs to binary labels (0=normal, 1=anomaly) based on configurable normal and anomaly class ID lists.
See Also
cuvis_ai.deciders : Binary decision nodes for threshold-based classification
BinaryAnomalyLabelMapper
¶
Bases: Node
Convert multi-class segmentation masks to binary anomaly targets.
Masks are remapped to torch.long tensors with 0 representing normal pixels and 1 indicating anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normal_class_ids
|
Iterable[int]
|
Class IDs that should be considered normal (default: (0, 2)). |
required |
anomaly_class_ids
|
Iterable[int] | None
|
Explicit anomaly IDs. When |
None
|
Source code in cuvis_ai/node/labels.py
forward
¶
Map multi-class labels to binary anomaly labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Features/scores to pass through [B, H, W, C] |
required |
mask
|
Tensor
|
Multi-class segmentation masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "cube" (pass-through) and "mask" (binary bool) keys |