signxai.common package

Submodules

signxai.common.method_families module

Method Family Architecture for SignXAI2

This module implements a family-based approach for XAI methods, grouping genuinely similar methods while preserving complex method-specific logic.

class signxai.common.method_families.MethodFamily[source]

Bases: ABC

Base class for all method families.

__init__()[source]
abstract can_handle(method_name: str) bool[source]

Check if this family can handle the given method.

abstract execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute method for TensorFlow.

abstract execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute method for PyTorch.

execute(model, x, method_name: str, framework: str, **kwargs)[source]

Main execution entry point.

class signxai.common.method_families.SimpleGradientFamily[source]

Bases: MethodFamily

Handles basic gradient-based methods that are truly similar. Safe for consolidation with minimal risk.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a simple gradient method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute gradient methods for TensorFlow with dynamic modifiers.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute gradient methods for PyTorch.

class signxai.common.method_families.StochasticMethodFamily[source]

Bases: MethodFamily

Handles noise-based attribution methods. Moderate risk - requires careful parameter handling.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a stochastic method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute stochastic methods for TensorFlow with dynamic modifiers.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute stochastic methods for PyTorch.

class signxai.common.method_families.LRPBasicFamily[source]

Bases: MethodFamily

Handles basic LRP methods with simple epsilon/alpha-beta rules. Moderate risk - requires careful rule handling.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a basic LRP method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute LRP methods for TensorFlow with comprehensive rule parsing.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute LRP methods for PyTorch with comprehensive rule parsing.

class signxai.common.method_families.SpecializedLRPFamily[source]

Bases: MethodFamily

Handles complex LRP methods that need special handling. Higher risk - these methods have complex requirements.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a specialized LRP method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute specialized LRP methods for TensorFlow with sign variants.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute specialized LRP methods for PyTorch with comprehensive parsing.

class signxai.common.method_families.DeepLiftFamily[source]

Bases: MethodFamily

Handles DeepLift and related methods.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a DeepLift method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute DeepLift for TensorFlow.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute DeepLift for PyTorch.

class signxai.common.method_families.GuidedFamily[source]

Bases: MethodFamily

Handles guided backprop, deconvnet and related methods.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a guided method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute guided methods for TensorFlow with dynamic modifiers.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute guided methods for PyTorch.

class signxai.common.method_families.CAMFamily[source]

Bases: MethodFamily

Handles GradCAM and other CAM-based methods.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a CAM method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute CAM methods for TensorFlow.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute CAM methods for PyTorch.

class signxai.common.method_families.OcclusionFamily[source]

Bases: MethodFamily

Handles occlusion-based methods.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is an occlusion method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute occlusion for TensorFlow.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute occlusion for PyTorch.

class signxai.common.method_families.RandomFamily[source]

Bases: MethodFamily

Handles random baseline methods.

__init__()[source]
can_handle(method_name: str) bool[source]

Check if this is a random method.

execute_tensorflow(model, x, method_name: str, **kwargs)[source]

Execute random for TensorFlow.

execute_pytorch(model, x, method_name: str, **kwargs)[source]

Execute random for PyTorch.

class signxai.common.method_families.MethodFamilyRegistry[source]

Bases: object

Registry that manages all method families and routes requests.

__init__()[source]
execute(model, x, method_name: str, framework: str, **kwargs)[source]

Execute a method by finding the appropriate family. Falls back to original wrappers if no family can handle it.

get_supported_methods() set[source]

Get methods that are ACTUALLY supported by BOTH frameworks.

Returns the intersection of methods that work in both TensorFlow and PyTorch, not the union. This ensures only truly comparable methods are returned.

signxai.common.method_families.get_registry() MethodFamilyRegistry[source]

Get or create the global registry instance.

signxai.common.method_normalizer module

Method name normalizer to handle naming inconsistencies between frameworks.

This module provides canonical method naming and aliasing support to ensure consistent method names across TensorFlow and PyTorch implementations.

class signxai.common.method_normalizer.MethodNormalizer[source]

Bases: object

Normalize method names across frameworks to handle inconsistencies.

METHOD_PRESETS: Dict[str, Dict] = {'integrated_gradients': {'baseline': None, 'steps': 50}, 'lrp_alpha_1_beta_0': {'alpha': 1.0, 'beta': 0.0}, 'lrp_alpha_2_beta_1': {'alpha': 2.0, 'beta': 1.0}, 'lrp_epsilon': {'epsilon': 0.1}, 'smoothgrad': {'noise_level': 0.1, 'num_samples': 25}, 'vargrad': {'noise_level': 0.1, 'num_samples': 25}}
CANONICAL_NAMES: Dict[str, str] = {'GradCAM': 'grad_cam', 'LRP': 'lrp', 'deconv': 'deconvnet', 'deconvnet': 'deconvnet', 'deconvolution': 'deconvnet', 'deep_lift': 'deeplift', 'deeplift': 'deeplift', 'deeplift_method': 'deeplift', 'gradCAM': 'grad_cam', 'grad_cam': 'grad_cam', 'gradcam': 'grad_cam', 'gradient': 'gradient', 'gradients': 'gradient', 'guided_backprop': 'guided_backprop', 'guided_backpropagation': 'guided_backprop', 'guidedbackprop': 'guided_backprop', 'integrated_gradient': 'integrated_gradients', 'integrated_gradients': 'integrated_gradients', 'integratedgradient': 'integrated_gradients', 'integratedgradients': 'integrated_gradients', 'lrp': 'lrp'}
FRAMEWORK_SPECIFIC: Dict[str, Set[str]] = {'pytorch': {'flatlrp_z', 'lrp_z_x_input', 'lrp_z_x_input_x_sign', 'lrp_z_x_sign', 'lrpsign_epsilon_100_improved', 'lrpsign_epsilon_20_improved'}, 'tensorflow': {}}
DISABLED_METHODS: Set[str] = {'deconvnet_x_input_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_input_x_sign_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_sign_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_sign_mu_0_5_DISABLED_BROKEN_WRAPPER', 'smoothgrad_x_input_DISABLED_BROKEN_WRAPPER'}
classmethod normalize(method_name: str, framework: str | None = None) str[source]

Normalize a method name to its canonical form.

Parameters:
  • method_name – The method name to normalize

  • framework – The framework being used (‘tensorflow’ or ‘pytorch’)

Returns:

The canonical method name

Raises:

ValueError – If the method is disabled or not available in the framework

classmethod get_aliases(canonical_name: str) Set[str][source]

Get all known aliases for a canonical method name.

Parameters:

canonical_name – The canonical method name

Returns:

Set of all aliases (including the canonical name itself)

classmethod is_framework_specific(method_name: str, framework: str) bool[source]

Check if a method is specific to a particular framework.

Parameters:
  • method_name – The method name to check

  • framework – The framework to check against

Returns:

True if the method is specific to the given framework

classmethod get_framework_methods(framework: str) Set[str][source]

Get all framework-specific methods for a given framework.

Parameters:

framework – The framework name

Returns:

Set of framework-specific method names

signxai.common.method_parser module

class signxai.common.method_parser.MethodParser[source]

Bases: object

Parses XAI method strings into a structured format with comprehensive parameter extraction.

Handles complex method names like: - lrp_alpha_2_beta_1 -> lrp with alpha=2, beta=1 - gradient_x_sign_mu_neg_0_5 -> gradient with sign modifier and mu=-0.5 - lrp_epsilon_0_25_std_x -> lrp_epsilon with epsilon=0.25 and std_x modifier

parse(method_name: str) Dict[str, Any][source]

Parses a method string into base method, modifiers, and parameters.

Parameters:

method_name (str) – The method string.

Returns:

  • base_method: The canonical base method name

  • modifiers: List of modifiers (x_input, x_sign, std_x, etc.)

  • params: Extracted parameters with proper types

  • original_name: The original method name

Return type:

A dictionary with

signxai.common.validation module

signxai.common.validation.validate_input_shape(tensor: ndarray | Tensor | Tensor, expected_dims: int = 4, framework: str = 'numpy') bool[source]

Validates the shape of the input tensor.

Parameters:
  • tensor – Input tensor to validate.

  • expected_dims – Expected number of dimensions. Defaults to 4.

  • framework – Framework of the input tensor (‘numpy’, ‘tensorflow’, or ‘pytorch’). Defaults to ‘numpy’.

Returns:

True if shape is valid.

Raises:

ValueError – If input shape is invalid or framework is unknown.

signxai.common.validation.validate_input_range(tensor: ndarray | Tensor | Tensor, min_val: float = -1.0, max_val: float = 1.0) bool[source]

Validates the range of input values.

Parameters:
  • tensor – Input tensor to validate.

  • min_val – Minimum expected value. Defaults to -1.0.

  • max_val – Maximum expected value. Defaults to 1.0.

Returns:

True if range is valid.

Raises:

ValueError – If input range is invalid.

signxai.common.validation.validate_model_output(output: ndarray | Tensor | Tensor, num_classes: int | None = None) bool[source]

Validates model output format and dimensions.

Parameters:
  • output – Model output to validate.

  • num_classes – Expected number of classes (if None, skips this check). Defaults to None.

Returns:

True if output is valid.

Raises:

ValueError – If output format is invalid.

signxai.common.validation.validate_attribution_output(attribution: ndarray | Tensor | Tensor, input_shape: Tuple[int, ...]) bool[source]

Validates attribution map output shape and values.

Parameters:
  • attribution – Attribution map to validate.

  • input_shape – Expected shape matching input tensor.

Returns:

True if attribution is valid.

Raises:

ValueError – If attribution format is invalid.

signxai.common.validation.validate_framework_compatibility(model: Any) str[source]

Determines and validates the deep learning framework of a model.

Parameters:

model – Model to validate.

Returns:

Framework name (‘tensorflow’ or ‘pytorch’).

Raises:

ValueError – If model framework cannot be determined or is unsupported.

signxai.common.validation.convert_to_numpy(tensor: ndarray | Tensor | Tensor) ndarray[source]

Converts a tensor from any supported framework to a NumPy array.

Parameters:

tensor – Input tensor from any supported framework.

Returns:

NumPy array containing the tensor data.

Raises:

ValueError – If the input tensor type is not supported.

signxai.common.visualization module

Visualization utilities for displaying explanations.

signxai.common.visualization.normalize_relevance_map(relevance_map, percentile=99)[source]

Normalize relevance map by clipping at given percentile.

Parameters:
  • relevance_map – Numpy array of relevance values

  • percentile – Percentile for clipping

Returns:

Normalized relevance map

signxai.common.visualization.relevance_to_heatmap(relevance_map, cmap='seismic', symmetric=True)[source]

Convert relevance map to RGB heatmap.

Parameters:
  • relevance_map – Normalized relevance map

  • cmap – Matplotlib colormap name

  • symmetric – If True, ensure colormap is centered at zero

Returns:

RGB heatmap (H, W, 3) with values in [0, 1]

signxai.common.visualization.overlay_heatmap(image, heatmap, alpha=0.5)[source]

Overlay heatmap on image.

Parameters:
  • image – RGB image (H, W, 3) with values in [0, 1]

  • heatmap – RGB heatmap (H, W, 3) with values in [0, 1]

  • alpha – Transparency value for overlay

Returns:

Overlaid image (H, W, 3) with values in [0, 1]

Module contents

Common utilities and components shared across frameworks.

class signxai.common.MethodNormalizer[source]

Bases: object

Normalize method names across frameworks to handle inconsistencies.

METHOD_PRESETS: Dict[str, Dict] = {'integrated_gradients': {'baseline': None, 'steps': 50}, 'lrp_alpha_1_beta_0': {'alpha': 1.0, 'beta': 0.0}, 'lrp_alpha_2_beta_1': {'alpha': 2.0, 'beta': 1.0}, 'lrp_epsilon': {'epsilon': 0.1}, 'smoothgrad': {'noise_level': 0.1, 'num_samples': 25}, 'vargrad': {'noise_level': 0.1, 'num_samples': 25}}
CANONICAL_NAMES: Dict[str, str] = {'GradCAM': 'grad_cam', 'LRP': 'lrp', 'deconv': 'deconvnet', 'deconvnet': 'deconvnet', 'deconvolution': 'deconvnet', 'deep_lift': 'deeplift', 'deeplift': 'deeplift', 'deeplift_method': 'deeplift', 'gradCAM': 'grad_cam', 'grad_cam': 'grad_cam', 'gradcam': 'grad_cam', 'gradient': 'gradient', 'gradients': 'gradient', 'guided_backprop': 'guided_backprop', 'guided_backpropagation': 'guided_backprop', 'guidedbackprop': 'guided_backprop', 'integrated_gradient': 'integrated_gradients', 'integrated_gradients': 'integrated_gradients', 'integratedgradient': 'integrated_gradients', 'integratedgradients': 'integrated_gradients', 'lrp': 'lrp'}
FRAMEWORK_SPECIFIC: Dict[str, Set[str]] = {'pytorch': {'flatlrp_z', 'lrp_z_x_input', 'lrp_z_x_input_x_sign', 'lrp_z_x_sign', 'lrpsign_epsilon_100_improved', 'lrpsign_epsilon_20_improved'}, 'tensorflow': {}}
DISABLED_METHODS: Set[str] = {'deconvnet_x_input_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_input_x_sign_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_sign_DISABLED_BROKEN_WRAPPER', 'deconvnet_x_sign_mu_0_5_DISABLED_BROKEN_WRAPPER', 'smoothgrad_x_input_DISABLED_BROKEN_WRAPPER'}
classmethod normalize(method_name: str, framework: str | None = None) str[source]

Normalize a method name to its canonical form.

Parameters:
  • method_name – The method name to normalize

  • framework – The framework being used (‘tensorflow’ or ‘pytorch’)

Returns:

The canonical method name

Raises:

ValueError – If the method is disabled or not available in the framework

classmethod get_aliases(canonical_name: str) Set[str][source]

Get all known aliases for a canonical method name.

Parameters:

canonical_name – The canonical method name

Returns:

Set of all aliases (including the canonical name itself)

classmethod is_framework_specific(method_name: str, framework: str) bool[source]

Check if a method is specific to a particular framework.

Parameters:
  • method_name – The method name to check

  • framework – The framework to check against

Returns:

True if the method is specific to the given framework

classmethod get_framework_methods(framework: str) Set[str][source]

Get all framework-specific methods for a given framework.

Parameters:

framework – The framework name

Returns:

Set of framework-specific method names