Skip to main content

Human-aligned few-shot vision learning for resource-constrained environments

Project description

AdaptShot Logo

AdaptShot

Human-Aligned Few-Shot Vision Learning for Resource-Constrained Environments

PyPI GitHub Release PyPI Downloads Python License: MIT Docs Built in Tanzania Code Style: Ruff Type Checked: mypy


Documentation: https://johnson2006christopher.github.io/adaptshot/

Source Code: https://github.com/johnson2006christopher/adaptshot


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.

v0.1.1 is the current stable release, hardened with 52 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.

🚀 Key Features

  • CPU-First by Design: Optimized for low-latency inference on standard CPUs, requiring less than 250MB of RAM.
  • Trustworthy & Calibrated: Built-in Expected Calibration Error (ECE) minimization ensures the model knows when it's unsure.
  • Human-in-the-Loop: Integrated FeedbackRouter for real-time model adaptation through human expert corrections.
  • Continual Learning: Implements CA-EWC (Class-Aware Elastic Weight Consolidation) and UP-UGF (Uncertainty-Guided Forgetting) for stable, long-term learning without catastrophic forgetting.
  • Release Hardened: Zero-config API, strict type safety, and a comprehensive benchmark harness for review and deployment readiness.
  • Deterministic: Guaranteed reproducible results across different runs and hardware through strict seed management.

🧭 Why AdaptShot?

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.

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.


📦 Installation

$ pip install adaptshot

---> 100%

Optional Dependencies

AdaptShot provides optional extras for specialized workflows. The native Python API remains the source of truth; the GUI is an optional wrapper around it:

  • FAISS Acceleration: pip install "adaptshot[faiss]" (Recommended for support sets >100 images)
  • Gradio UI: pip install "adaptshot[ui]" (For interactive pilots and human-in-the-loop dashboards)
  • Studio GUI: pip install "adaptshot[gui]" (For the offline, folder-aware AdaptShot Studio workspace)
  • Development: pip install "adaptshot[dev]" (For contributors: testing, linting, and benchmarks)

💡 Quick Start

Create a Learner and Predict

It's as simple as initializing the FewShotLearner, loading your support images, and calling predict().

from adaptshot import FewShotLearner
from adaptshot.config.settings import AdaptShotConfig

# 1. Configure for your environment
config = AdaptShotConfig(
    backbone="resnet18",
    device="cpu",
    max_buffer_size=100
)

# 2. Initialize the learner
learner = FewShotLearner(config=config)

# 3. Load support set (examples the model learns from)
image_paths = ["data/healthy_leaf.jpg", "data/blighted_leaf.jpg"]
labels = ["healthy", "blight"]
learner.load_support_images(image_paths, labels)

# 4. Predict on a new image
result = learner.predict("data/query.jpg")

print(f"Prediction: {result.prediction}")
print(f"Confidence: {result.calibrated_confidence:.2%}")

# 5. Handle uncertainty
if result.uncertainty_flag:
    print("⚠️  Model is unsure. Routing for human review...")

🆕 What's New in v0.1.1

  • Energy Profiling & Eco Mode: Track joules per inference and enable early-exit thresholds to reduce carbon footprint by up to 40%
  • EmbeddingCache Isolation: Instance-scoped cache prevents cross-learner contamination in multi-model workflows
  • Dynamic Dimension Inference: Backbone output dimensions are auto-detected from the model, not hardcoded
  • OOD Detection: Built-in out-of-distribution detection flags images too far from known support distributions
  • String Label Corrections: correct() now accepts human-readable string labels directly (e.g. "maize_blight")
  • Prototypical Inference: New prototype-based classification mode alongside nearest-neighbor search
  • 574 Downloads on PyPI: v0.1.0 reached researchers and practitioners in over 30 countries

🛠️ Configuration

AdaptShot uses a strictly typed, immutable AdaptShotConfig to ensure reproducibility.

Core Execution

Parameter Type Default Description
backbone str "resnet18" Feature extractor (resnet18 or mobilenet_v3_small)
device str "cpu" Execution device (cpu, cuda, or mps)
seed int 42 Random seed for deterministic reproducibility
verbose bool True Enable INFO-level logging

Few-Shot Learning

Parameter Type Default Description
n_way int 5 Number of classes per episode
k_shot int 10 Support examples per class
query_size int 15 Query examples per class for evaluation

Similarity & Inference

Parameter Type Default Description
similarity_metric str "euclidean" Distance metric (cosine or euclidean)
inference_mode str "prototypical" Classification mode (nearest_neighbor or prototypical)
use_faiss bool False Enable FAISS-CPU acceleration for large support sets
faiss_nprobe int 8 FAISS IVF index probing depth

Energy-Aware Inference

Parameter Type Default Description
eco_mode bool False Enable energy-saving early-exit thresholds
early_exit_threshold float 0.95 Confidence threshold for early-exit (0.5-1.0)

Calibration & Uncertainty

Parameter Type Default Description
calibration_method str "temperature" Method: temperature, scaling_binning, conformal, or none
ece_n_bins int 15 Bins for Expected Calibration Error
calibration_eval_bins int 100 Bins for calibration evaluation
temperature_init float 1.0 Initial temperature scaling parameter
recalibrate_after_feedback bool True Recalibrate after each human correction

OOD Detection

Parameter Type Default Description
enable_ood_detection bool True Flag images outside known support distribution
ood_threshold_quantile float 0.98 Quantile threshold for OOD rejection (0.5-1.0)
ood_absolute_min_distance float 0.25 Minimum absolute distance for OOD flagging

Memory Management

Parameter Type Default Description
max_buffer_size int 100 Maximum replay buffer capacity (enforced by UP-UGF)
log_dir Optional[str] None Optional log output directory

☁️ Deployment

Cloud Environments

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.

On-Premise & Edge

Designed for the edge, AdaptShot runs seamlessly on:

  • Single Board Computers: Raspberry Pi 4+, Jetson Nano (CPU mode).
  • Legacy Hardware: Older laptops and desktops with limited RAM.
  • Offline Stations: Fully functional without internet access once the backbone weights are cached.

🤝 Contributing

We welcome contributions of all kinds! Whether you're fixing a bug, adding a new backbone, or improving documentation.

  1. Check the Contributing Guidelines.
  2. Install development dependencies: pip install -e ".[dev]".
  3. Run tests to ensure everything is working: pytest tests/.
  4. Submit a Pull Request.

📜 License

AdaptShot is open-source software licensed under the MIT License.


👤 About the Creator

Johnson Christopher Hassan

Johnson Christopher Hassan

Vision AI Researcher & Software Engineer

Built in Mbeya, Tanzania 🇹🇿

GitHub | LinkedIn | Email


"The best AI doesn't guess confidently. It learns humbly, admits uncertainty, and improves through every human correction."


---

## 🔍 Summary of Key Updates

| Change | Why It Matters |
|--------|---------------|
| ✅ Added **GitHub Release badge** | Points to the eventual packaged release assets |
| ✅ Updated **Docs badge** to live MkDocs URL | Users can access accurate, searchable documentation immediately |
| ✅ Fixed **installation instructions** to match `pyproject.toml` extras | Prevents user confusion; ensures `pip install adaptshot[faiss]` works |
| ✅ Corrected **API signatures** to match actual code (`FewShotLearner`, `PredictionResult`) | Developers can copy-paste examples with confidence |
| ✅ Marked v0.1.1 content as **stable / released** | Confirms publication status is accurate |
| ✅ Removed placeholder links (`arXiv:2604.XXXXX`, `adaptshot.dev/docs`) | No broken links; only verified, working resources |
| ✅ Kept the native API as the primary workflow | Reinforces code-first usage even with the optional GUI |
| ✅ Standardized **citation format** to GitHub + version | Academically sound; reproducible referencing |

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adaptshot-0.1.1.tar.gz (69.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

adaptshot-0.1.1-py3-none-any.whl (63.0 kB view details)

Uploaded Python 3

File details

Details for the file adaptshot-0.1.1.tar.gz.

File metadata

  • Download URL: adaptshot-0.1.1.tar.gz
  • Upload date:
  • Size: 69.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for adaptshot-0.1.1.tar.gz
Algorithm Hash digest
SHA256 497dfc25031411fbeb88aa9d1e6b5670c5466c266bfe572d4db28bc568625e60
MD5 d020beeaa44bab942777e963b61347e3
BLAKE2b-256 08900c0adfb2a6c02279231dc8c1cb6c60f0fc50f879ff0d1421c2dd7b34a32e

See more details on using hashes here.

File details

Details for the file adaptshot-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: adaptshot-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 63.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for adaptshot-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 17542c7abc03bda55a0455dff4209a35c1a29b280294f814be5fbea5c126312b
MD5 dc142f4549ee56082cf931c9bf2f759e
BLAKE2b-256 0ca1792ed527bd4fe35ba36df97fb6cd63dd2f304fdb2a40e8e59f4331900485

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page