adaptshot 0.1.0__tar.gz → 0.2.0.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. adaptshot-0.2.0.dev0/LICENSE +21 -0
  2. adaptshot-0.2.0.dev0/PKG-INFO +325 -0
  3. adaptshot-0.2.0.dev0/README.md +280 -0
  4. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/pyproject.toml +20 -7
  5. adaptshot-0.2.0.dev0/src/adaptshot/__init__.py +44 -0
  6. adaptshot-0.2.0.dev0/src/adaptshot/config/settings.py +101 -0
  7. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/core/act.py +24 -5
  8. adaptshot-0.2.0.dev0/src/adaptshot/core/backends/__init__.py +11 -0
  9. adaptshot-0.2.0.dev0/src/adaptshot/core/backends/onnx_backend.py +95 -0
  10. adaptshot-0.2.0.dev0/src/adaptshot/core/calibration.py +304 -0
  11. adaptshot-0.2.0.dev0/src/adaptshot/core/conformal.py +436 -0
  12. adaptshot-0.2.0.dev0/src/adaptshot/core/contrastive.py +512 -0
  13. adaptshot-0.2.0.dev0/src/adaptshot/core/explain.py +586 -0
  14. adaptshot-0.2.0.dev0/src/adaptshot/core/extractor.py +274 -0
  15. adaptshot-0.2.0.dev0/src/adaptshot/core/learner.py +1643 -0
  16. adaptshot-0.2.0.dev0/src/adaptshot/core/similarity.py +240 -0
  17. adaptshot-0.2.0.dev0/src/adaptshot/core/uncertainty.py +569 -0
  18. adaptshot-0.2.0.dev0/src/adaptshot/data/__init__.py +5 -0
  19. adaptshot-0.2.0.dev0/src/adaptshot/data/mobilenet_v3_small.onnx +0 -0
  20. adaptshot-0.2.0.dev0/src/adaptshot/data/mobilenet_v3_small.onnx.data +0 -0
  21. adaptshot-0.2.0.dev0/src/adaptshot/data/resnet18.onnx +0 -0
  22. adaptshot-0.2.0.dev0/src/adaptshot/data/resnet18.onnx.data +0 -0
  23. adaptshot-0.2.0.dev0/src/adaptshot/studio/__init__.py +5 -0
  24. adaptshot-0.2.0.dev0/src/adaptshot/studio/app.py +1028 -0
  25. adaptshot-0.2.0.dev0/src/adaptshot/studio/utils.py +794 -0
  26. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/training/feedback_router.py +7 -4
  27. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/training/finetune.py +56 -21
  28. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/training/up_ugf.py +41 -14
  29. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/ui/app.py +13 -11
  30. adaptshot-0.2.0.dev0/src/adaptshot/utils/exceptions.py +21 -0
  31. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/utils/io.py +2 -2
  32. adaptshot-0.2.0.dev0/src/adaptshot/utils/migrations.py +39 -0
  33. adaptshot-0.2.0.dev0/src/adaptshot/utils/profiling.py +166 -0
  34. adaptshot-0.2.0.dev0/src/adaptshot.egg-info/PKG-INFO +325 -0
  35. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot.egg-info/SOURCES.txt +27 -1
  36. adaptshot-0.2.0.dev0/src/adaptshot.egg-info/entry_points.txt +2 -0
  37. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot.egg-info/requires.txt +12 -3
  38. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/tests/test_calibration.py +4 -5
  39. adaptshot-0.2.0.dev0/tests/test_conformal.py +132 -0
  40. adaptshot-0.2.0.dev0/tests/test_contrastive.py +100 -0
  41. adaptshot-0.2.0.dev0/tests/test_exceptions.py +178 -0
  42. adaptshot-0.2.0.dev0/tests/test_explain.py +173 -0
  43. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/tests/test_extractor.py +44 -9
  44. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/tests/test_feedback_router.py +0 -1
  45. adaptshot-0.2.0.dev0/tests/test_learner_integration.py +183 -0
  46. adaptshot-0.2.0.dev0/tests/test_persistence.py +124 -0
  47. adaptshot-0.2.0.dev0/tests/test_release_metadata.py +17 -0
  48. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/tests/test_similarity.py +0 -1
  49. adaptshot-0.2.0.dev0/tests/test_studio_utils.py +106 -0
  50. adaptshot-0.2.0.dev0/tests/test_uncertainty.py +156 -0
  51. adaptshot-0.1.0/LICENSE +0 -1
  52. adaptshot-0.1.0/PKG-INFO +0 -289
  53. adaptshot-0.1.0/README.md +0 -250
  54. adaptshot-0.1.0/src/adaptshot/__init__.py +0 -19
  55. adaptshot-0.1.0/src/adaptshot/config/settings.py +0 -55
  56. adaptshot-0.1.0/src/adaptshot/core/calibration.py +0 -184
  57. adaptshot-0.1.0/src/adaptshot/core/extractor.py +0 -70
  58. adaptshot-0.1.0/src/adaptshot/core/learner.py +0 -328
  59. adaptshot-0.1.0/src/adaptshot/core/similarity.py +0 -118
  60. adaptshot-0.1.0/src/adaptshot/utils/__init__.py +0 -0
  61. adaptshot-0.1.0/src/adaptshot.egg-info/PKG-INFO +0 -289
  62. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/setup.cfg +0 -0
  63. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/config/__init__.py +0 -0
  64. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/core/__init__.py +0 -0
  65. {adaptshot-0.1.0/src/adaptshot/data → adaptshot-0.2.0.dev0/src/adaptshot/evaluation}/__init__.py +0 -0
  66. {adaptshot-0.1.0/src/adaptshot/evaluation → adaptshot-0.2.0.dev0/src/adaptshot/training}/__init__.py +0 -0
  67. {adaptshot-0.1.0/src/adaptshot/training → adaptshot-0.2.0.dev0/src/adaptshot/ui}/__init__.py +0 -0
  68. {adaptshot-0.1.0/src/adaptshot/ui → adaptshot-0.2.0.dev0/src/adaptshot/utils}/__init__.py +0 -0
  69. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot/utils/determinism.py +0 -0
  70. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot.egg-info/dependency_links.txt +0 -0
  71. {adaptshot-0.1.0 → adaptshot-0.2.0.dev0}/src/adaptshot.egg-info/top_level.txt +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Johnson Christopher Hassan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,325 @@
1
+ Metadata-Version: 2.4
2
+ Name: adaptshot
3
+ Version: 0.2.0.dev0
4
+ Summary: Human-aligned few-shot vision learning for resource-constrained environments
5
+ Author-email: Johnson Christopher Hassan <johnson2006christopher@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/johnson2006christopher/adaptshot
8
+ Project-URL: Documentation, https://github.com/johnson2006christopher/adaptshot/docs
9
+ Project-URL: Repository, https://github.com/johnson2006christopher/adaptshot.git
10
+ Project-URL: Bug Tracker, https://github.com/johnson2006christopher/adaptshot/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=1.24.0
22
+ Requires-Dist: Pillow>=9.0.0
23
+ Provides-Extra: torch
24
+ Requires-Dist: torch>=2.0.0; extra == "torch"
25
+ Requires-Dist: torchvision>=0.15.0; extra == "torch"
26
+ Provides-Extra: faiss
27
+ Requires-Dist: faiss-cpu>=1.7.4; extra == "faiss"
28
+ Provides-Extra: ui
29
+ Requires-Dist: gradio>=3.50.0; extra == "ui"
30
+ Provides-Extra: gui
31
+ Requires-Dist: gradio>=3.50.0; extra == "gui"
32
+ Requires-Dist: pandas>=2.0.0; extra == "gui"
33
+ Requires-Dist: onnx>=1.16.0; extra == "gui"
34
+ Requires-Dist: onnxscript>=0.3.0; extra == "gui"
35
+ Requires-Dist: onnxruntime>=1.14.0; extra == "gui"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
38
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
39
+ Requires-Dist: mypy>=1.5.0; extra == "dev"
40
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
41
+ Requires-Dist: pre-commit>=3.4.0; extra == "dev"
42
+ Provides-Extra: all
43
+ Requires-Dist: adaptshot[dev,faiss,gui,torch]; extra == "all"
44
+ Dynamic: license-file
45
+
46
+
47
+ <div align="center">
48
+
49
+ <img src="docs/images/adaptshot-logo.png" width="300" alt="AdaptShot Logo">
50
+
51
+ # AdaptShot
52
+
53
+ **Human-Aligned Few-Shot Vision Learning for Resource-Constrained Environments**
54
+
55
+ [![PyPI](https://img.shields.io/pypi/v/adaptshot.svg)](https://pypi.org/project/adaptshot/)
56
+ [![GitHub Release](https://img.shields.io/github/v/release/johnson2006christopher/adaptshot?label=GitHub%20Release)](https://github.com/johnson2006christopher/adaptshot/releases)
57
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/adaptshot?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/adaptshot)
58
+ [![Python](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/)
59
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
60
+ [![Docs](https://img.shields.io/badge/docs-MkDocs-blue)](https://johnson2006christopher.github.io/adaptshot/)
61
+ [![Built in Tanzania](https://img.shields.io/badge/Built%20in-Tanzania%20🇹🇿-gold.svg)](https://en.wikipedia.org/wiki/Tanzania)
62
+ [![Code Style: Ruff](https://img.shields.io/badge/code%20style-ruff-black)](https://github.com/astral-sh/ruff)
63
+ [![Type Checked: mypy](https://img.shields.io/badge/type--checked-mypy-blue)](https://mypy-lang.org/)
64
+
65
+ ---
66
+
67
+ **Documentation**: [https://johnson2006christopher.github.io/adaptshot/](https://johnson2006christopher.github.io/adaptshot/)
68
+
69
+ **Source Code**: [https://github.com/johnson2006christopher/adaptshot](https://github.com/johnson2006christopher/adaptshot)
70
+
71
+ ---
72
+
73
+ AdaptShot is a high-performance, CPU-optimized, human-in-the-loop few-shot vision library. It is designed to learn from every human correction, guarantee calibrated uncertainty, and run deterministically on edge hardware with minimal resources.
74
+
75
+ v0.2.0-dev is the current release, hardened with 92 regression tests, strict type-checking, and a comprehensive benchmark harness. Built in Tanzania by a self-taught engineer with nothing but a laptop and determination.
76
+
77
+ </div>
78
+
79
+ ## 🚀 Key Features
80
+
81
+ * **CPU-First by Design**: Optimized for low-latency inference on standard CPUs, requiring less than 250MB of RAM.
82
+ * **Trustworthy & Calibrated**: Built-in **Expected Calibration Error (ECE)** minimization and **conformal prediction** with finite-sample coverage guarantees.
83
+ * **Human-in-the-Loop**: Integrated **FeedbackRouter** for real-time model adaptation through human expert corrections.
84
+ * **Continual Learning**: Implements **head-only CA-EWC** (Fisher-regularized classification head fine-tuning, ~2K parameters) and **UP-UGF** (Uncertainty-Guided Forgetting with LSH-accelerated redundancy scoring) for stable, long-term learning without catastrophic forgetting.
85
+ * **Multi-Signal Uncertainty**: Epistemic (stochastic embedding perturbation sensitivity), aleatoric (k-NN entropy), and distributional (shrinkage-regularized Mahalanobis distance) uncertainty quantification with OOD detection. *(Full MC Dropout planned for future torch-dependent release.)*
86
+ * **Explainable AI**: Embedding-space feature attribution (which support examples influenced the prediction), confidence decomposition with historical penalty tracking, counterfactual explanations, and per-dimension saliency analysis.
87
+ * **Contrastive Prototypes**: Gradient-trained class representations via InfoNCE contrastive loss with 2-layer MLP projection head and EMA momentum prototype refinement.
88
+ * **Release Hardened**: Zero-config API, strict type safety, and a comprehensive benchmark harness for review and deployment readiness.
89
+ * **Deterministic**: Guaranteed reproducible results across different runs and hardware through strict seed management.
90
+
91
+ ---
92
+
93
+ ## 🧭 Why AdaptShot?
94
+
95
+ In many real-world scenarios—from rural clinics in Tanzania to remote agricultural fields—AI must operate under extreme constraints: sparse data, no GPU access, and limited connectivity.
96
+
97
+ AdaptShot addresses these challenges by prioritizing **efficiency**, **transparency**, and **human collaboration**. It turns the constraint of small data into an opportunity for high-quality, human-guided learning.
98
+
99
+ ---
100
+
101
+ ## 📦 Installation
102
+
103
+ <div class="termy">
104
+
105
+ ```bash
106
+ $ pip install adaptshot
107
+
108
+ ---> 100%
109
+ ```
110
+
111
+ </div>
112
+
113
+ **Core dependencies**: numpy, Pillow (~15 MB total). PyTorch is **optional** — install it only if you need training/fine-tuning:
114
+
115
+ ```bash
116
+ pip install "adaptshot[torch]" # adds PyTorch + torchvision for training
117
+ ```
118
+
119
+ > **Fast install**: The base library installs in under 60 seconds on standard connections — no GPU drivers, no CUDA, no 2 GB downloads.
120
+
121
+ ### Optional Dependencies
122
+
123
+ AdaptShot provides optional extras for specialized workflows. The native Python API remains the source of truth; the GUI is an optional wrapper around it:
124
+
125
+ * **PyTorch (Training)**: `pip install "adaptshot[torch]"` (Required for CA-EWC fine-tuning and custom backbones)
126
+ * **FAISS Acceleration**: `pip install "adaptshot[faiss]"` (Recommended for support sets >100 images)
127
+ * **Gradio UI**: `pip install "adaptshot[ui]"` (For interactive pilots and human-in-the-loop dashboards)
128
+ * **Studio GUI**: `pip install "adaptshot[gui]"` (For the offline, folder-aware AdaptShot Studio workspace)
129
+ * **Development**: `pip install "adaptshot[dev]"` (For contributors: testing, linting, and benchmarks)
130
+
131
+ ---
132
+
133
+ ## 💡 Quick Start
134
+
135
+ ### Create a Learner and Predict
136
+
137
+ It's as simple as initializing the `FewShotLearner`, loading your support images, and calling `predict()`.
138
+
139
+ ```python
140
+ from adaptshot import FewShotLearner
141
+ from adaptshot.config.settings import AdaptShotConfig
142
+
143
+ # 1. Configure for your environment
144
+ config = AdaptShotConfig(
145
+ backbone="resnet18",
146
+ device="cpu",
147
+ max_buffer_size=100
148
+ )
149
+
150
+ # 2. Initialize the learner
151
+ learner = FewShotLearner(config=config)
152
+
153
+ # 3. Load support set (examples the model learns from)
154
+ image_paths = ["data/healthy_leaf.jpg", "data/blighted_leaf.jpg"]
155
+ labels = ["healthy", "blight"]
156
+ learner.load_support_images(image_paths, labels)
157
+
158
+ # 4. Predict on a new image
159
+ result = learner.predict("data/query.jpg")
160
+
161
+ print(f"Prediction: {result.prediction}")
162
+ print(f"Confidence: {result.calibrated_confidence:.2%}")
163
+
164
+ # 5. Handle uncertainty
165
+ if result.uncertainty_flag:
166
+ print("⚠️ Model is unsure. Routing for human review...")
167
+ ```
168
+
169
+ ---
170
+
171
+ ## 🆕 What's New in v0.2.0
172
+
173
+ - **Conformal Prediction**: Distribution-free prediction sets with true leave-one-out calibration guaranteeing finite-sample coverage at configurable significance levels
174
+ - **Contrastive Prototype Learning**: Gradient-trained InfoNCE class prototypes with 2-layer MLP projection head (full backpropagation through W1/b1/W2/b2)
175
+ - **Advanced Uncertainty**: Three complementary signals — epistemic (stochastic perturbation sensitivity), aleatoric (k-NN entropy), and distributional (shrinkage-regularized Mahalanobis OOD) — fused with mode-gated computation
176
+ - **XAI Explainability**: Embedding-space feature attribution, confidence decomposition with historical penalty tracking, counterfactual analysis, and per-dimension saliency
177
+ - **Cross-conformal prediction mode**: K-fold cross-conformal quantile averaging for more stable prediction sets
178
+ - **Bootstrap Temperature Calibration**: Autonomous LOO grid-search temperature optimization for cold-start scenarios
179
+ - **UP-UGF LSH Acceleration**: Approximate O(N log N) redundancy scoring via random projection locality-sensitive hashing for large buffers (>100 examples)
180
+ - **Memory Profiling**: `MemoryTracker` with tracemalloc + psutil instrumentation for verifying <250MB RAM operation
181
+ - **miniImageNet Benchmarks**: Standard few-shot benchmarks with baseline references (Prototypical Networks, Matching Networks, MAML)
182
+ - **ONNX Export**: Bundled backbone export script with SHA-256 verification for torch-free inference
183
+ - **ACT Symmetric Updates**: Mean-reverting threshold adaptation prevents monotonic drift in autonomous operation
184
+ - **37 new tests** (92 total) across conformal, contrastive, uncertainty, and explainability modules
185
+ - **12 new documentation pages**: Architecture deep-dive, algorithm theory, API reference, 5 tutorials, 2 GUI guides
186
+
187
+ ## 🛠️ Configuration
188
+
189
+ AdaptShot uses a strictly typed, immutable `AdaptShotConfig` to ensure reproducibility.
190
+
191
+ ### Core Execution
192
+
193
+ | Parameter | Type | Default | Description |
194
+ | :--- | :--- | :--- | :--- |
195
+ | `backbone` | `str` | `"resnet18"` | Feature extractor (`resnet18` or `mobilenet_v3_small`) |
196
+ | `device` | `str` | `"cpu"` | Execution device (`cpu`, `cuda`, or `mps`) |
197
+ | `seed` | `int` | `42` | Random seed for deterministic reproducibility |
198
+ | `verbose` | `bool` | `True` | Enable INFO-level logging |
199
+
200
+ ### Few-Shot Learning
201
+
202
+ | Parameter | Type | Default | Description |
203
+ | :--- | :--- | :--- | :--- |
204
+ | `n_way` | `int` | `5` | Number of classes per episode |
205
+ | `k_shot` | `int` | `10` | Support examples per class |
206
+ | `query_size` | `int` | `15` | Query examples per class for evaluation |
207
+
208
+ ### Similarity & Inference
209
+
210
+ | Parameter | Type | Default | Description |
211
+ | :--- | :--- | :--- | :--- |
212
+ | `similarity_metric` | `str` | `"euclidean"` | Distance metric (`cosine` or `euclidean`) |
213
+ | `inference_mode` | `str` | `"prototypical"` | Classification mode (`nearest_neighbor`, `prototypical`, or `contrastive`) |
214
+ | `use_faiss` | `bool` | `False` | Enable FAISS-CPU acceleration for large support sets |
215
+ | `faiss_nprobe` | `int` | `8` | FAISS IVF index probing depth |
216
+
217
+ ### Energy-Aware Inference
218
+
219
+ | Parameter | Type | Default | Description |
220
+ | :--- | :--- | :--- | :--- |
221
+ | `eco_mode` | `bool` | `False` | Enable energy-saving early-exit thresholds |
222
+ | `early_exit_threshold` | `float` | `0.95` | Confidence threshold for early-exit (0.5-1.0) |
223
+
224
+ ### Calibration & Uncertainty
225
+
226
+ | Parameter | Type | Default | Description |
227
+ | :--- | :--- | :--- | :--- |
228
+ | `calibration_method` | `str` | `"temperature"` | Method: `temperature`, `scaling_binning`, `conformal`, or `none` |
229
+ | `ece_n_bins` | `int` | `15` | Bins for Expected Calibration Error |
230
+ | `calibration_eval_bins` | `int` | `100` | Bins for calibration evaluation |
231
+ | `temperature_init` | `float` | `1.0` | Initial temperature scaling parameter |
232
+ | `recalibrate_after_feedback` | `bool` | `True` | Recalibrate after each human correction |
233
+
234
+ ### OOD Detection
235
+
236
+ | Parameter | Type | Default | Description |
237
+ | :--- | :--- | :--- | :--- |
238
+ | `enable_ood_detection` | `bool` | `True` | Flag images outside known support distribution |
239
+ | `ood_threshold_quantile` | `float` | `0.98` | Quantile threshold for OOD rejection (0.5-1.0) |
240
+ | `ood_absolute_min_distance` | `float` | `0.25` | Minimum absolute distance for OOD flagging |
241
+
242
+ ### Memory Management
243
+
244
+ | Parameter | Type | Default | Description |
245
+ | :--- | :--- | :--- | :--- |
246
+ | `max_buffer_size` | `int` | `100` | Maximum replay buffer capacity (enforced by UP-UGF) |
247
+ | `log_dir` | `Optional[str]` | `None` | Optional log output directory |
248
+
249
+ ### Advanced Algorithms (v0.2.0)
250
+
251
+ | Parameter | Type | Default | Description |
252
+ | :--- | :--- | :--- | :--- |
253
+ | `conformal_alpha` | `float` | `0.05` | Significance level for conformal prediction sets (0.01-0.50) |
254
+ | `conformal_mode` | `str` | `"split"` | Conformal prediction mode (`split` or `cross`) |
255
+ | `uncertainty_mode` | `str` | `"ensemble"` | Uncertainty mode (`mcdropout`, `entropy`, `mahalanobis`, or `ensemble`) |
256
+ | `explainability_enabled` | `bool` | `True` | Enable XAI explainability for predictions |
257
+
258
+ ---
259
+
260
+ ## ☁️ Deployment
261
+
262
+ ### Cloud Environments
263
+ AdaptShot is ideal for cost-effective cloud deployments on standard CPU instances (e.g., AWS `t3.medium`, GCP `e2-standard-2`). Since it doesn't require GPUs, you can significantly reduce operational costs while maintaining high-throughput inference.
264
+
265
+ ### On-Premise & Edge
266
+ Designed for the edge, AdaptShot runs seamlessly on:
267
+ * **Single Board Computers**: Raspberry Pi 4+, Jetson Nano (CPU mode).
268
+ * **Legacy Hardware**: Older laptops and desktops with limited RAM.
269
+ * **Offline Stations**: Fully functional without internet access once the backbone weights are cached.
270
+
271
+ ---
272
+
273
+ ## 🤝 Contributing
274
+
275
+ We welcome contributions of all kinds! Whether you're fixing a bug, adding a new backbone, or improving documentation.
276
+
277
+ 1. Check the [Contributing Guidelines](CONTRIBUTING.md).
278
+ 2. Install development dependencies: `pip install -e ".[dev]"`.
279
+ 3. Run tests to ensure everything is working: `pytest tests/`.
280
+ 4. Submit a Pull Request.
281
+
282
+ ---
283
+
284
+ ## 📜 License
285
+
286
+ AdaptShot is open-source software licensed under the **[MIT License](LICENSE)**.
287
+
288
+ ---
289
+
290
+ ## 👤 About the Creator
291
+
292
+ <div align="center">
293
+ <img src="docs/images/johnson.jpeg" width="150" style="border-radius: 50%;" alt="Johnson Christopher Hassan">
294
+
295
+ **Johnson Christopher Hassan**
296
+
297
+ *Vision AI Researcher & Software Engineer*
298
+
299
+ Built in Mbeya, Tanzania 🇹🇿
300
+
301
+ [GitHub](https://github.com/johnson2006christopher) | [LinkedIn](https://www.linkedin.com/in/johnson-christopher-hassan) | [Email](mailto:johnson2006christopher@gmail.com)
302
+
303
+ </div>
304
+
305
+ ---
306
+
307
+ <div align="center">
308
+ <p><i>"The best AI doesn't guess confidently. It learns humbly, admits uncertainty, and improves through every human correction."</i></p>
309
+ </div>
310
+
311
+ ---
312
+
313
+ ## 🔍 Summary of Key Updates
314
+
315
+ | Change | Why It Matters |
316
+ |--------|---------------|
317
+ | ✅ Added **GitHub Release badge** | Points to the eventual packaged release assets |
318
+ | ✅ Updated **Docs badge** to live MkDocs URL | Users can access accurate, searchable documentation immediately |
319
+ | ✅ Fixed **installation instructions** to match `pyproject.toml` extras | Prevents user confusion; ensures `pip install adaptshot[faiss]` works |
320
+ | ✅ Corrected **API signatures** to match actual code (`FewShotLearner`, `PredictionResult`) | Developers can copy-paste examples with confidence |
321
+ | ✅ Marked v0.1.2 content as **stable / released** | Confirms publication status is accurate |
322
+ | ✅ Removed placeholder links (`arXiv:2604.XXXXX`, `adaptshot.dev/docs`) | No broken links; only verified, working resources |
323
+ | ✅ Kept the native API as the primary workflow | Reinforces code-first usage even with the optional GUI |
324
+ | ✅ Standardized **citation format** to GitHub + version | Academically sound; reproducible referencing |
325
+
@@ -0,0 +1,280 @@
1
+
2
+ <div align="center">
3
+
4
+ <img src="docs/images/adaptshot-logo.png" width="300" alt="AdaptShot Logo">
5
+
6
+ # AdaptShot
7
+
8
+ **Human-Aligned Few-Shot Vision Learning for Resource-Constrained Environments**
9
+
10
+ [![PyPI](https://img.shields.io/pypi/v/adaptshot.svg)](https://pypi.org/project/adaptshot/)
11
+ [![GitHub Release](https://img.shields.io/github/v/release/johnson2006christopher/adaptshot?label=GitHub%20Release)](https://github.com/johnson2006christopher/adaptshot/releases)
12
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/adaptshot?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/adaptshot)
13
+ [![Python](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/)
14
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
15
+ [![Docs](https://img.shields.io/badge/docs-MkDocs-blue)](https://johnson2006christopher.github.io/adaptshot/)
16
+ [![Built in Tanzania](https://img.shields.io/badge/Built%20in-Tanzania%20🇹🇿-gold.svg)](https://en.wikipedia.org/wiki/Tanzania)
17
+ [![Code Style: Ruff](https://img.shields.io/badge/code%20style-ruff-black)](https://github.com/astral-sh/ruff)
18
+ [![Type Checked: mypy](https://img.shields.io/badge/type--checked-mypy-blue)](https://mypy-lang.org/)
19
+
20
+ ---
21
+
22
+ **Documentation**: [https://johnson2006christopher.github.io/adaptshot/](https://johnson2006christopher.github.io/adaptshot/)
23
+
24
+ **Source Code**: [https://github.com/johnson2006christopher/adaptshot](https://github.com/johnson2006christopher/adaptshot)
25
+
26
+ ---
27
+
28
+ AdaptShot is a high-performance, CPU-optimized, human-in-the-loop few-shot vision library. It is designed to learn from every human correction, guarantee calibrated uncertainty, and run deterministically on edge hardware with minimal resources.
29
+
30
+ v0.2.0-dev is the current release, hardened with 92 regression tests, strict type-checking, and a comprehensive benchmark harness. Built in Tanzania by a self-taught engineer with nothing but a laptop and determination.
31
+
32
+ </div>
33
+
34
+ ## 🚀 Key Features
35
+
36
+ * **CPU-First by Design**: Optimized for low-latency inference on standard CPUs, requiring less than 250MB of RAM.
37
+ * **Trustworthy & Calibrated**: Built-in **Expected Calibration Error (ECE)** minimization and **conformal prediction** with finite-sample coverage guarantees.
38
+ * **Human-in-the-Loop**: Integrated **FeedbackRouter** for real-time model adaptation through human expert corrections.
39
+ * **Continual Learning**: Implements **head-only CA-EWC** (Fisher-regularized classification head fine-tuning, ~2K parameters) and **UP-UGF** (Uncertainty-Guided Forgetting with LSH-accelerated redundancy scoring) for stable, long-term learning without catastrophic forgetting.
40
+ * **Multi-Signal Uncertainty**: Epistemic (stochastic embedding perturbation sensitivity), aleatoric (k-NN entropy), and distributional (shrinkage-regularized Mahalanobis distance) uncertainty quantification with OOD detection. *(Full MC Dropout planned for future torch-dependent release.)*
41
+ * **Explainable AI**: Embedding-space feature attribution (which support examples influenced the prediction), confidence decomposition with historical penalty tracking, counterfactual explanations, and per-dimension saliency analysis.
42
+ * **Contrastive Prototypes**: Gradient-trained class representations via InfoNCE contrastive loss with 2-layer MLP projection head and EMA momentum prototype refinement.
43
+ * **Release Hardened**: Zero-config API, strict type safety, and a comprehensive benchmark harness for review and deployment readiness.
44
+ * **Deterministic**: Guaranteed reproducible results across different runs and hardware through strict seed management.
45
+
46
+ ---
47
+
48
+ ## 🧭 Why AdaptShot?
49
+
50
+ In many real-world scenarios—from rural clinics in Tanzania to remote agricultural fields—AI must operate under extreme constraints: sparse data, no GPU access, and limited connectivity.
51
+
52
+ AdaptShot addresses these challenges by prioritizing **efficiency**, **transparency**, and **human collaboration**. It turns the constraint of small data into an opportunity for high-quality, human-guided learning.
53
+
54
+ ---
55
+
56
+ ## 📦 Installation
57
+
58
+ <div class="termy">
59
+
60
+ ```bash
61
+ $ pip install adaptshot
62
+
63
+ ---> 100%
64
+ ```
65
+
66
+ </div>
67
+
68
+ **Core dependencies**: numpy, Pillow (~15 MB total). PyTorch is **optional** — install it only if you need training/fine-tuning:
69
+
70
+ ```bash
71
+ pip install "adaptshot[torch]" # adds PyTorch + torchvision for training
72
+ ```
73
+
74
+ > **Fast install**: The base library installs in under 60 seconds on standard connections — no GPU drivers, no CUDA, no 2 GB downloads.
75
+
76
+ ### Optional Dependencies
77
+
78
+ AdaptShot provides optional extras for specialized workflows. The native Python API remains the source of truth; the GUI is an optional wrapper around it:
79
+
80
+ * **PyTorch (Training)**: `pip install "adaptshot[torch]"` (Required for CA-EWC fine-tuning and custom backbones)
81
+ * **FAISS Acceleration**: `pip install "adaptshot[faiss]"` (Recommended for support sets >100 images)
82
+ * **Gradio UI**: `pip install "adaptshot[ui]"` (For interactive pilots and human-in-the-loop dashboards)
83
+ * **Studio GUI**: `pip install "adaptshot[gui]"` (For the offline, folder-aware AdaptShot Studio workspace)
84
+ * **Development**: `pip install "adaptshot[dev]"` (For contributors: testing, linting, and benchmarks)
85
+
86
+ ---
87
+
88
+ ## 💡 Quick Start
89
+
90
+ ### Create a Learner and Predict
91
+
92
+ It's as simple as initializing the `FewShotLearner`, loading your support images, and calling `predict()`.
93
+
94
+ ```python
95
+ from adaptshot import FewShotLearner
96
+ from adaptshot.config.settings import AdaptShotConfig
97
+
98
+ # 1. Configure for your environment
99
+ config = AdaptShotConfig(
100
+ backbone="resnet18",
101
+ device="cpu",
102
+ max_buffer_size=100
103
+ )
104
+
105
+ # 2. Initialize the learner
106
+ learner = FewShotLearner(config=config)
107
+
108
+ # 3. Load support set (examples the model learns from)
109
+ image_paths = ["data/healthy_leaf.jpg", "data/blighted_leaf.jpg"]
110
+ labels = ["healthy", "blight"]
111
+ learner.load_support_images(image_paths, labels)
112
+
113
+ # 4. Predict on a new image
114
+ result = learner.predict("data/query.jpg")
115
+
116
+ print(f"Prediction: {result.prediction}")
117
+ print(f"Confidence: {result.calibrated_confidence:.2%}")
118
+
119
+ # 5. Handle uncertainty
120
+ if result.uncertainty_flag:
121
+ print("⚠️ Model is unsure. Routing for human review...")
122
+ ```
123
+
124
+ ---
125
+
126
+ ## 🆕 What's New in v0.2.0
127
+
128
+ - **Conformal Prediction**: Distribution-free prediction sets with true leave-one-out calibration guaranteeing finite-sample coverage at configurable significance levels
129
+ - **Contrastive Prototype Learning**: Gradient-trained InfoNCE class prototypes with 2-layer MLP projection head (full backpropagation through W1/b1/W2/b2)
130
+ - **Advanced Uncertainty**: Three complementary signals — epistemic (stochastic perturbation sensitivity), aleatoric (k-NN entropy), and distributional (shrinkage-regularized Mahalanobis OOD) — fused with mode-gated computation
131
+ - **XAI Explainability**: Embedding-space feature attribution, confidence decomposition with historical penalty tracking, counterfactual analysis, and per-dimension saliency
132
+ - **Cross-conformal prediction mode**: K-fold cross-conformal quantile averaging for more stable prediction sets
133
+ - **Bootstrap Temperature Calibration**: Autonomous LOO grid-search temperature optimization for cold-start scenarios
134
+ - **UP-UGF LSH Acceleration**: Approximate O(N log N) redundancy scoring via random projection locality-sensitive hashing for large buffers (>100 examples)
135
+ - **Memory Profiling**: `MemoryTracker` with tracemalloc + psutil instrumentation for verifying <250MB RAM operation
136
+ - **miniImageNet Benchmarks**: Standard few-shot benchmarks with baseline references (Prototypical Networks, Matching Networks, MAML)
137
+ - **ONNX Export**: Bundled backbone export script with SHA-256 verification for torch-free inference
138
+ - **ACT Symmetric Updates**: Mean-reverting threshold adaptation prevents monotonic drift in autonomous operation
139
+ - **37 new tests** (92 total) across conformal, contrastive, uncertainty, and explainability modules
140
+ - **12 new documentation pages**: Architecture deep-dive, algorithm theory, API reference, 5 tutorials, 2 GUI guides
141
+
142
+ ## 🛠️ Configuration
143
+
144
+ AdaptShot uses a strictly typed, immutable `AdaptShotConfig` to ensure reproducibility.
145
+
146
+ ### Core Execution
147
+
148
+ | Parameter | Type | Default | Description |
149
+ | :--- | :--- | :--- | :--- |
150
+ | `backbone` | `str` | `"resnet18"` | Feature extractor (`resnet18` or `mobilenet_v3_small`) |
151
+ | `device` | `str` | `"cpu"` | Execution device (`cpu`, `cuda`, or `mps`) |
152
+ | `seed` | `int` | `42` | Random seed for deterministic reproducibility |
153
+ | `verbose` | `bool` | `True` | Enable INFO-level logging |
154
+
155
+ ### Few-Shot Learning
156
+
157
+ | Parameter | Type | Default | Description |
158
+ | :--- | :--- | :--- | :--- |
159
+ | `n_way` | `int` | `5` | Number of classes per episode |
160
+ | `k_shot` | `int` | `10` | Support examples per class |
161
+ | `query_size` | `int` | `15` | Query examples per class for evaluation |
162
+
163
+ ### Similarity & Inference
164
+
165
+ | Parameter | Type | Default | Description |
166
+ | :--- | :--- | :--- | :--- |
167
+ | `similarity_metric` | `str` | `"euclidean"` | Distance metric (`cosine` or `euclidean`) |
168
+ | `inference_mode` | `str` | `"prototypical"` | Classification mode (`nearest_neighbor`, `prototypical`, or `contrastive`) |
169
+ | `use_faiss` | `bool` | `False` | Enable FAISS-CPU acceleration for large support sets |
170
+ | `faiss_nprobe` | `int` | `8` | FAISS IVF index probing depth |
171
+
172
+ ### Energy-Aware Inference
173
+
174
+ | Parameter | Type | Default | Description |
175
+ | :--- | :--- | :--- | :--- |
176
+ | `eco_mode` | `bool` | `False` | Enable energy-saving early-exit thresholds |
177
+ | `early_exit_threshold` | `float` | `0.95` | Confidence threshold for early-exit (0.5-1.0) |
178
+
179
+ ### Calibration & Uncertainty
180
+
181
+ | Parameter | Type | Default | Description |
182
+ | :--- | :--- | :--- | :--- |
183
+ | `calibration_method` | `str` | `"temperature"` | Method: `temperature`, `scaling_binning`, `conformal`, or `none` |
184
+ | `ece_n_bins` | `int` | `15` | Bins for Expected Calibration Error |
185
+ | `calibration_eval_bins` | `int` | `100` | Bins for calibration evaluation |
186
+ | `temperature_init` | `float` | `1.0` | Initial temperature scaling parameter |
187
+ | `recalibrate_after_feedback` | `bool` | `True` | Recalibrate after each human correction |
188
+
189
+ ### OOD Detection
190
+
191
+ | Parameter | Type | Default | Description |
192
+ | :--- | :--- | :--- | :--- |
193
+ | `enable_ood_detection` | `bool` | `True` | Flag images outside known support distribution |
194
+ | `ood_threshold_quantile` | `float` | `0.98` | Quantile threshold for OOD rejection (0.5-1.0) |
195
+ | `ood_absolute_min_distance` | `float` | `0.25` | Minimum absolute distance for OOD flagging |
196
+
197
+ ### Memory Management
198
+
199
+ | Parameter | Type | Default | Description |
200
+ | :--- | :--- | :--- | :--- |
201
+ | `max_buffer_size` | `int` | `100` | Maximum replay buffer capacity (enforced by UP-UGF) |
202
+ | `log_dir` | `Optional[str]` | `None` | Optional log output directory |
203
+
204
+ ### Advanced Algorithms (v0.2.0)
205
+
206
+ | Parameter | Type | Default | Description |
207
+ | :--- | :--- | :--- | :--- |
208
+ | `conformal_alpha` | `float` | `0.05` | Significance level for conformal prediction sets (0.01-0.50) |
209
+ | `conformal_mode` | `str` | `"split"` | Conformal prediction mode (`split` or `cross`) |
210
+ | `uncertainty_mode` | `str` | `"ensemble"` | Uncertainty mode (`mcdropout`, `entropy`, `mahalanobis`, or `ensemble`) |
211
+ | `explainability_enabled` | `bool` | `True` | Enable XAI explainability for predictions |
212
+
213
+ ---
214
+
215
+ ## ☁️ Deployment
216
+
217
+ ### Cloud Environments
218
+ AdaptShot is ideal for cost-effective cloud deployments on standard CPU instances (e.g., AWS `t3.medium`, GCP `e2-standard-2`). Since it doesn't require GPUs, you can significantly reduce operational costs while maintaining high-throughput inference.
219
+
220
+ ### On-Premise & Edge
221
+ Designed for the edge, AdaptShot runs seamlessly on:
222
+ * **Single Board Computers**: Raspberry Pi 4+, Jetson Nano (CPU mode).
223
+ * **Legacy Hardware**: Older laptops and desktops with limited RAM.
224
+ * **Offline Stations**: Fully functional without internet access once the backbone weights are cached.
225
+
226
+ ---
227
+
228
+ ## 🤝 Contributing
229
+
230
+ We welcome contributions of all kinds! Whether you're fixing a bug, adding a new backbone, or improving documentation.
231
+
232
+ 1. Check the [Contributing Guidelines](CONTRIBUTING.md).
233
+ 2. Install development dependencies: `pip install -e ".[dev]"`.
234
+ 3. Run tests to ensure everything is working: `pytest tests/`.
235
+ 4. Submit a Pull Request.
236
+
237
+ ---
238
+
239
+ ## 📜 License
240
+
241
+ AdaptShot is open-source software licensed under the **[MIT License](LICENSE)**.
242
+
243
+ ---
244
+
245
+ ## 👤 About the Creator
246
+
247
+ <div align="center">
248
+ <img src="docs/images/johnson.jpeg" width="150" style="border-radius: 50%;" alt="Johnson Christopher Hassan">
249
+
250
+ **Johnson Christopher Hassan**
251
+
252
+ *Vision AI Researcher & Software Engineer*
253
+
254
+ Built in Mbeya, Tanzania 🇹🇿
255
+
256
+ [GitHub](https://github.com/johnson2006christopher) | [LinkedIn](https://www.linkedin.com/in/johnson-christopher-hassan) | [Email](mailto:johnson2006christopher@gmail.com)
257
+
258
+ </div>
259
+
260
+ ---
261
+
262
+ <div align="center">
263
+ <p><i>"The best AI doesn't guess confidently. It learns humbly, admits uncertainty, and improves through every human correction."</i></p>
264
+ </div>
265
+
266
+ ---
267
+
268
+ ## 🔍 Summary of Key Updates
269
+
270
+ | Change | Why It Matters |
271
+ |--------|---------------|
272
+ | ✅ Added **GitHub Release badge** | Points to the eventual packaged release assets |
273
+ | ✅ Updated **Docs badge** to live MkDocs URL | Users can access accurate, searchable documentation immediately |
274
+ | ✅ Fixed **installation instructions** to match `pyproject.toml` extras | Prevents user confusion; ensures `pip install adaptshot[faiss]` works |
275
+ | ✅ Corrected **API signatures** to match actual code (`FewShotLearner`, `PredictionResult`) | Developers can copy-paste examples with confidence |
276
+ | ✅ Marked v0.1.2 content as **stable / released** | Confirms publication status is accurate |
277
+ | ✅ Removed placeholder links (`arXiv:2604.XXXXX`, `adaptshot.dev/docs`) | No broken links; only verified, working resources |
278
+ | ✅ Kept the native API as the primary workflow | Reinforces code-first usage even with the optional GUI |
279
+ | ✅ Standardized **citation format** to GitHub + version | Academically sound; reproducible referencing |
280
+