ExplainabilityHelper Module

Contains tools for model explainability and interpretability in machine learning workflows.

class HMB.ExplainabilityHelper.OptunaMLPipelineSHAPExplainer(baseDir, experimentFolderName, testFilename, targetColumn, pickleFilePath, shapStorageKeyword, csvName='Optuna_Best_Params.csv', dpi=1080)[source]

Bases: object

A class to perform SHAP (SHapley Additive exPlanations) analysis on a trained machine learning model.

This class provides a pipeline for loading a trained model and its associated data, preparing the test set to match the training pipeline (including feature selection and scaling), computing SHAP values for model interpretability, and generating a variety of SHAP-based visual explanations (waterfall, force, bar, beeswarm, scatter, and summary plots).

SHAP is a unified approach to explain the output of any machine learning model. It connects game theory with local explanations, providing both global and local interpretability.

Variables:
  • baseDir (str) – Base directory containing data and results.

  • experimentFolderName (str) – Name of the folder containing model storage files.

  • testFilename (str) – Filename of the test dataset.

  • targetColumn (str) – Name of the target column in the dataset.

  • pickleFilePath (str) – Path to the pickled model/storage file.

  • shapStorageKeyword (str) – Keyword for the storage path where SHAP results will be saved.

  • dpi (int) – Dots per inch for saving plots.

  • storagePath (str) – Full path for saving SHAP visualizations.

  • objects (dict) – Loaded model objects (model, scaler, etc.).

  • testData (pd.DataFrame) – Loaded test data.

  • XTest (pd.DataFrame) – Test features.

  • yTest (pd.Series) – Test target.

  • model – Trained model.

  • explainer – SHAP explainer object.

  • shapValues – Computed SHAP values.

  • yPred – Model predictions.

  • yPredDecoded – Decoded predictions.

Example

import HMB.ExplainabilityHelper as eh

explainer = eh.SHAPExplainer(
  baseDir="path/to/baseDir",
  experimentFolderName="Experiment1",
  testFilename="test_data.csv",
  targetColumn="target",
  pickleFilePath=None,
  shapStorageKeyword="SHAP_Results",
  dpi=1080,
  csvName="Optuna_Best_Params.csv"
)
explainer.LoadModelAndData(maxNoRecords=100)
explainer.ComputeShapValues()
explainer.MakePredictions()
explainer.VisualizeExplanations(
  instanceIndex=0,
  categoryToExplain="all",
  noOfRecords=150,
  noOfFeatures=5
)

Notes

SHAP visualizations are saved as PNG and PDF files in the specified storage directory. The class supports both global and local interpretability visualizations. For more information about SHAP and its visualization techniques, see: https://shap.readthedocs.io/en/latest/index.html

Initialize the SHAPExplainer object with file paths and configuration.

Parameters:
  • baseDir (str) – Base directory containing data and results.

  • experimentFolderName (str) – Name of the folder containing model storage files.

  • testFilename (str) – Filename of the test dataset.

  • targetColumn (str) – Name of the target column in the dataset.

  • pickleFilePath (str) – Path to the pickled model/storage file (if not provided, it will be constructed).

  • shapStorageKeyword (str) – Keyword for the storage path where SHAP results will be saved.

  • csvName (str, optional) – Filename for the CSV containing Optuna’s best parameters (default: “Optuna_Best_Params.csv”).

  • dpi (int, optional) – Dots per inch for saving plots (default: 1080).

Notes

  • The storage directory for SHAP results will be created if it does not exist.

  • All attributes are initialized to None except for configuration parameters.

__init__(baseDir, experimentFolderName, testFilename, targetColumn, pickleFilePath, shapStorageKeyword, csvName='Optuna_Best_Params.csv', dpi=1080)[source]

Initialize the SHAPExplainer object with file paths and configuration.

Parameters:
  • baseDir (str) – Base directory containing data and results.

  • experimentFolderName (str) – Name of the folder containing model storage files.

  • testFilename (str) – Filename of the test dataset.

  • targetColumn (str) – Name of the target column in the dataset.

  • pickleFilePath (str) – Path to the pickled model/storage file (if not provided, it will be constructed).

  • shapStorageKeyword (str) – Keyword for the storage path where SHAP results will be saved.

  • csvName (str, optional) – Filename for the CSV containing Optuna’s best parameters (default: “Optuna_Best_Params.csv”).

  • dpi (int, optional) – Dots per inch for saving plots (default: 1080).

Notes

  • The storage directory for SHAP results will be created if it does not exist.

  • All attributes are initialized to None except for configuration parameters.

LoadModelAndData(maxNoRecords=10)[source]

Load the trained model objects and the test dataset from files, and prepare the test data.

This method loads the model, scaler, feature selector, and other objects from a pickle file, reads the test dataset, applies the same preprocessing pipeline as used during training (feature selection, scaling), and limits the number of records if specified.

Refer to the class “OptunaTuning” documentation in the “MachineLearningHelper” module for details on how the model and preprocessing objects are stored.

Parameters:

maxNoRecords (int, optional) – Maximum number of records to limit the test dataset to (default: 10).

Notes

  • Ensures that the test data columns match those used during training.

  • Applies the same scaler and feature selector as in the training pipeline.

  • If maxNoRecords is set, randomly samples up to that number of records from the test set.

  • Prints the Optuna’s best parameters and columns used during training.

ComputeShapValues(maxEvals=None)[source]

Initialize the SHAP explainer and compute SHAP values for the test set.

This method creates a SHAP explainer object using the trained model and the prepared test features, then computes SHAP values for the test set to explain model predictions.

Parameters:

maxEvals (int, optional) – Maximum number of evaluations for the SHAP explainer (default: None, which means noOfFeatures * 2 + 1).

Notes

  • The computed SHAP values are stored in self.shapValues.

  • Prints the shape of the computed SHAP values.

  • The SHAP explainer is stored in self.explainer.

MakePredictions()[source]

Make predictions on the test set using the loaded model and decode them.

This method uses the trained model to predict on the prepared test features, and decodes the predicted labels back to their original form using the stored label encoder.

Notes

  • The predictions are stored in self.yPred.

  • The decoded predictions are stored in self.yPredDecoded.

VisualizeComparativeFeatureImportance(noOfFeatures=10)[source]

Generate a comparative bar plot showing SHAP feature importance across AMD categories.

This method computes mean absolute SHAP values per feature for each diagnostic category and visualizes them in a grouped bar chart for direct comparison.

Parameters:

noOfFeatures (int, optional) – Number of top features to display (default: 10).

VisualizeDependenceWithAnnotations(topFeatures=None)[source]

Generate SHAP dependence plots for specified top features with automatic interaction detection.

Parameters:

topFeatures (list of str, optional) – List of feature names to generate dependence plots for. If None, the top 4 features by mean absolute SHAP value will be selected automatically.

VisualizeClassStratifiedBeeswarm(noOfFeatures=15)[source]

Generate class-stratified SHAP beeswarm plots for the top features. This method creates separate SHAP beeswarm plots for each diagnostic category in the test set, allowing for visual comparison of feature importance distributions across classes.

Parameters:

noOfFeatures (int, optional) – Number of top features to display in the beeswarm plot (default: 15).

VisualizeErrorAnalysis(maxErrors=5)[source]

Generate SHAP waterfall plots for misclassified instances in the test set. This method identifies misclassified samples based on the model’s predictions and the true labels, then generates SHAP waterfall plots for a specified number of these error cases, providing insights into the feature contributions that led to the misclassification.

Parameters:

maxErrors (int, optional) – Maximum number of misclassified instances to visualize (default: 5).

VisualizeDecisionPlot(noOfInstances=500, noOfFeatures=20, classLabel=None)[source]

Generate a SHAP decision plot showing cumulative feature contributions across multiple instances.

This method creates a decision plot where each line represents one test sample, showing how SHAP values for top features accumulate to produce the final model output. Color-coding by class label enables visual assessment of class separation.

Parameters:
  • noOfInstances (int, optional) – Number of instances to display (default: 500).

  • noOfFeatures (int, optional) – Number of top features to include (default: 20).

  • classLabel (int | str | None, optional) – Specific class to filter; None shows all classes.

VisualizeExplanations(instanceIndex=None, categoryToExplain='all', noOfRecords=150, noOfFeatures=5)[source]

Generate and save various SHAP visualizations for model interpretability.

This method produces and saves the following SHAP plots:
  • Waterfall plot for a specific instance’s prediction.

  • Force plot for a specific instance’s prediction.

  • Bar plot (global feature importance).

  • Beeswarm plot (global feature importance).

  • Scatter and summary plots for the test set, optionally filtered by class/category.

Parameters:
  • instanceIndex (int, optional) – Index of the specific instance to explain. If None, a random index is chosen.

  • categoryToExplain (int | str, optional) – The class label for reference in plots (e.g., 0 for Negative Label = 0). If “all”, plots are generated for all classes.

  • noOfRecords (int, optional) – Number of records to consider for summary/scatter plots.

  • noOfFeatures (int, optional) – Number of top features to display in plots.

Notes

  • All plots are saved as both PNG and PDF files in the storage directory.

  • If categoryToExplain is “all”, plots are generated for each unique class in the target variable.

  • Prints a message when visualizations are saved.

  • Uses SHAP’s built-in plotting functions for visualization.

class HMB.ExplainabilityHelper.CAMExplainerPyTorch(torchModel=None, yoloModel=None, device='cpu', camType='gradcam', imgSize=640, alpha=0.45, outputBase=None, figsize=(14, 12), dpi=300, fontSize=14, topN=20, debug=False)[source]

Bases: object

A convenience wrapper to run CAM / attribution methods on a torch model and save results.

This class provides a compact, self-contained interface for computing a wide set of class-discriminative and gradient-based attribution maps (Grad-CAM family, Layer-CAM, Score-CAM, Ablation-CAM) and classic attribution techniques (saliency, SmoothGrad, Integrated Gradients, Occlusion, Grad x Input). The implementation prefers the instance-level implementations when available and falls back to module-level helper functions present in the same module.

The class is intended to be used in explainability pipelines where a trained PyTorch classification model (or a YOLO classification wrapper) is available and a human-readable visualization (heatmap overlay and annotated figure) is required.

Variables:
  • torchModel (torch.nn.Module | None) – The underlying PyTorch model used for inference and gradients.

  • yoloModel (object | None) – Optional Ultralytics YOLO wrapper from which a torch model may be extracted.

  • device (torch.device) – Device where model and tensors are executed.

  • camType (str) – Selected CAM / attribution method name (lowercase key used by dispatch map).

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs (Overlays, Heatmaps) are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

  • targetLayer (torch.nn.Module | None) – Default convolutional layer chosen as target for CAM computations.

Example

import torch
import numpy as np
from PIL import Image
from HMB.ExplainabilityHelper import CAMExplainerPyTorch

# Create a tiny dummy model for a quick smoke test.
model = torch.nn.Sequential(
  torch.nn.Conv2d(3, 8, kernel_size=3, padding=1),
  torch.nn.ReLU(),
  torch.nn.AdaptiveAvgPool2d((8, 8)),
  torch.nn.Flatten(),
  torch.nn.Linear(8 * 8 * 8, 10)
)

explainer = CAMExplainerPyTorch(
  torchModel=model,
  device="cpu",
  camType="gradcam",
  imgSize=224,
  outputBase="./ExplainabilityOut",
  debug=True
)

# Process a single image and save overlay/annotated outputs.
img = Image.fromarray((np.random.rand(224, 224, 3) * 255).astype("uint8"))
tmpPath = Path("./tempSampleImage.png")
img.save(tmpPath)
result = explainer.ProcessImage(tmpPath, classNames={i: str(i) for i in range(10)})
print(result)

Notes

  • The class-level implementations are intended to be self-sufficient; if a module-level helper function exists with the same name the instance will prefer the instance method first and fall back to the module function.

  • Some CAMs (Score-CAM, Ablation-CAM) are computationally heavy for large models or high-resolution inputs; tune top-K and sample counts accordingly.

  • Removed methods: RISE, GuidedGradCam, GuidedBackprop, GradientShap and DeepLift are intentionally not supported at the class-level and will raise a RuntimeError if requested via the class dispatch. Module-level helpers (if present) remain unchanged and can be invoked directly.

  • Naming conventions: method names use CamelCase and variables use camelCase.

Initialize the CAMExplainerPyTorch with model, device and visualization settings.

Parameters:
  • torchModel (torch.nn.Module | None) – The underlying PyTorch model used for inference and gradients.

  • yoloModel (object | None) – Optional Ultralytics YOLO wrapper from which a torch model may be extracted.

  • device (str) – Device where model and tensors are executed (“cpu” or “cuda”).

  • camType (str) – Selected CAM / attribution method name (lowercase key used by dispatch map).

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs (Overlays, Heatmaps) are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

Notes

  • If both torchModel and yoloModel are provided, torchModel takes precedence.

  • If no torchModel is provided but a yoloModel is, the underlying torch model is extracted automatically.

AVAILABLE_CAM_METHODS = {'ablationcam', 'eigencam', 'gradcam', 'gradcampp', 'gradxinput', 'integratedgradients', 'layercam', 'occlusion', 'saliency', 'scorecam', 'smoothgrad', 'smoothgradcampp', 'xgradcam'}
__init__(torchModel=None, yoloModel=None, device='cpu', camType='gradcam', imgSize=640, alpha=0.45, outputBase=None, figsize=(14, 12), dpi=300, fontSize=14, topN=20, debug=False)[source]

Initialize the CAMExplainerPyTorch with model, device and visualization settings.

Parameters:
  • torchModel (torch.nn.Module | None) – The underlying PyTorch model used for inference and gradients.

  • yoloModel (object | None) – Optional Ultralytics YOLO wrapper from which a torch model may be extracted.

  • device (str) – Device where model and tensors are executed (“cpu” or “cuda”).

  • camType (str) – Selected CAM / attribution method name (lowercase key used by dispatch map).

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs (Overlays, Heatmaps) are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

Notes

  • If both torchModel and yoloModel are provided, torchModel takes precedence.

  • If no torchModel is provided but a yoloModel is, the underlying torch model is extracted automatically.

ExtractModel(yoloModel)[source]

Extract torch model from a YOLO wrapper or return the same model.

Parameters:

yoloModel (object | None) – Ultralytics YOLO wrapper or a torch.nn.Module.

Returns:

Extracted underlying torch model when possible, otherwise returns the provided object or None if input is None.

Return type:

torch.nn.Module | object | None

Notes

  • This mirrors the module-level helper but lives on the instance so it is always available. It tolerates wrappers that nest a .model attribute.

GetLastConvLayer(model)[source]

Find the last Conv2d layer to target for Grad-CAM.

Parameters:

model (torch.nn.Module | None) – PyTorch model to inspect.

Returns:

The last torch.nn.Conv2d module found in the model or None if no Conv2d layer is present.

Return type:

torch.nn.Module | None

Notes

  • Traverses the module tree and returns the deepest Conv2d instance. This method is safe to call with None and will return None in that case.

NormalizeHeatmap(heatmap)[source]

Normalize and enhance heatmap contrast to the [0,1] range.

Parameters:

heatmap (numpy.ndarray) – Raw heatmap array with arbitrary range.

Returns:

Normalized and smoothed heatmap clipped to [0,1].

Return type:

numpy.ndarray

Notes

  • Applies clipping, percentile-based contrast stretching, Gaussian blur and a mild gamma correction to improve visual contrast.

ApplyHeatmapOverlay(imageRgb, heatmap, alpha=None)[source]

Blend heatmap onto an RGB image and return uint8 RGB result.

Parameters:
  • imageRgb (numpy.ndarray) – Original RGB image array (H, W, 3) in uint8 or float.

  • heatmap (numpy.ndarray) – Heatmap normalized to [0,1] with shape (H, W).

  • alpha (float | None) – Blend factor for overlay. If None uses instance alpha.

Returns:

Blended RGB image as uint8.

Return type:

numpy.ndarray

Notes

  • Converts the heatmap to a colormap (Viridis) and blends using cv2.addWeighted.

  • Ensures the heatmap is resized to the image dimensions when needed.

LoadImage(imagePath, imageSize=None)[source]

Load and preprocess an image for the classifier and return tensor + RGB array.

Parameters:
  • imagePath (Path | str) – Path to the image file to load.

  • imageSize (int | None) – Square size to which the image is resized. If None, uses the explainer instance imgSize.

Returns:

(inputTensor, originalImage) where inputTensor is a torch tensor shaped (1, C, H, W) and originalImage is an RGB numpy array (H, W, 3).

Return type:

tuple

Notes

  • The pixel intensities are scaled to [0,1] and arranged in CHW order for model consumption. The returned originalImage preserves original pixels.

CamTypeToFolderName(camTypeString)[source]

Return CamelCase folder name for a camType string.

Parameters:

camTypeString (str) – Lowercase key describing the CAM method.

Returns:

CamelCase folder name suitable for file system use.

Return type:

str

Notes

  • Mapping centralizes naming so file outputs use consistent CamelCase strings for human-readability.

FormatClassName(classIndex, classNames, defaultLabel)[source]

Return readable class name from index.

Parameters:
  • classIndex (int | None) – Integer class index to map to a name.

  • classNames (dict) – Mapping from index to class name.

  • defaultLabel (str) – Fallback label when no mapping is available.

Returns:

Resolved class name or the provided defaultLabel.

Return type:

str

Notes

  • Safe to call with classIndex == None.

CreateAnnotatedVisualization(imageRgb, heatmap, overlayImage, className, predictedClassName, trueClassName, alpha, confidence, methodName='GradCam', figureSize=(12, 12), dpiValue=300, fontSize=14)[source]

Build a 2x2 annotated saliency figure with colorbars.

Parameters:
  • imageRgb (numpy.ndarray) – Original RGB image array.

  • heatmap (numpy.ndarray) – Heatmap in [0,1] used to render colorbars.

  • overlayImage (numpy.ndarray) – RGB overlay image produced by ApplyHeatmapOverlay.

  • className (str) – Name of the class being explained.

  • predictedClassName (str) – Predicted class name for annotation.

  • trueClassName (str) – Ground truth class name for annotation.

  • alpha (float) – Transparency value used for the overlay annotation.

  • confidence (float) – Confidence value for the predicted class in [0,1].

  • methodName (str) – Human readable method name used in titles.

  • figureSize (tuple) – Figure size in inches as (W, H).

  • dpiValue (int) – DPI used when rendering the figure.

  • fontSize (int) – Base font size used in annotations.

Returns:

RGB numpy array containing the rendered annotated visualization.

Return type:

numpy.ndarray

ComputeSaliency(inputTensor, predictedClass, targetForCam=None, targetLayer=None)[source]

Dispatch to the requested CAM / attribution routine and return a heatmap.

Parameters:
  • inputTensor (torch.Tensor) – Input image tensor shaped (1, C, H, W).

  • predictedClass (int) – Index of the predicted class returned by the model.

  • targetForCam (int | None) – Explicit target class index to explain. If None, the predictedClass will be used.

  • targetLayer (torch.nn.Module | None) – Convolutional layer to use for CAMs.

Returns:

Heatmap normalized to [0,1] as a 2D array matching input spatial dims.

Return type:

numpy.ndarray

Notes

  • Chooses an instance-level implementation when available, otherwise falls back to the module-level helper function with the same name.

  • Raises RuntimeError when no implementation is found for the selected camType.

ComputeSmoothGradCamPlusPlusSaliency(inputTensor, targetClass, targetLayer=None, device=None, samples=16, noiseLevel=0.15)[source]

Compute SmoothGrad-CAM++ by averaging Grad-CAM++ maps over noisy inputs.

Parameters:
  • inputTensor (torch.Tensor) – Base input tensor to perturb.

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to attach hooks to for Grad-CAM++.

  • device (torch.device | None) – Device used for computation.

  • samples (int) – Number of noisy samples to average.

  • noiseLevel (float) – Standard deviation of additive gaussian noise.

Returns:

Averaged Grad-CAM++ heatmap normalized to [0,1].

Return type:

numpy.ndarray

Notes

  • This is a smoothing wrapper around the Grad-CAM++ implementation and is useful to reduce high-frequency noise in single-shot CAMs.

ProcessImage(imagePath, classNames=None, overlaysDir=None, annotationsDir=None, heatmapsDir=None, contrast=False)[source]

Process a single image: predict, compute saliency and save outputs.

Parameters:
  • imagePath (Path | str) – Path to the image file to process.

  • classNames (dict | None) – Optional mapping class_idx -> className used for annotations.

  • overlaysDir (Path | None) – Directory to save overlay and annotated PNGs.

  • annotationsDir (Path | None) – Directory to save annotated images (not used currently).

  • heatmapsDir (Path | None) – Directory to save raw heatmap numpy arrays.

  • contrast (bool) – When True use class-contrast mode (explain top non-predicted class).

Returns:

Summary information about the processed image including image path, predicted/true class information and saliency statistics.

Return type:

dict

Notes

  • Prepares output directories when self.outputBase was provided at init.

  • File names use CamelCase for the fixed parts to match project conventions.

ProcessDirectory(imageFiles, classNames=None, overlaysDir=None, heatmapsDir=None, contrast=False)[source]

Process a list of images and return results for each image.

Parameters:
  • imageFiles (list[Path] | list[str]) – Iterable of image paths to process.

  • classNames (dict | None) – Optional class index->name mapping for annotations.

  • overlaysDir (Path | None) – Directory to save overlay/annotated outputs.

  • heatmapsDir (Path | None) – Directory to save heatmap arrays.

  • contrast (bool) – When True use class-contrast mode for CAM targets.

Returns:

List of result dictionaries returned by ProcessImage for each file.

Return type:

list[dict]

Notes

  • Creates output directories if they do not already exist.

ComputeGradCamSaliency(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute Grad-CAM heatmap for the predicted class using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None | int | str) – Layer to hook or index/name of layer.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

Returns:

Grad-CAM heatmap resized to input spatial dimensions and normalized to [0,1].

Return type:

numpy.ndarray

ComputeGradCamPlusPlusSaliency(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute Grad-CAM++ heatmap for the predicted class using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to attach hooks to for Grad-CAM++.

  • device (torch.device | None) – Device used for computation.

Returns:

Grad-CAM++ heatmap normalized to [0,1].

Return type:

numpy.ndarray

Notes

  • This is a smoothing wrapper around the Grad-CAM++ implementation and is useful to reduce high-frequency noise in single-shot CAMs.

ComputeXGradCamSaliency(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute XGrad-CAM heatmap for the predicted class using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to attach hooks to for XGrad-CAM.

  • device (torch.device | None) – Device used for computation.

Returns:

XGrad-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeEigenCamSaliency(inputTensor, targetLayer=None, device=None)[source]

Compute Eigen-CAM heatmap using activation PCA (gradient-free) using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetLayer (torch.nn.Module | None) – Layer to capture activations from.

  • device (torch.device | None) – Device used for computation.

Returns:

Eigen-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeLayerCamSaliency(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute Layer-CAM heatmap for the predicted class using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to capture activations from.

  • device (torch.device | None) – Device used for computation.

Returns:

Layer-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeScoreCamSaliency(inputTensor, targetClass, targetLayer=None, device=None, topK=32)[source]

Compute Score-CAM heatmap (forward-based, no gradients) for the predicted class using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to capture channel maps from.

  • device (torch.device | None) – Device used for computation.

  • topK (int) – Number of top channels to consider to reduce compute.

Returns:

Score-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeAblationCamSaliency(inputTensor, targetClass, targetLayer=None, device=None, topK=32)[source]

Compute Ablation-CAM heatmap by ablating top channels in the target layer using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Layer to capture channel maps from.

  • device (torch.device | None) – Device used for computation.

  • topK (int) – Number of top channels to ablate for weight estimation.

Returns:

Ablation-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ResolveTargetLayer(model, targetLayer)[source]

Resolve a target layer specification to a torch.nn.Module instance.

Parameters:
  • model (torch.nn.Module) – Model containing the target layer.

  • targetLayer (torch.nn.Module | int | str | None) – Specification of the target layer which can be: (a) None: pick the last Conv2d layer. (b) int: index of the Conv2d layer in model.modules(). (c) str: name of the module in model.named_modules(). (d) torch.nn.Module: already a module instance.

Returns:

Resolved module instance or None if not found.

Return type:

torch.nn.Module | None

Notes

  • If targetLayer is None, the last Conv2d layer is selected.

  • If an integer index is provided, the corresponding Conv2d module is selected.

  • If a string name is provided, the named module is searched for.

  • If the targetLayer is already a module-like object with hook API, it is returned as is.

ComputeIntegratedGradients(inputTensor, targetClass, targetLayer=None, device=None, steps=50)[source]

Compute Integrated Gradients for the predicted class from a zero baseline using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Present for API compatibility but not used for Integrated Gradients.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

  • steps (int) – Number of interpolation steps between baseline and input.

Returns:

Integrated Gradients attribution map normalized to [0,1].

Return type:

numpy.ndarray

ComputeOcclusion(inputTensor, targetClass, targetLayer=None, device=None, patchSize=32, stride=16)[source]

Compute Occlusion sensitivity map by sliding a gray patch and measuring score drop using the instance model.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Present for API compatibility but not used for Occlusion.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

  • patchSize (int) – Size of square occlusion patch.

  • stride (int) – Stride to move the occlusion patch.

Returns:

Occlusion sensitivity map normalized to [0,1].

Return type:

numpy.ndarray

ComputeSaliencyMap(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute vanilla saliency map (absolute gradients) for the target class.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Present for API compatibility but not used for Saliency Map.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

Returns:

Saliency map normalized to [0,1].

Return type:

numpy.ndarray

ComputeSmoothGrad(inputTensor, targetClass, targetLayer=None, device=None, samples=25, noiseLevel=0.15)[source]

Compute SmoothGrad by averaging saliency maps over noisy input samples.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Present for API compatibility but not used for SmoothGrad.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

  • samples (int) – Number of noisy samples to average over.

  • noiseLevel (float) – Standard deviation of Gaussian noise relative to input range [0,1].

Returns:

SmoothGrad saliency map normalized to [0,1].

Return type:

numpy.ndarray

ComputeGradXInput(inputTensor, targetClass, targetLayer=None, device=None)[source]

Compute gradient * input attributions (Grad x Input) for the target class.

Parameters:
  • inputTensor (torch.Tensor) – Input tensor shaped (1, C, H, W).

  • targetClass (int) – Target class index to explain.

  • targetLayer (torch.nn.Module | None) – Present for API compatibility but not used for Grad x Input.

  • device (torch.device | None) – Device used for computation. If None uses the instance device.

Returns:

Grad x Input attribution map normalized to [0,1].

Return type:

numpy.ndarray

class HMB.ExplainabilityHelper.CAMExplainerTensorFlow(tfModel=None, device='cpu', camType='gradcam', imgSize=640, alpha=0.45, outputBase=None, figsize=(14, 12), dpi=300, fontSize=14, topN=20, debug=False)[source]

Bases: object

A convenience wrapper to run CAM / attribution methods on a TensorFlow model and save results.

This class provides a compact, self-contained interface for computing a wide set of class-discriminative and gradient-based attribution maps (Grad-CAM family, Layer-CAM, Score-CAM, Ablation-CAM) and classic attribution techniques (saliency, SmoothGrad, Integrated Gradients, Occlusion, Grad x Input). The implementation mirrors the CAMExplainerPyTorch class but works with tf.keras models.

The class is intended to be used in explainability pipelines where a trained TensorFlow classification model is available and a human-readable visualization (heatmap overlay and annotated figure) is required.

Variables:
  • tfModel (tf.keras.Model | None) – The underlying TensorFlow model used for inference.

  • device (str) – Device where model and tensors are executed.

  • camType (str) – Selected CAM / attribution method name.

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

  • targetLayer (tf.keras.layers.Layer | None) – Default convolutional layer chosen as target.

Initialize the CAMExplainerTensorFlow with model, device and visualization settings.

Parameters:
  • tfModel (tf.keras.Model | None) – The underlying TensorFlow model used for inference.

  • device (str) – Device where model and tensors are executed (“cpu” or “gpu”).

  • camType (str) – Selected CAM / attribution method name.

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

AVAILABLE_CAM_METHODS = {'ablationcam', 'eigencam', 'gradcam', 'gradcampp', 'gradxinput', 'integratedgradients', 'layercam', 'occlusion', 'saliency', 'scorecam', 'smoothgrad', 'smoothgradcampp', 'xgradcam'}
__init__(tfModel=None, device='cpu', camType='gradcam', imgSize=640, alpha=0.45, outputBase=None, figsize=(14, 12), dpi=300, fontSize=14, topN=20, debug=False)[source]

Initialize the CAMExplainerTensorFlow with model, device and visualization settings.

Parameters:
  • tfModel (tf.keras.Model | None) – The underlying TensorFlow model used for inference.

  • device (str) – Device where model and tensors are executed (“cpu” or “gpu”).

  • camType (str) – Selected CAM / attribution method name.

  • imgSize (int) – Default square input size for preprocessing images.

  • alpha (float) – Default overlay transparency when blending heatmaps with the image.

  • outputBase (Path | None) – Optional base path where outputs are saved.

  • figsize (tuple) – Default figure size used by annotated visualizations.

  • dpi (int) – Default DPI used to render annotated images.

  • fontSize (int) – Base font size used in annotations.

  • topN (int) – Top-N value used for uncertainty/confidence tracking.

  • debug (bool) – Enable verbose debug prints if True.

GetLastConvLayer(model)[source]

Find the last Conv2D layer to target for Grad-CAM.

Parameters:

model (tf.keras.Model | None) – TensorFlow model to inspect.

Returns:

The last Conv2D layer found or None.

Return type:

tf.keras.layers.Layer | None

ResolveTargetLayer(model, targetLayer)[source]

Resolve a target layer specification to a tf.keras.layers.Layer instance.

Parameters:
  • model (tf.keras.Model) – Model containing the target layer.

  • targetLayer (tf.keras.layers.Layer | int | str | None) – Specification of the target layer.

Returns:

Resolved layer instance or None if not found.

Return type:

tf.keras.layers.Layer | None

CamTypeToFolderName(camTypeString)[source]

Return CamelCase folder name for a camType string.

Parameters:

camTypeString (str) – Lowercase key describing the CAM method.

Returns:

CamelCase folder name suitable for file system use.

Return type:

str

FormatClassName(classIndex, classNames, defaultLabel)[source]

Return readable class name from index.

Parameters:
  • classIndex (int | None) – Integer class index to map to a name.

  • classNames (dict) – Mapping from index to class name.

  • defaultLabel (str) – Fallback label when no mapping is available.

Returns:

Resolved class name or the provided defaultLabel.

Return type:

str

LoadImage(imagePath, imageSize=None)[source]

Load and preprocess an image for the classifier and return tensor + RGB array.

Parameters:
  • imagePath (Path | str) – Path to the image file to load.

  • imageSize (int | None) – Square size to which the image is resized.

Returns:

(inputTensor, originalImage) where inputTensor is a tf tensor and originalImage is RGB numpy array.

Return type:

tuple

NormalizeHeatmap(heatmap)[source]

Normalize and enhance heatmap contrast to the [0,1] range.

Parameters:

heatmap (numpy.ndarray) – Raw heatmap array with arbitrary range.

Returns:

Normalized and smoothed heatmap clipped to [0,1].

Return type:

numpy.ndarray

ApplyHeatmapOverlay(imageRgb, heatmap, alpha=None)[source]

Blend heatmap onto an RGB image and return uint8 RGB result.

Parameters:
  • imageRgb (numpy.ndarray) – Original RGB image array.

  • heatmap (numpy.ndarray) – Heatmap normalized to [0,1].

  • alpha (float | None) – Blend factor for overlay.

Returns:

Blended RGB image as uint8.

Return type:

numpy.ndarray

ComputeSaliency(inputTensor, predictedClass, targetForCam=None, targetLayer=None)[source]

Dispatch to the requested CAM / attribution routine and return a heatmap.

Parameters:
  • inputTensor (tf.Tensor) – Input image tensor shaped (1, H, W, C).

  • predictedClass (int) – Index of the predicted class.

  • targetForCam (int | None) – Explicit target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Convolutional layer to use for CAMs.

Returns:

Heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeGradCamSaliency(inputTensor, targetClass, targetLayer=None)[source]

Compute Grad-CAM heatmap for the predicted class.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to hook for Grad-CAM.

Returns:

Grad-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeGradCamPlusPlusSaliency(inputTensor, targetClass, targetLayer=None)[source]

Compute Grad-CAM++ heatmap for the predicted class.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to hook for Grad-CAM++.

Returns:

Grad-CAM++ heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeXGradCamSaliency(inputTensor, targetClass, targetLayer=None)[source]

Compute XGrad-CAM heatmap for the predicted class.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to hook.

Returns:

XGrad-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeEigenCamSaliency(inputTensor, targetLayer=None)[source]

Compute Eigen-CAM heatmap using activation PCA.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetLayer (tf.keras.layers.Layer | None) – Layer to capture activations.

Returns:

Eigen-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeLayerCamSaliency(inputTensor, targetClass, targetLayer=None)[source]

Compute Layer-CAM heatmap for the predicted class.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to hook.

Returns:

Layer-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeScoreCamSaliency(inputTensor, targetClass, targetLayer=None, topK=32)[source]

Compute Score-CAM heatmap (forward-based).

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to capture maps.

  • topK (int) – Number of top channels to consider.

Returns:

Score-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeAblationCamSaliency(inputTensor, targetClass, targetLayer=None, topK=32)[source]

Compute Ablation-CAM heatmap by ablating top channels.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to capture maps.

  • topK (int) – Number of top channels to ablate.

Returns:

Ablation-CAM heatmap normalized to [0,1].

Return type:

numpy.ndarray

ComputeIntegratedGradients(inputTensor, targetClass, targetLayer=None, steps=50)[source]

Compute Integrated Gradients for the predicted class.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Not used.

  • steps (int) – Number of interpolation steps.

Returns:

Integrated Gradients attribution map normalized to [0,1].

Return type:

numpy.ndarray

ComputeOcclusion(inputTensor, targetClass, targetLayer=None, patchSize=32, stride=16)[source]

Compute Occlusion sensitivity map.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Not used.

  • patchSize (int) – Size of square occlusion patch.

  • stride (int) – Stride to move the patch.

Returns:

Occlusion sensitivity map normalized to [0,1].

Return type:

numpy.ndarray

ComputeSaliencyMap(inputTensor, targetClass, targetLayer=None)[source]

Compute vanilla saliency map.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Not used.

Returns:

Saliency map normalized to [0,1].

Return type:

numpy.ndarray

ComputeSmoothGrad(inputTensor, targetClass, targetLayer=None, samples=25, noiseLevel=0.15)[source]

Compute SmoothGrad by averaging saliency maps.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Not used.

  • samples (int) – Number of noisy samples.

  • noiseLevel (float) – Standard deviation of noise.

Returns:

SmoothGrad saliency map normalized to [0,1].

Return type:

numpy.ndarray

ComputeGradXInput(inputTensor, targetClass, targetLayer=None)[source]

Compute Grad x Input attributions.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Not used.

Returns:

Grad x Input attribution map normalized to [0,1].

Return type:

numpy.ndarray

ComputeSmoothGradCamPlusPlusSaliency(inputTensor, targetClass, targetLayer=None, samples=16, noiseLevel=0.15)[source]

Compute SmoothGrad-CAM++ by averaging Grad-CAM++ maps.

Parameters:
  • inputTensor (tf.Tensor) – Input tensor shaped (1, H, W, C).

  • targetClass (int) – Target class index to explain.

  • targetLayer (tf.keras.layers.Layer | None) – Layer to hook.

  • samples (int) – Number of noisy samples.

  • noiseLevel (float) – Standard deviation of noise.

Returns:

SmoothGrad-CAM++ heatmap normalized to [0,1].

Return type:

numpy.ndarray

ProcessImage(imagePath, classNames=None, overlaysDir=None, annotationsDir=None, heatmapsDir=None, contrast=False)[source]

Process a single image: predict, compute saliency and save outputs.

Parameters:
  • imagePath (Path | str) – Path to the image file to process.

  • classNames (dict | None) – Optional mapping class_idx -> className.

  • overlaysDir (Path | None) – Directory to save overlay and annotated PNGs.

  • annotationsDir (Path | None) – Directory to save annotated images.

  • heatmapsDir (Path | None) – Directory to save raw heatmap numpy arrays.

  • contrast (bool) – When True use class-contrast mode.

Returns:

Summary information about the processed image.

Return type:

dict

ProcessDirectory(imageFiles, classNames=None, overlaysDir=None, heatmapsDir=None, contrast=False)[source]

Process a list of images and return results for each image.

Parameters:
  • imageFiles (list[Path] | list[str]) – Iterable of image paths to process.

  • classNames (dict | None) – Optional class index->name mapping.

  • overlaysDir (Path | None) – Directory to save overlay/annotated outputs.

  • heatmapsDir (Path | None) – Directory to save heatmap arrays.

  • contrast (bool) – When True use class-contrast mode.

Returns:

List of result dictionaries.

Return type:

list[dict]

CreateAnnotatedVisualization(imageRgb, heatmap, overlayImage, className, predictedClassName, trueClassName, alpha, confidence, methodName='GradCam', figureSize=(12, 12), dpiValue=300, fontSize=14)[source]

Build a 2x2 annotated saliency figure with colorbars.

Parameters:
  • imageRgb (numpy.ndarray) – Original RGB image array.

  • heatmap (numpy.ndarray) – Heatmap in [0,1] used to render colorbars.

  • overlayImage (numpy.ndarray) – RGB overlay image.

  • className (str) – Name of the class being explained.

  • predictedClassName (str) – Predicted class name.

  • trueClassName (str) – Ground truth class name.

  • alpha (float) – Transparency value.

  • confidence (float) – Confidence value.

  • methodName (str) – Human readable method name.

  • figureSize (tuple) – Figure size in inches.

  • dpiValue (int) – DPI used.

  • fontSize (int) – Base font size.

Returns:

RGB numpy array containing the rendered annotated visualization.

Return type:

numpy.ndarray

HMB.ExplainabilityHelper.TSNEFeaturesExplainability(featsSub, labelEncoder, nSamples, outDir, predIdxSub, trueIdxSub, numComponents=2, dpi=720, randomState=42, exportInteractive=False, figureTitlePrefix='t-SNE of Features', axisLabelPrefix='t-SNE Dimension', fileNamePrefix='TSNEFeatures', colorPaletteName='colorblind', enableClusterMetrics=True, enableMisclassificationHighlight=True, enableCentroidAnnotations=True, markerStyleCorrect='o', markerStylePredicted='^', markerStyleError='X', outputFileFormat='pdf', customClassNames=None, perplexityMin=5, perplexityMax=50, annotationOffset=(8, -5), fontSizeTitle=16, fontSizeAxis=14, alphaCorrect=0.85, alphaError=0.9, edgeColor='white', edgeWidth=0.3)[source]

Create a set of publication-ready t-SNE visualizations for feature embeddings and optionally compute cluster quality metrics.

The function produces several static figures saved to outDir:
  • Basic t-SNE colored by true labels

  • Basic t-SNE colored by predicted labels

  • Enhanced t-SNE (true labels) with optional centroid annotations

  • Enhanced t-SNE (predicted labels)

  • Side-by-side comparison of true vs predicted labels

  • Misclassification-highlighted view (optional)

  • Optional interactive Plotly HTML export (if exportInteractive and plotly installed)

Parameters:
  • featsSub (array-like) – Feature vectors to embed (n_samples x n_features).

  • labelEncoder (sklearn.preprocessing.LabelEncoder or None) – Optional encoder to map integer class indices back to human-readable class names. If None, integer class ids or customClassNames are used.

  • nSamples (int) – Number of samples in featsSub (used for metrics and adaptive params).

  • outDir (pathlib.Path or str) – Directory where generated figures and JSON metrics will be saved.

  • predIdxSub (array-like) – Predicted class indices for each sample (length nSamples).

  • trueIdxSub (array-like) – Ground-truth class indices for each sample (length nSamples).

  • numComponents (int) – Dimensionality of the embedding (default: 2).

  • dpi (int) – DPI to use when saving figures (default: 720).

  • randomState (int) – Random seed controlling t-SNE initialization (default: 42).

  • exportInteractive (bool) – If True, export an interactive Plotly HTML file.

  • figureTitlePrefix (str) – Prefix used in figure titles.

  • axisLabelPrefix (str) – Prefix used for axis labels.

  • fileNamePrefix (str) – Prefix used for output filenames.

  • colorPaletteName (str) – Seaborn palette name for consistent class colors.

  • enableClusterMetrics (bool) – If True compute silhouette, Davies-Bouldin and Calinski-Harabasz scores and save them as JSON.

  • enableMisclassificationHighlight (bool) – If True generate an additional figure highlighting misclassified samples.

  • enableCentroidAnnotations (bool) – If True annotate cluster centroids with class names.

  • markerStyleCorrect (str) – Matplotlib marker for correct predictions.

  • markerStylePredicted (str) – Matplotlib marker for predicted-label plots.

  • markerStyleError (str) – Matplotlib marker for error highlights.

  • outputFileFormat (str) – File format used when saving figures (e.g., “pdf”, “png”).

  • customClassNames (list or None) – Optional explicit list of class names matching the sorted unique values in trueIdxSub.

  • perplexityMin (int) – Minimum perplexity allowed when adapting to nSamples.

  • perplexityMax (int) – Maximum perplexity allowed when adapting to nSamples.

  • annotationOffset (tuple) – Offset in points for centroid annotation text (x,y).

  • fontSizeTitle (int) – Font size for figure titles.

  • fontSizeAxis (int) – Font size for axis labels.

  • alphaCorrect (float) – Alpha (opacity) for correctly-classified points.

  • alphaError (float) – Alpha (opacity) for error points.

  • edgeColor (str) – Edge color for plotted markers.

  • edgeWidth (float) – Edge line width for plotted markers.

Returns:

If enableClusterMetrics is True, returns a dictionary containing computed cluster quality metrics (SilhouetteScore, DaviesBouldinIndex, CalinskiHarabaszScore, NumSamples, Perplexity). Otherwise returns None.

Return type:

dict or None

Example

from HMB.ExplainabilityHelper import TSNEFeaturesExplainability

metrics = TSNEFeaturesExplainability(
  featsSub=featuresArray,
  labelEncoder=le,
  nSamples=len(featuresArray),
  outDir=Path("./figures"),
  predIdxSub=preds,
  trueIdxSub=labels,
  exportInteractive=True
)
HMB.ExplainabilityHelper.UMAPFeaturesExplainability(featsSub, labelEncoder, nSamples, outDir, predIdxSub, trueIdxSub, numComponents=2, dpi=720, randomState=42, exportInteractive=False, figureTitlePrefix='UMAP of Features', axisLabelPrefix='UMAP Dimension', fileNamePrefix='UMAPFeatures', colorPaletteName='colorblind', enableClusterMetrics=True, enableMisclassificationHighlight=True, enableCentroidAnnotations=True, markerStyleCorrect='o', markerStylePredicted='^', markerStyleError='X', outputFileFormat='pdf', customClassNames=None, nNeighbors=15, minDist=0.1, metric='euclidean', annotationOffset=(8, -5), fontSizeTitle=16, fontSizeAxis=14, alphaCorrect=0.85, alphaError=0.9, edgeColor='white', edgeWidth=0.3)[source]

Create a set of publication-ready UMAP visualizations for feature embeddings and optionally compute cluster quality metrics.

The function produces several static figures saved to outDir:
  • Basic UMAP colored by true labels

  • Basic UMAP colored by predicted labels

  • Enhanced UMAP (true labels) with optional centroid annotations

  • Enhanced UMAP (predicted labels)

  • Side-by-side comparison of true vs predicted labels

  • Misclassification-highlighted view (optional)

  • Optional interactive Plotly HTML export (if exportInteractive and plotly installed)

Parameters:
  • featsSub (array-like) – Feature vectors to embed (n_samples x n_features).

  • labelEncoder (sklearn.preprocessing.LabelEncoder or None) – Optional encoder to map integer class indices back to human-readable class names. If None, integer class ids or customClassNames are used.

  • nSamples (int) – Number of samples in featsSub (used for metrics reporting).

  • outDir (pathlib.Path or str) – Directory where generated figures and JSON metrics will be saved.

  • predIdxSub (array-like) – Predicted class indices for each sample (length nSamples).

  • trueIdxSub (array-like) – Ground-truth class indices for each sample (length nSamples).

  • numComponents (int) – Dimensionality of the embedding (default: 2).

  • dpi (int) – DPI to use when saving figures (default: 720).

  • randomState (int) – Random seed controlling UMAP initialization (default: 42).

  • exportInteractive (bool) – If True, export an interactive Plotly HTML file.

  • figureTitlePrefix (str) – Prefix used in figure titles.

  • axisLabelPrefix (str) – Prefix used for axis labels.

  • fileNamePrefix (str) – Prefix used for output filenames.

  • colorPaletteName (str) – Seaborn palette name for consistent class colors.

  • enableClusterMetrics (bool) – If True compute silhouette, Davies-Bouldin and Calinski-Harabasz scores and save them as JSON.

  • enableMisclassificationHighlight (bool) – If True generate an additional figure highlighting misclassified samples.

  • enableCentroidAnnotations (bool) – If True annotate cluster centroids with class names.

  • markerStyleCorrect (str) – Matplotlib marker for correct predictions.

  • markerStylePredicted (str) – Matplotlib marker for predicted-label plots.

  • markerStyleError (str) – Matplotlib marker for error highlights.

  • outputFileFormat (str) – File format used when saving figures (e.g., “pdf”, “png”).

  • customClassNames (list or None) – Optional explicit list of class names matching the sorted unique values in trueIdxSub.

  • nNeighbors (int) – UMAP n_neighbors hyperparameter controlling local connectivity.

  • minDist (float) – UMAP min_dist hyperparameter controlling embedding tightness.

  • metric (str) – Distance metric passed to UMAP (default: “euclidean”).

  • annotationOffset (tuple) – Offset in points for centroid annotation text (x,y).

  • fontSizeTitle (int) – Font size for figure titles.

  • fontSizeAxis (int) – Font size for axis labels.

  • alphaCorrect (float) – Alpha (opacity) for correctly-classified points.

  • alphaError (float) – Alpha (opacity) for error points.

  • edgeColor (str) – Edge color for plotted markers.

  • edgeWidth (float) – Edge line width for plotted markers.

Returns:

If enableClusterMetrics is True, returns a dictionary containing computed cluster quality metrics (SilhouetteScore, DaviesBouldinIndex, CalinskiHarabaszScore, NumSamples, NNeighbors, MinDist, Metric). Otherwise returns None.

Return type:

dict or None

Example

from HMB.ExplainabilityHelper import UMAPFeaturesExplainability

metrics = UMAPFeaturesExplainability(
  featsSub=featuresArray,
  labelEncoder=le,
  nSamples=len(featuresArray),
  outDir=Path("./figures"),
  predIdxSub=preds,
  trueIdxSub=labels,
  exportInteractive=True
)
HMB.ExplainabilityHelper.TFGradCam(model, imgTensor, classIdx=None, lastConvLayerName=None)[source]

Compute Grad-CAM heatmap for imgTensor and target class index.

Parameters:
  • model (tensorflow.keras.Model) – Trained Keras model.

  • imgTensor (numpy.ndarray or tf.Tensor) – Shape (1,H,W,3) preprocessed input.

  • classIdx (int or None) – Target class index; if None uses model prediction.

  • lastConvLayerName (str|None) – Specify conv layer name; if None pick last Conv2D.

Returns.

heatmap (2D numpy array): normalized heatmap in [0,1].

Example

from HMB.ExplainabilityHelper import TFGradCam

model = ...  # Load or build model.
img = ...    # Load and preprocess image to shape (1, H, W, 3).
heatmap = TFGradCam(model, img, classIdx=2, lastConvLayerName=None)
HMB.ExplainabilityHelper.SaveTFGradCamsForSamples(model, imgPaths, sampleIndices, outFolder, imgSize=(512, 512), lastConvLayerName=None)[source]

Compute and save Grad-CAM overlays for the provided samples.

Parameters:
  • model (tensorflow.keras.Model) – Trained Keras model.

  • imgPaths (list) – List of image file paths in the same order as indices refer to.

  • sampleIndices (array-like) – Indices to visualize.

  • outFolder (str) – Output folder where overlays will be saved.

  • imgSize (tuple) – Size to resize images for model input.

  • lastConvLayerName (str) – Optional conv layer to use.

Example

from HMB.ExplainabilityHelper import SaveGradCamsForSamples

model = ...  # Load or build model.
imgPaths = [...]  # List of image file paths.
sampleIndices = [0, 5, 10]  # Indices of samples to visualize.
outFolder = "GradCAM_Overlays"

SaveGradCamsForSamples(
  model,
  imgPaths,
  sampleIndices,
  outFolder,
  imgSize=(512, 512),
  lastConvLayerName=None
)
HMB.ExplainabilityHelper.ModelPredictProba(model, xArray, device=None)[source]

Compute model probabilities for numpy input X using a PyTorch model.

Parameters:
  • model (Any) – PyTorch model or sklearn-like model with predict_proba.

  • xArray (numpy.ndarray) – Input features as numpy array (N, D).

  • device (str | None) – Optional device string (e.g., “cuda”, “cpu”). If None, uses model device.

Returns:

Probability predictions of shape (N, num_classes).

Return type:

numpy.ndarray

HMB.ExplainabilityHelper.ComputeShapValues(model, backgroundData, xData, featureNames=None, nsamples=100)[source]

Compute SHAP values for a model given a background and inputs.

Parameters:
  • model (Any) – PyTorch model or sklearn-like model.

  • backgroundData (numpy.ndarray) – Background dataset for SHAP baseline (N_bg, D).

  • xData (numpy.ndarray) – Input data to explain (N, D).

  • featureNames (List[str] | None) – Optional list of feature names for plotting.

  • nsamples (int) – Number of samples for KernelExplainer fallback (default: 100).

Returns:

SHAP explanation object (shap.Explanation or list of arrays).

Return type:

Any

HMB.ExplainabilityHelper.ShapSummaryPlot(shapValues, featureNames=None, show=False, savePath=None, dpi=720)[source]

Plot a SHAP summary plot and optionally save to disk.

Parameters:
  • shapValues (Any) – SHAP explanation object or values array.

  • featureNames (List[str] | None) – Optional list of feature names.

  • show (bool) – Whether to display the plot interactively (default: False).

  • savePath (str | None) – Optional path to save the figure (default: None).

  • dpi (int) – Dots per inch for saved figure resolution (default: 720).

HMB.ExplainabilityHelper.ExtractAttentionWeights(model, xArray, layerType='MultiheadAttention')[source]

Extract attention weight tensors from transformer-like modules in a model.

Parameters:
  • model (Any) – PyTorch model containing MultiheadAttention or TransformerEncoderLayer modules.

  • xArray (numpy.ndarray) – Input array to run a forward pass (shape depends on model).

  • layerType (str) – String hint for layer type (default: “MultiheadAttention”).

Returns:

List of attention weight arrays extracted from hooks.

Return type:

List[numpy.ndarray]

HMB.ExplainabilityHelper.IntegratedGradients(model, inputArray, targetLabel, baseline=None, steps=50, device=None)[source]

Compute naive integrated gradients attributions for a model and single input.

Parameters:
  • model (Any) – PyTorch model.

  • inputArray (numpy.ndarray) – Single input sample (D,) or (H, W, C) depending on model.

  • targetLabel (int) – Target class index for attribution.

  • baseline (numpy.ndarray | None) – Baseline input (same shape as inputArray). If None, uses zeros.

  • steps (int) – Number of interpolation steps (default: 50).

  • device (str | None) – Optional device string.

Returns:

Attribution map of same shape as inputArray.

Return type:

numpy.ndarray

HMB.ExplainabilityHelper.SmoothGrad(model, inputArray, targetLabel, stdevSpread=0.15, nSamples=25, device=None)[source]

Compute SmoothGrad by averaging IntegratedGradients on noisy inputs.

Parameters:
  • model (Any) – PyTorch model.

  • inputArray (numpy.ndarray) – Single input sample.

  • targetLabel (int) – Target class index.

  • stdevSpread (float) – Noise standard deviation as fraction of input range (default: 0.15).

  • nSamples (int) – Number of noisy samples to average (default: 25).

  • device (str | None) – Optional device string.

Returns:

Smoothed attribution map of same shape as inputArray.

Return type:

numpy.ndarray

HMB.ExplainabilityHelper.GradCam1D(model, inputArray, targetLabel, layerName=None, device=None)[source]

Compute a Grad-CAM-like 1D saliency map for convolutional models.

Parameters:
  • model (Any) – PyTorch model containing Conv1d layers.

  • inputArray (numpy.ndarray) – 1D input signal (L,) or (C, L).

  • targetLabel (int) – Target class index.

  • layerName (str | None) – Optional name of target Conv1d layer. If None, uses last Conv1d.

  • device (str | None) – Optional device string.

Returns:

1D saliency map normalized to [0, 1] and resampled to input length.

Return type:

numpy.ndarray

HMB.ExplainabilityHelper.FindCounterfactual(model, x0, targetClass, maxIters=200, learningRate=0.01, lambdaReg=0.01, device=None)[source]

Find a simple gradient-based counterfactual that changes the model prediction to a target class.

Parameters:
  • model (Any) – PyTorch model.

  • x0 (numpy.ndarray) – Original input sample.

  • targetClass (int) – Desired target class index.

  • maxIters (int) – Maximum optimization iterations (default: 200).

  • learningRate (float) – Learning rate for input optimization (default: 1e-2).

  • lambdaReg (float) – L2 regularization weight to penalize large changes (default: 0.01).

  • device (str | None) – Optional device string.

Returns:

(counterfactual_input, l2_distance) where counterfactual_input is a numpy array

and l2_distance is the Euclidean distance from the original input.

Return type:

tuple

HMB.ExplainabilityHelper.TrainSurrogateTree(model, xArray, maxDepth=3)[source]

Train a decision tree surrogate model on the predictions of a black-box model.

Parameters:
  • model (Any) – Black-box model (PyTorch or sklearn-like).

  • xArray (numpy.ndarray) – Input features (N, D).

  • maxDepth (int) – Maximum depth of the decision tree (default: 3).

Returns:

(trainedDecisionTree, textualRulesString).

Return type:

tuple

HMB.ExplainabilityHelper.ExplanationStability(shapValuesList)[source]

Compute the stability of explanations as average pairwise Spearman correlation.

Parameters:

shapValuesList (List[numpy.ndarray]) – List of explanation arrays (each shape D or flattened).

Returns:

Mean pairwise Spearman correlation (1.0 = perfectly stable).

Return type:

float

HMB.ExplainabilityHelper.DeletionFaithfulness(model, xSample, featureImportanceOrder, steps=10)[source]

Compute deletion faithfulness by progressively removing top features and measuring prediction drop.

Parameters:
  • model (Any) – PyTorch model or sklearn-like model.

  • xSample (numpy.ndarray) – Single input sample (D,).

  • featureImportanceOrder (List[int]) – List of feature indices sorted by importance (most important first).

  • steps (int) – Number of deletion steps (default: 10).

Returns:

(normalized_auc, probability_sequence) where normalized_auc is the area under the

probability-vs-removal curve normalized by the initial probability, and probability_sequence is the list of probabilities for the original predicted class at each step.

Return type:

tuple