Run this model with HF Jobs
Run Addax-Data-Science/CONGO-CMR-v1 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Addax-Data-Science/CONGO-CMR-v1. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Addax-Data-Science/CONGO-CMR-v1 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Addax-Data-Science/CONGO-CMR-v1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Addax-Data-Science/CONGO-CMR-v1 with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Addax-Data-Science/CONGO-CMR-v1") - Notebooks
- Google Colab
- Kaggle
CBNet v1, Keras 3 re-save of alexvmt/CBNet
Browse filesFiles changed (6)
- .gitattributes+1
- README.mdAdded+7
- class_list.yamlAdded+12
- inference.pyAdded+245
- model.kerasAdded+3
- taxonomy.csvAdded+13
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodel.keras filter=lfs diff=lfs merge=lfs -text1234567---{}---
This repository contains open-source models redistributed for easy integration with [AddaxAI](https://addaxdatascience.com/addaxai/), hosted by [Addax Data Science](https://addaxdatascience.com/). Each model retains its original license (see license files) and attribution. We comply with all original license terms. Users must review and comply with individual model licenses before use. See below for detailed model information including original sources, licenses, and attributions.
For the owner, license, citation and links of this model, see the [AddaxAI model zoo](https://docs.addaxai.com/docs/reference/model-zoo).123456789101112'1': atherurus_africanus'10': philantomba_monticola'11': potamochoerus_porcus'12': tragelaphus_spekii'2': cephalophus_callipygus'3': cephalophus_dorsalis'4': cephalophus_silvicultor'5': cercocebus_torquatus'6': cricetomys_emini'7': loxodonta_cyclotis'8': mandrillus_sphinx'9': pan_troglodytes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""Inference script for CONGO-CMR-v1 (CBNet, Congo Basin species classifier)
CBNet (CongoBasinNet) supports conservation in the Congo Basin, inparticular Cameroon. It classifies 12 forest species and is a fine-tunedversion of SpeciesNet, trained on about 15,000 WWF Cameroon camera trapimages. Accuracy 0.902 and macro accuracy 0.817 on a held-out test set.
Model: CBNet v1Input: 480x480 RGB crops, pixels scaled to [0, 1], no mean/std normalisationFramework: Keras 3 with TensorFlow backend (EfficientNetV2M architecture)Classes: 12 (see class_list.yaml, ids 1..12 -> scientific names)Developer: Alexander Merdian-TarkoLicense: MITInfo: https://alexvmt.github.io/
The author saved the model with Keras 2.14, which Keras 3 refuses to load.The model.keras shipped here is the same network re-saved in Keras 3: theEfficientNetV2M graph was rebuilt layer for layer (same names, sameshapes, 12-class softmax head, no preprocessing layer) and the originalweights were loaded by layer name. Checked on 25 real crops against theoriginal in Keras 2.14: identical top-5 order on every crop, maximumprobability difference 3e-6.
Author: Peter van LunterenCreated: 2026-11-02"""
from __future__ import annotations
import osimport sysfrom pathlib import Path
import numpy as npimport tensorflow as tfimport yamlfrom keras import savingfrom PIL import Image, ImageFile
# Keras backend. A Keras 3 .keras file is backend-agnostic. TensorFlow is# what gives this env a GPU: tensorflow-metal on macOS and CUDA on Linux,# where JAX in this env is CPU-only.os.environ["KERAS_BACKEND"] = "tensorflow"
# Don't freak out over truncated imagesImageFile.LOAD_TRUNCATED_IMAGES = True
# The model's classes are scientific names with underscores# (class_list.yaml, as the author trained it). The app shows a label as# the species' common name, so the label the app stores is the English# name; taxonomy.csv carries the same English names in model_class and# the scientific names in the rank columns. Every class in class_list.yaml# must have an entry here, or load_model() refuses to start: a missing# entry would otherwise ship a label with no taxonomy row.COMMON_NAMES: dict[str, str] = { "atherurus_africanus": "african brush-tailed porcupine", "cephalophus_callipygus": "peters's duiker", "cephalophus_dorsalis": "bay duiker", "cephalophus_silvicultor": "yellow-backed duiker", "cercocebus_torquatus": "red-capped mangabey", "cricetomys_emini": "emin's pouched rat", "loxodonta_cyclotis": "african forest elephant", "mandrillus_sphinx": "mandrill", "pan_troglodytes": "chimpanzee", "philantomba_monticola": "blue duiker", "potamochoerus_porcus": "red river hog", "tragelaphus_spekii": "sitatunga",}
class ModelInference: """Keras inference implementation for the CBNet Congo Basin classifier."""
def __init__(self, model_dir: Path, model_path: Path): """ Initialize with model paths.
Args: model_dir: Directory containing model files (including class_list.yaml) model_path: Path to the .keras model file """ self.model_dir = model_dir self.model_path = model_path self.model = None self.img_size = 480 # SpeciesNet / EfficientNetV2M input size self.class_ids: list[str] | None = None
def check_gpu(self) -> bool: """ Check GPU availability for TensorFlow/Keras inference.
Returns: True if GPU available, False otherwise """ try: return len(tf.config.list_logical_devices("GPU")) > 0 except Exception: return False
def load_model(self) -> None: """ Load the Keras model and the class list. Called once per worker.
class_list.yaml maps the model's output index + 1 to the class, as the author documents it: `'1': atherurus_africanus, ...`. Output index i is class id i + 1, so the list is read in numeric key order.
Raises: RuntimeError: If model loading fails FileNotFoundError: If model_path or class_list.yaml is missing """ if not self.model_path.exists(): raise FileNotFoundError(f"Model file not found: {self.model_path}")
try: self.model = saving.load_model(str(self.model_path), compile=False) except Exception as e: raise RuntimeError(f"Failed to load Keras model from {self.model_path}: {e}") from e
class_list_path = self.model_dir / "class_list.yaml" if not class_list_path.exists(): raise FileNotFoundError(f"Class list file not found: {class_list_path}")
try: with open(class_list_path, encoding="utf-8") as f: class_map = yaml.safe_load(f) by_id = {int(k): str(v).strip() for k, v in class_map.items()} except Exception as e: raise RuntimeError(f"Failed to load class labels from {class_list_path}: {e}") from e
n = len(by_id) if sorted(by_id) != list(range(1, n + 1)): raise RuntimeError( f"{class_list_path} must hold ids 1..{n} without gaps, got {sorted(by_id)}" ) n_out = int(self.model.outputs[0].shape[-1]) if n_out != n: raise RuntimeError( f"Model has {n_out} outputs but class_list.yaml lists {n} classes" )
missing = [by_id[i] for i in range(1, n + 1) if by_id[i] not in COMMON_NAMES] if missing: raise RuntimeError( f"No common name for model class(es) {missing}; add them to COMMON_NAMES" ) self.class_ids = [COMMON_NAMES[by_id[i]] for i in range(1, n + 1)]
def get_crop( self, image: Image.Image, bbox: tuple[float, float, float, float] ) -> Image.Image | None: """ Crop the MegaDetector box out of the full image, as the author does.
Direct crop, no padding or squaring: the box edges in pixels are the normalised coordinates times the image size, rounded. Resizing to the model input happens in get_tensor / get_classification.
Args: image: PIL Image (full resolution) bbox: Normalized bounding box (x, y, width, height) in range [0.0, 1.0]
Returns: Cropped PIL Image, or None if the box is empty """ x, y, w, h = bbox if w <= 0 or h <= 0: print( f"[CONGO get_crop] Rejecting bbox with zero/negative dims: w={w}, h={h}", file=sys.stderr, flush=True, ) return None
im_width, im_height = image.size left = min(max(round(x * im_width), 0), im_width) top = min(max(round(y * im_height), 0), im_height) right = min(max(round((x + w) * im_width), 0), im_width) bottom = min(max(round((y + h) * im_height), 0), im_height)
if right <= left or bottom <= top: print( f"[CONGO get_crop] Rejecting empty crop ({left},{top})-({right},{bottom}) " f"for bbox {bbox} on {im_width}x{im_height}", file=sys.stderr, flush=True, ) return None
return image.crop((left, top, right, bottom))
def _preprocess(self, crop: Image.Image) -> np.ndarray: """Resize to 480x480 bicubic and scale pixels to [0, 1], as the author does.""" resized = crop.convert("RGB").resize((self.img_size, self.img_size), Image.BICUBIC) return np.asarray(resized, dtype=np.float32) / 255.0
def _to_classifications(self, probs: np.ndarray) -> list[list[str, float]]: return [[self.class_ids[i], float(probs[i])] for i in range(len(self.class_ids))]
def get_classification(self, crop: Image.Image) -> list[list[str, float]]: """ Run classification on one cropped image.
Args: crop: Cropped PIL Image from get_crop()
Returns: List of [class_name, confidence] lists for ALL classes, in model order. Sorting by confidence is handled by classification_worker.py.
Raises: RuntimeError: If model not loaded or inference fails """ if self.model is None or self.class_ids is None: raise RuntimeError("Model not loaded - call load_model() first")
if crop is None: return []
try: arr = self._preprocess(crop) probs = self.model.predict(arr[None], verbose=0)[0] return self._to_classifications(probs) except Exception as e: raise RuntimeError(f"Keras classification failed: {e}") from e
def get_class_names(self) -> dict[str, str]: """ Get mapping of class IDs to species names.
Returns: Dict mapping class ID (1-indexed string) to the label the app stores, in the model's output order: {"1": class_ids[0], "2": class_ids[1], ...} """ if self.class_ids is None: raise RuntimeError("Class IDs not loaded - call load_model() first") return {str(i + 1): name for i, name in enumerate(self.class_ids)}
def get_tensor(self, crop: Image.Image): """Preprocess a crop into a float32 [480, 480, 3] array for batch inference.""" return self._preprocess(crop)
def classify_batch(self, batch): """Run inference on a batch of preprocessed arrays.""" probs = self.model.predict(batch, verbose=0) return [self._to_classifications(p) for p in probs]123version https://git-lfs.github.com/spec/v1oid sha256:66a3fcaf94043daca6dc304b21c2e8b4160afb6c5a3c8fa58d936849242e1357size 21504555612345678910111213model_class,class,order,family,genus,species,variant
african brush-tailed porcupine,mammalia,rodentia,hystricidae,atherurus,africanus,
peters's duiker,mammalia,artiodactyla,bovidae,cephalophus,callipygus,
bay duiker,mammalia,artiodactyla,bovidae,cephalophus,dorsalis,
yellow-backed duiker,mammalia,artiodactyla,bovidae,cephalophus,silvicultor,
red-capped mangabey,mammalia,primates,cercopithecidae,cercocebus,torquatus,
emin's pouched rat,mammalia,rodentia,nesomyidae,cricetomys,emini,
african forest elephant,mammalia,proboscidea,elephantidae,loxodonta,cyclotis,
mandrill,mammalia,primates,cercopithecidae,mandrillus,sphinx,
chimpanzee,mammalia,primates,hominidae,pan,troglodytes,
blue duiker,mammalia,artiodactyla,bovidae,philantomba,monticola,
red river hog,mammalia,artiodactyla,suidae,potamochoerus,porcus,
sitatunga,mammalia,artiodactyla,bovidae,tragelaphus,spekii,.gitattributes+1
README.mdAdded+7
class_list.yamlAdded+12
inference.pyAdded+245
model.kerasAdded+3
taxonomy.csvAdded+13