{"id":45467933,"url":"https://github.com/desenyon/scope-rx","last_synced_at":"2026-02-22T10:04:03.779Z","repository":{"id":281740093,"uuid":"946284653","full_name":"desenyon/scope-rx","owner":"desenyon","description":"ScopeRX is a comprehensive Python library for explaining and interpreting neural network predictions. It provides state-of-the-art attribution methods, evaluation metrics, and visualization tools - all unified under a simple, intuitive API.","archived":false,"fork":false,"pushed_at":"2026-02-15T06:21:34.000Z","size":124,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-15T12:31:47.756Z","etag":null,"topics":["library","neural-networks","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/desenyon.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-10T22:45:14.000Z","updated_at":"2026-02-15T06:25:13.000Z","dependencies_parsed_at":"2025-03-10T23:11:30.809Z","dependency_job_id":"b6e60153-f7e3-45fe-a0cc-84be1f4a01b3","html_url":"https://github.com/desenyon/scope-rx","commit_stats":null,"previous_names":["arcoson/gradientvis","xcalen/gradientvis","desenyon/gradientvis","desenyon/scope-rx"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/desenyon/scope-rx","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/desenyon%2Fscope-rx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/desenyon%2Fscope-rx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/desenyon%2Fscope-rx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/desenyon%2Fscope-rx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/desenyon","download_url":"https://codeload.github.com/desenyon/scope-rx/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/desenyon%2Fscope-rx/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29708861,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-22T05:59:28.568Z","status":"ssl_error","status_checked_at":"2026-02-22T05:58:46.208Z","response_time":110,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["library","neural-networks","python"],"created_at":"2026-02-22T10:04:02.515Z","updated_at":"2026-02-22T10:04:03.765Z","avatar_url":"https://github.com/desenyon.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ScopeRX\n\n**Neural Network Explainability and Interpretability Library**\n\n[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![CI](https://github.com/xcalen/scope-rx/actions/workflows/ci.yml/badge.svg)](https://github.com/xcalen/scope-rx/actions/workflows/ci.yml) [![Codecov](https://codecov.io/gh/xcalen/scope-rx/branch/main/graph/badge.svg)](https://codecov.io/gh/xcalen/scope-rx)\n\nScopeRX is a comprehensive, production-grade Python library for explaining and interpreting neural network predictions. It provides state-of-the-art attribution methods, evaluation metrics, and visualization tools - all unified under a simple, intuitive API.\n\n## What's New\n\n### v2.0.1\n- **`torchvision` promoted to core dependency** — no longer requires `pip install scope-rx[full]`.\n- **`KernelSHAP` / `LIME`**: Fixed all-zero attributions on low-complexity images (SLIC grid fallback + Ridge label scaling).\n- **`GuidedBackprop`**: Input tensor is cloned before `requires_grad`, preventing mutation of caller's tensor.\n- **`MeaningfulPerturbation`**: Validated input detached before optimisation to avoid gradient graph conflicts.\n- **Metrics**: `aopc_score` returns a writeable array; `max_sensitivity` always returns a plain `float`.\n- **Tests**: New end-to-end integration suite (`test/test_everything.py`) with correctness assertions for all 15 methods.\n\n### v2.0.0\n- **Type Safety**: Fully typed codebase with `mypy` compliance.\n- **Production Grade**: Enhanced stability, error handling, and performance optimizations.\n- **CI/CD**: Automated testing and linting pipelines.\n- **Improved Methods**: Refactored `KernelSHAP`, `RISE`, and Attention methods for better accuracy and speed.\n\n## Features\n\n- **15+ Explanation Methods**: From classic GradCAM to cutting-edge RISE and attention methods\n- **Unified API**: One interface to rule them all - switch between methods with a single parameter\n- **Evaluation Metrics**: Faithfulness, sensitivity, and stability metrics to quantify explanation quality\n- **Beautiful Visualizations**: Publication-ready plots with minimal code\n- **Model Agnostic**: Works with any PyTorch model architecture\n- **Transformer Support**: Dedicated attention visualization for Vision Transformers\n- **CLI Tool**: Generate explanations from the command line\n\n## Installation\n\n```bash\npip install scope-rx\n```\n\n**With optional dependencies:**\n\n```bash\n# For interactive Plotly visualizations\npip install scope-rx[interactive]\n\n# For development\npip install scope-rx[dev]\n\n# Full installation with all extras (transformers, SHAP, captum)\npip install scope-rx[full]\n```\n\n\u003e **Note:** `torchvision` is a core dependency and is installed automatically with `pip install scope-rx`.\n\n## Quick Start\n\n```python\nfrom scope_rx import ScopeRX\nimport torch\nimport torchvision.models as models\n\n# Load your model\nmodel = models.resnet50(pretrained=True)\nmodel.eval()\n\n# Create explainer\nexplainer = ScopeRX(model)\n\n# Generate explanation\nresult = explainer.explain(\n    input_tensor,\n    method='gradcam',\n    target_class=predicted_class\n)\n\n# Visualize\nresult.visualize()\n\n# Or save to file\nresult.save(\"explanation.png\")\n```\n\n## Available Methods\n\n### Gradient-Based Methods\n\n| Method                   | Description                                | Use Case                            |\n| ------------------------ | ------------------------------------------ | ----------------------------------- |\n| `gradcam`              | Gradient-weighted Class Activation Mapping | General CNN visualization           |\n| `gradcam++`            | Improved GradCAM with better localization  | Multiple object instances           |\n| `scorecam`             | Score-based CAM (gradient-free)            | When gradients are unstable         |\n| `layercam`             | Layer-wise CAM                             | Fine-grained attribution            |\n| `smoothgrad`           | Noise-smoothed gradients                   | Reducing gradient noise             |\n| `integrated_gradients` | Axiomatic attribution method               | Theoretically grounded explanations |\n| `vanilla`              | Simple input gradients                     | Quick baseline                      |\n| `guided_backprop`      | Guided backpropagation                     | High-resolution visualization       |\n\n### Perturbation-Based Methods\n\n| Method                      | Description                    | Use Case                         |\n| --------------------------- | ------------------------------ | -------------------------------- |\n| `occlusion`               | Sliding window occlusion       | Understanding spatial importance |\n| `rise`                    | Randomized Input Sampling      | Black-box models                 |\n| `meaningful_perturbation` | Optimized minimal perturbation | Finding minimal explanations     |\n\n### Model-Agnostic Methods\n\n| Method          | Description                      | Use Case                       |\n| --------------- | -------------------------------- | ------------------------------ |\n| `kernel_shap` | Kernel SHAP approximation        | Shapley value estimation       |\n| `lime`        | Local Interpretable Explanations | Interpretable local surrogates |\n\n### Attention-Based Methods (for Transformers)\n\n| Method                | Description                  | Use Case                      |\n| --------------------- | ---------------------------- | ----------------------------- |\n| `attention_rollout` | Attention weight aggregation | Vision Transformers           |\n| `attention_flow`    | Attention flow propagation   | Understanding attention paths |\n| `raw_attention`     | Raw attention weights        | Quick attention inspection    |\n\n## Compare Methods\n\n```python\nfrom scope_rx import ScopeRX\n\nexplainer = ScopeRX(model)\n\n# Compare multiple methods at once\nresults = explainer.compare_methods(\n    input_tensor,\n    methods=['gradcam', 'smoothgrad', 'integrated_gradients', 'rise'],\n    target_class=predicted_class\n)\n\n# Visualize comparison\nfrom scope_rx.visualization import plot_comparison\nplot_comparison({name: r.attribution for name, r in results.items()})\n```\n\n## Evaluate Explanations\n\n```python\nfrom scope_rx.metrics import (\n    faithfulness_score,\n    insertion_deletion_auc,\n    sensitivity_score,\n    stability_score\n)\n\n# Faithfulness: Does the explanation reflect model behavior?\nfaith = faithfulness_score(model, input_tensor, attribution, target_class=0)\n\n# Insertion/Deletion: How does model output change as we add/remove important features?\nscores = insertion_deletion_auc(model, input_tensor, attribution, target_class=0)\nprint(f\"Insertion AUC: {scores['insertion_auc']:.3f}\")\nprint(f\"Deletion AUC: {scores['deletion_auc']:.3f}\")\n\n# Sensitivity: Are explanations sensitive to meaningful changes?\nsens = sensitivity_score(explainer, input_tensor, target_class=0)\n\n# Stability: Are explanations stable across similar inputs?\nstab = stability_score(explainer, input_tensor, target_class=0)\n```\n\n## Visualization\n\n```python\nfrom scope_rx.visualization import (\n    plot_attribution,\n    plot_comparison,\n    overlay_attribution,\n    create_interactive_plot,\n    export_visualization\n)\n\n# Simple plot\nplot_attribution(attribution, image=original_image)\n\n# Interactive Plotly plot\nfig = create_interactive_plot(attribution, image=original_image)\nfig.show()\n\n# Export to various formats\nexport_visualization(attribution, \"output.png\", colormap=\"jet\")\nexport_visualization(attribution, \"output.npy\")  # Raw numpy array\n```\n\n## Command Line Interface\n\n```bash\n# Generate explanation\nscope-rx explain image.jpg --model resnet50 --method gradcam --output heatmap.png\n\n# Compare methods\nscope-rx compare image.jpg --model resnet50 --methods gradcam,smoothgrad,rise\n\n# List available methods\nscope-rx list-methods\n\n# Show model layers (for layer selection)\nscope-rx show-layers --model resnet50\n```\n\n## Advanced Usage\n\n### Custom Target Layers\n\n```python\nfrom scope_rx import GradCAM\n\n# Specify exact layer\nexplainer = GradCAM(model, target_layer=\"layer4.1.conv2\")\n```\n\n### Custom Baselines for Integrated Gradients\n\n```python\nfrom scope_rx import IntegratedGradients\n\n# Use different baselines\nexplainer = IntegratedGradients(\n    model,\n    n_steps=50,\n    baseline=\"blur\"  # Options: \"zero\", \"random\", \"blur\"\n)\n```\n\n### Batch Processing\n\n```python\nfrom scope_rx import ScopeRX\nfrom scope_rx.utils import preprocess_image\nfrom pathlib import Path\n\nexplainer = ScopeRX(model)\n\n# Process multiple images\nfor image_path in image_paths:\n    input_tensor = preprocess_image(image_path)\n    result = explainer.explain(input_tensor, method='gradcam')\n    result.save(f\"explanations/{Path(image_path).stem}.png\")\n```\n\n### Using Individual Explainers\n\n```python\nfrom scope_rx import GradCAM, SmoothGrad, RISE\n\n# Use specific explainer directly\ngradcam = GradCAM(model, target_layer=\"layer4\")\nresult = gradcam.explain(input_tensor, target_class=0)\n\n# SmoothGrad with custom parameters\nsmoothgrad = SmoothGrad(model, n_samples=50, noise_level=0.2)\nresult = smoothgrad.explain(input_tensor, target_class=0)\n```\n\n## Testing\n\n```bash\n# Run the comprehensive end-to-end test suite (CLI + Python API + metrics + visualization)\npython test/test_everything.py\n\n# Run unit tests with pytest\npytest tests/\n\n# Run with coverage\npytest tests/ --cov=scope_rx --cov-report=html\n\n# Run specific test module\npytest tests/test_gradient_methods.py -v\n```\n\n## Documentation\n\nFor full documentation, visit our [documentation site](https://github.com/xcalen/scope-rx/docs).\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Citation\n\nIf you use ScopeRX in your research, please cite:\n\n```bibtex\n@software{scoperx2024,\n  title = {ScopeRX: Neural Network Explainability Library},\n  author = {XCALEN},\n  year = {2024},\n  url = {https://github.com/xcalen/scope-rx}\n}\n```\n\n## Acknowledgments\n\nScopeRX builds upon the excellent work of the interpretability research community. Special thanks to the authors of:\n\n- GradCAM, GradCAM++, ScoreCAM, LayerCAM\n- SHAP and LIME\n- Integrated Gradients\n- RISE\n- And many others who have contributed to the field of explainable AI\n\n---\n\n**Made with love by Desenyon**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdesenyon%2Fscope-rx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdesenyon%2Fscope-rx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdesenyon%2Fscope-rx/lists"}