Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A practical, end-to-end workflow for training a Mask R-CNN model

1. Motivation

On the previous page, data holds everything prepared for training: the images and labels directories, ready in the format geoai expects. This page uses that directly to train a Mask R-CNN model.

This is the page where the architecture from two pages ago and the data from the previous page become an actual trained model. As with the detection and segmentation training functions in earlier lessons, geoai hides most of the implementation behind a small set of parameters; understanding what each one controls is what lets you make good choices for your own project data later.


2. Core idea

geoai.train_instance_segmentation_model() runs the complete Mask R-CNN training pipeline: it builds the backbone, RPN, detection head, and mask head from the previous architecture page, and trains all of them together against a combined loss.


3. Workflow

Training an instance segmentation model requires configuring both structural parameters (which adapt the network architecture to your spatial data) and optimization hyperparameters (which control how the model learns). This section walks through setting up, executing, and evaluating a Mask R-CNN training pipeline on the prepared Luxembourg dataset.


A. Dataset preparation

Before launching model training, we re-establish the dataset preparation pipeline to ensure all required directories and inputs are loaded:


B. Core structural parameters

Three structural parameters adapt the Mask R-CNN model to the physical properties of our satellite imagery and labels:

num_classes = 2
num_channels = 4
instance_labels = True

C. The training pipeline

With the data prepared and parameters defined, we initialize and run the training function:

During training, model checkpoints and performance history logs are saved to field_boundaries/models/, with the highest-performing iteration stored as best_model.pth.


D. Hyperparameters & GPU-memory

Hyperparameters control the optimization behavior during training:


E. Deconstructing the loss function

Unlike single-task models evaluated on a single loss value, Mask R-CNN optimizes a compound multi-task loss (LtotalL_{\text{total}}) representing five separate model operations:

Ltotal=Lrpn_cls+Lrpn_box+Lcls+Lbox+LmaskL_{\text{total}} = L_{\text{rpn\_cls}} + L_{\text{rpn\_box}} + L_{\text{cls}} + L_{\text{box}} + L_{\text{mask}}
Loss ComponentDescriptionDiagnostic Meaning if High
Lrpn_clsL_{\text{rpn\_cls}} (RPN Objectness)Evaluates whether the RPN correctly identifies regions containing objects.Model struggles to find candidate features in the scene.
Lrpn_boxL_{\text{rpn\_box}} (RPN Box Proposal)Measures initial coarse anchor box alignment.Candidate proposal boxes are poorly aligned with true features.
LclsL_{\text{cls}} (Class Prediction)Evaluates classification of proposal regions (e.g., field vs. background).Model misclassifies identified object proposals.
LboxL_{\text{box}} (Box Refinement)Measures boundary accuracy of the refined detection bounding box.Final bounding boxes are loose or misaligned.
LmaskL_{\text{mask}} (Mask Prediction)Evaluates binary pixel accuracy within each bounding box (28×2828 \times 28 grid).Predicted internal field shapes fail to match true geometric boundaries.

Monitoring individual loss terms during training helps isolate specific model weaknesses—such as identifying whether poor final outputs stem from missed detections (Lrpn_clsL_{\text{rpn\_cls}}) or inaccurate edge boundaries (LmaskL_{\text{mask}}).


F. Inspecting training history

After training completes, plot the metric history to evaluate convergence and generalization:

When evaluating training curves, look for structural health indicators rather than focusing solely on final numeric values:

Healthy Training                     Overfitting Warning
Loss                                 Loss
 │  ─── Training                      │  ─── Training
 │  --- Validation                    │  --- Validation
 │ \                                  │ \
 │  \__                               │  \__      /----------- (Val rises)
 │     \________                      │     \____/
 └───────────────── Epochs            └───────────────── Epochs

G. Reproducibility

To maintain scientific reproducibility across model iterations, explicitly record model parameters, environment settings, and data lineage for every training run:

Documenting dataset versions, spectral channel ordering, spatial resolution, and hyperparameter configurations ensures your geospatial deep learning workflows remain fully interpretable and reproducible.


4. Common pitfalls


5. Mini task

Training on your laptop’s 8 GB GPU raises an out-of-memory error at batch_size=8. List two things you would try, in order, before concluding the task is infeasible on your hardware.

Sample solution

First, reduce batch_size to something like 2 or 4, which directly reduces how many regions the model processes simultaneously and is the most common and effective fix for this specific error. If that alone does not resolve it, consider exporting smaller training tiles or choosing a lighter backbone encoder, both mentioned as further options for constrained GPU memory; only after trying these would concluding the task is infeasible on the available hardware be reasonable.


6. Key takeaways

Further reading