Skip to content
← All work

Case study 07

MAUI pest detection

A YOLO11s detector for the 102 IP102 pest classes, published on Hugging Face, inside a LangGraph agent that turns detections, NDVI and weather into farm advice.

0
1
2
3
4
5
6
7
8
9
,
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
Downloads, all time
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
Downloads, last 30 days
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
Likes
Stack
PythonUltralytics YOLO11PyTorchLangGraphAnthropic ClaudeOpen-MeteoAWS S3
Sections
Context · The problem · Design · Guardrails · Evals and results · A failure I handled · Stack · Links

Context

MARS (Maui Agronomics Recommendation System) was my final-year university project. It has two parts: a YOLO11s detector I trained on IP102 to find 102 crop pest species, published on Hugging Face as underdogquality/yolo11s-pest-detection, and a LangGraph agent. The agent takes a field image and a location, runs the detector, computes NDVI for multispectral images, pulls weather, and returns a risk level with plain advice for a farmer.

The problem

A box labelled “brown plant hopper” is not something a smallholder can act on. They need to know what to do today: spray what, irrigate how much, or keep watching. Crop vigour, recent rain and evapotranspiration all change that answer. So the detector is one input among several, and a model combines them into a short instruction.

Design

Training the detector. I fine-tuned a pretrained YOLO11s with Ultralytics 8.3.112 on a GPU in Google Colab. The model card names an NVIDIA A100. The checkpoint stores its own training arguments, so these numbers come from best.pt itself, not from memory:

  • Data. IP102, 102 classes, rebalanced and split into train, val and test folders (pests.yaml).
  • Resolution and batch. imgsz 896, batch 64, mixed precision on.
  • Schedule. 100 epochs planned, early-stopping patience 20, SGD chosen by the auto optimizer, lr0 0.01 decaying to 1% of that, momentum 0.937, weight decay 0.0005, 3 warmup epochs.
  • Augmentation. Mosaic on (switched off for the last 10 epochs), HSV jitter (hue 0.015, saturation 0.7, value 0.4), translate 0.1, scale 0.5, horizontal flip at 0.5, RandAugment and random erasing at 0.4. No mixup, copy-paste, rotation or vertical flip.
  • Run. It was interrupted after epoch 11 and resumed from last.pt (the time column restarts at epoch 12). The best checkpoint is epoch 77.

Serving the detector. On Hugging Face, best.pt and pests.yaml load with two lines of Ultralytics code. Inside MARS, the YOLO node loads the same best.pt, calls predict, writes the annotated PNG to S3, and returns labels, scores, boxes and the S3 path.

The agent graph. recommendation.py compiles a four-node LangGraph StateGraph, deployed on the LangGraph Platform as the advisor graph:

  1. weather_node calls Open-Meteo for 7 past days and 3 forecast days at the field’s coordinates. Each day carries temperature, humidity, rain, wind and FAO Penman-Monteith reference evapotranspiration (ET0).
  2. A router sends .tif and .tiff images to the NDVI pipeline. JPEGs go straight to YOLO.
  3. The NDVI pipeline converts a 5-band drone image to top-of-atmosphere reflectance and subtracts a dark object per band. It then applies a 3x3 median filter and computes NDVI. Each pixel’s NDVI becomes a crop coefficient, Kc = clip(1.25 x NDVI + 0.1, 0.1, 1.2). Crop water requirement is mean Kc times the latest ET0. Min, max and mean NDVI and that water figure go into state, and a colour map goes to S3.
  4. YOLO runs on every image. For TIFFs, a helper first picks three bands and rescales them to 8-bit.
  5. The Maui node sends detections with scores, the NDVI summary and the weather to Claude 3.7 Sonnet at temperature 0.3. The prompt asks for a fixed JSON object: risk_level (Low, Moderate or High), advice, and a summary of at most 60 words. The prompt also tells the model to name the pests and matching treatments.

Guardrails

  • Typed state. Every node reads and writes Pydantic models (YoloAnalysisOutputModel, NDVIOutputModel, MauiRecommendationModel), so a node cannot hand the next one a malformed shape.
  • Arithmetic stays in code. NDVI, Kc and crop water requirement are numpy. The model only reads the results. It never computes them.
  • Tolerant parsing with a safe default. The Maui node pulls JSON from a fenced block or a bare object. If parsing fails, it returns risk_level: "Unknown" with the parse error. A guess is never presented as advice.
  • Node failures stay contained. The YOLO and NDVI nodes catch their own exceptions and write the error into state. The run still reaches the recommendation node with whatever data exists.

Evals and results

The checkpoint’s own metrics at epoch 77, computed by Ultralytics on the val split:

  • Precision 0.923, recall 0.907
  • mAP@0.5 0.941, mAP@0.5:0.95 0.838

The metrics were still rising slowly at epoch 77. mAP@0.5 went from 0.810 at epoch 11 to 0.941.

The model card also reports a lower set in a column labelled “Validation Set”: precision 0.744, recall 0.789, mAP@0.5 0.815, mAP@0.5:0.95 0.605. No results file in either repo shows which split produced those, so I read them as the conservative figure. The headline “94%” belongs to mAP@0.5. Precision is 92%.

The download count shown at the top of this page is fetched live from the Hugging Face API.

What is not measured: no file shows how the balanced split was built, so I cannot rule out near-duplicates across train and val. The two copies of the model card disagree on dataset size (14K+ images on GitHub, 34K+ on Hugging Face). There are no per-class metrics and no test on drone imagery, and the TIFF path feeds the detector a false-colour band mix it never saw in training. The pipeline takes single images, not live video. There is no eval of the agent’s advice and no field trial, so no measured irrigation saving or earlier outbreak detection. A known defect: the YOLO node returns the model’s full class-name list, not the class of each box. The labels passed to the agent are therefore not tied to its detections. The fix is to map boxes.cls through names.

A failure I handled

The first end-to-end run with a multispectral drone TIFF broke the YOLO node. The S3 reader returns a TIFF as a float32 array with five bands. YOLO expects an 8-bit image with three channels. The commit history on one day shows the fix in steps:

  1. My first helper re-decoded raw bytes with PIL. But the reader had already decoded the image, so that path was wrong (4cb5026).
  2. I replaced it with an array helper. It moved channels from first to last position, expanded grayscale to three channels and scaled to uint8 (297ee88). A 5-band image still came out with five channels.
  3. The working version branches on type (91795b1). A PIL JPEG converts to RGB. An array with more than three bands gets an explicit band selection, [2, 1, 3]. It is min-max scaled to 0 to 255, with a constant fallback when the image is flat. Then it round-trips through an in-memory PNG, so Ultralytics receives a standard contiguous RGB array.
  4. Two follow-ups: a stale variable name in the node (7186d01), and a router that called endswith with a list, which raises a TypeError, fixed to a tuple (2115caa, 3baf2f4).

After that, a TIFF flows through NDVI, YOLO and the recommendation, as the README’s sample output shows.

Stack

Python, Ultralytics YOLO11s, PyTorch, LangGraph Platform, LangChain ChatAnthropic (Claude 3.7 Sonnet), LangSmith, Pydantic, NumPy, SciPy, tifffile, Pillow, Open-Meteo, AWS S3.

github.com/winstonkaranja/mars, Hugging Face model

Next case study

Carbon-Sync

NDVI and crop biomass from multispectral aerial imagery, converted to carbon credits in tonnes of CO2 equivalent, with a LangGraph agronomy advisor on the same pipeline.

Read it →