The Effect of Temporal Image Selection on CNN-Based Classification of Nutritional Deficiencies in Coffee Leaves
Experiment code for the SIBGRAPI 2026 paper of the same name, by Hericles Felipe Ferraz, Mauricio Cunha Escarpinati and Thiago Pirola Ribeiro (FACOM/UFU).
The paper asks whether an accuracy optimum found along a cumulative time axis is a property of the plants or of the selection protocol. This repository holds the three training designs that answer it, the analysis that tests them, and the scripts that produce every figure in the paper.
Accuracy peaks at 77.97% under the conventional image-level split. The two controls in this repository show that the peak belongs to the protocol, not to the plants: under plant-level validation it falls to 36.6% and the curve flattens.
Scope. This repository contains code and result tables only. The images are not versioned here and are not ours to redistribute. See Data.
Images are sorted globally by capture timestamp. DATA_START_FRAC discards the
earliest fraction of that ordering, so frac95 keeps the last 5% (recent captures,
well-developed symptoms, few images) and frac50 keeps the last 50% (a wider window
that also pulls in older, weakly symptomatic material). The selections are nested:
frac95 ⊂ frac75 ⊂ frac60 ⊂ frac50.
| Design | Split | What it isolates | Result |
|---|---|---|---|
cumulative_selections |
image-level 80/20 | nothing, the conventional protocol | bell-shaped curve peaking at 77.97% (512×512, frac60) |
plant_split |
4-fold grouped by replicate | plant identity | accuracy falls to 36.6% and the peak disappears (F = 1.12, p = 0.39) |
temporal_bands |
both, over disjoint bands | training-set size | bands differ (F = 4.05, p = 0.026), but only the earliest one, which is also the only one spanning a 26-day gap in acquisition, and the four contiguous bands that follow are indistinguishable (F = 0.64, p = 0.61) |
The conclusion is negative and deliberately narrow: what does not reproduce under plant separation is the peak. With four biological replicates the design bounds any effect of symptom development at about ten points rather than excluding one.
Interpretability is qualitative. Grad-CAM on ResNet50's layer3 produces maps that
track the anatomical location of each deficiency, while layer4, whose receptive field
spans almost the whole image, reduces to a few broad regions.
Grad-CAM for all seven classes. The layer3 maps resolve fine leaf
structure, following interveinal areas for Mg and margins and tips for K, whereas the
layer4 maps collapse to a few broad regions. The model received no
spatial supervision, so this alignment with expert diagnostic cues is emergent.
| Folder | Contents |
|---|---|
experiments/cumulative_selections/ |
20 runs: ResNet50 at 2 resolutions across 10 selection levels |
experiments/plant_split/ |
16 plant-level folds over 4 selection levels |
experiments/temporal_bands/ |
5 disjoint bands under the image-level and plant-level protocols |
analysis/ |
the blocked ANOVAs reported in the paper |
interpretability/ |
Grad-CAM, layer3 against layer4 |
figures/ |
the five figures of the paper |
preprocessing/ |
dataset preparation and the square-crop pipeline |
results/ |
per-run and per-fold metrics behind every number |
data/ |
data contract only, see data/README.md |
Each experiment script is self-contained: the CoffeeDataset definition, the
architecture, and the training loop all live in the file itself, so each protocol can
be read and reproduced in isolation.
- Python 3.10 or newer, managed by uv
- An NVIDIA GPU is recommended. The reported runs used an RTX 5060 Ti with 16 GB.
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
uv sync --extra notebookThe first line installs uv, the second creates the virtual environment and installs
every dependency, and the third adds the optional notebook tooling. Run any script with
uv run, without activating anything manually.
The default torch/torchvision wheels cover most setups. For a specific CUDA build,
such as CUDA 12.8 on recent Blackwell GPUs, point uv at the matching PyTorch index by
adding this to pyproject.toml:
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }The code expects two artifacts, both provided by the user. The full contract is in
data/README.md.
- A CSV
data/data_collection_clean.csvwith the columnspath, classe_final, vaso, timestamp, referencia. - The images at
data/dataset_clean/<classe_final>/<vaso>/<timestamp>/<file>.JPG, already preprocessed to 512×512.
The images come from a controlled greenhouse trial run by third parties and are not redistributed here. Requests for access should be directed to the authors.
All scripts resolve paths from a project root, this repository by default. To point data and outputs elsewhere:
export COFFEE_PROJECT_ROOT=/path/to/your/data_and_resultsUnder that root the scripts read data/ and write results_benchmark/,
results_plant_split/ and results_temporal_bands/.
The conventional protocol, 20 runs over ResNet50 at two resolutions and ten selection levels:
uv run python experiments/cumulative_selections/train_cumulative_selections.pyThe plant-level control, four selection levels of four folds each:
uv run python experiments/plant_split/train_plant_split.pyThe constant-volume control, five disjoint bands under both protocols:
PROTOCOL=image uv run python experiments/temporal_bands/train_temporal_bands.py
PROTOCOL=plant uv run python experiments/temporal_bands/train_temporal_bands.pyThe statistics reported in the paper, straight from results/:
uv run python analysis/blocked_anova.pyAll three training scripts accept SMOKE_TEST=1, which runs a reduced pass on CPU to
verify the pipeline without producing reportable results.
Details of each protocol, including the configuration grid, outputs and metrics, are in
the README.md of each subfolder.
Docker packages the code only. The dataset and the results stay on the host and are
bind-mounted into the container, so nothing large is ever copied into the image. The
torch and torchvision wheels already bundle the CUDA runtime, so the image builds on
a plain python:3.12-slim base and reaches the GPU through the
NVIDIA Container Toolkit
with --gpus all. Install that toolkit on the host first.
Point the container at your data by copying the example environment file and setting an
absolute host path to the directory that holds data/ and receives the results_*/
outputs, the layout described in data/README.md:
cp .env.example .envThat directory is mounted at /workspace, which is where COFFEE_PROJECT_ROOT points
inside the image, so the scripts read data/ and write results_benchmark/,
results_plant_split/, results_temporal_bands/, outputs/, mlflow.db and the
MLflow run artifacts under mlruns/ there.
Build the image:
docker compose buildConfirm the GPU is visible, which should print True:
docker compose run --rm app python -c "import torch; print(torch.cuda.is_available())"If it prints False, check that the NVIDIA Container Toolkit is installed and that
docker run --rm --gpus all ... nvidia-smi works on the host.
Run the experiments, with the same uv workflow used natively:
docker compose run --rm app uv run python experiments/cumulative_selections/train_cumulative_selections.py
docker compose run --rm app uv run python experiments/plant_split/train_plant_split.py
docker compose run --rm -e PROTOCOL=plant app uv run python experiments/temporal_bands/train_temporal_bands.pyFor a reduced pass that verifies the pipeline without producing reportable results:
docker compose run --rm -e SMOKE_TEST=1 app uv run python experiments/plant_split/train_plant_split.pyThe scripts log to mlflow.db on the mount, and the mlflow-ui service serves the
MLflow UI from the same image against that database:
docker compose up mlflow-uiThen open http://localhost:5000. Training and the UI are separate services, so an
experiment can run under app while the results are browsed under mlflow-ui.
Every script seeds random, numpy and torch, sets cudnn.deterministic and
disables cudnn.benchmark, and uses SEED = 42 throughout. Data splits come from
scikit-learn with that same fixed seed, so the partitions are a function of the seed
alone.
This was checked rather than assumed. The plant-level protocol was run twice under
identical settings, on GPU, with 8 dataloader workers, and the two runs agreed on 31 of
the 32 fields of fold_metrics.csv, bit for bit: accuracy, macro F1, macro precision,
macro recall, the per-class F1 of all seven classes, and the split sizes. The single
field that differed was duration_min, which is wall-clock time.
That result holds for a fixed environment. A different GPU, driver or PyTorch version
can still shift the last digits, and torch.use_deterministic_algorithms is
deliberately left unset, since the seeded cuDNN configuration already proved sufficient
here and enabling it would forbid faster kernels for no measured gain.
To repeat the check:
docker compose run --rm -e SMOKE_TEST=1 -e USE_GPU=1 -e NUM_WORKERS=8 app \
uv run python experiments/plant_split/train_plant_split.pyRun it twice and compare results_plant_split/resnet50_224x224_frac60_plantsplit/fold_metrics.csv
between runs. Note that SMOKE_TEST=1 trains for a single epoch on a subsample, so its
accuracies are meaningless as results. It exercises the pipeline, not the science.
results/ holds the metrics behind every number in the paper, so the
tables and figures can be checked without rerunning any training:
| File | Contents |
|---|---|
cumulative_selections.csv |
20 runs: accuracy, macro F1, macro precision and recall |
plant_split_folds.csv |
16 folds: per-fold accuracy and macro F1, with the held-out replicate |
temporal_bands_folds.csv |
5 bands × 2 protocols: per-fold accuracy and macro F1 |
analysis/blocked_anova.py recomputes the four F statistics reported in the paper from
these files.
The training scripts log metrics via MLflow to a local mlflow.db. Inspect them
with uv run mlflow ui --backend-store-uri sqlite:///mlflow.db.
@inproceedings{2026FerrazTemporal,
author = {Ferraz, Hericles Felipe and Escarpinati, Mauricio Cunha and Ribeiro, Thiago Pirola},
title = {The Effect of Temporal Image Selection on {CNN}-Based Classification of Nutritional Deficiencies in Coffee Leaves},
booktitle = {Proceedings of the 39th SIBGRAPI Conference on Graphics, Patterns and Images},
year = {2026},
}Distributed under the MIT license. See LICENSE.

