Skip to main content
Open In Colab

Faster R-CNN Hyperparameter Optimization with Optuna + W&B (COCO MiniTrain) and Small-Object Transfer (Drones)

This notebook is the deliverable for the assignment:
  • Training dataset: COCO MiniTrain (COCO-format subset)
    https://github.com/giddyyupp/coco-minitrain
  • Optimization engine: Optuna (TPE + pruning)
  • Experiment tracking: Weights & Biases (W&B) (logging + dashboards)
  • Generalization test: drone small-object detection (Assignment 3 dataset)
You will:
  1. Run a baseline Faster R-CNN on COCO MiniTrain.
  2. Run stage-wise hyperparameter optimization with Optuna.
  3. Log all runs to W&B and analyze them in the W&B UI.
  4. Evaluate the tuned detector on the drone dataset and discuss transfer.

What you must submit

  • A shareable link to your W&B project (public or access granted to the TA).
  • This notebook (executed), including:
    • baseline run
    • Optuna study runs with pruning
    • final 3-seed retraining
    • drone evaluation (baseline vs tuned)
    • analysis cells (plots + written answers)

Metrics

You must report COCO-style metrics:
  • mAP\mathrm{mAP} (COCO mAP@[0.5:0.950.5:0.95])
  • AP50\mathrm{AP}_{50} and AP75\mathrm{AP}_{75}
  • Recall (COCO AR or a simpler recall estimate)

Objective (default)

You will optimize validation COCO mAP: maxθ  mAPval(θ),\max_{\theta}\; \mathrm{mAP}_{\text{val}}(\theta), where θ\theta denotes the hyperparameters under search.
If you want to trade off latency, define a scalarized objective: J(θ)=mAPval(θ)λLatency(θ).J(\theta)=\mathrm{mAP}_{\text{val}}(\theta)-\lambda\,\mathrm{Latency}(\theta). In that case, you must define λ\lambda and measure latency consistently.

0. Colab setup

  1. Enable GPU: Runtime → Change runtime type → GPU
  2. Install packages
  3. Login to W&B

1. Reproducibility (required)

You must fix and log:
  • random seeds
  • dataset split indices
  • code version (commit hash, if applicable)
You will run final training with 3 different seeds and report: mean mAP±std.\text{mean mAP} \pm \text{std}.

2. Dataset: COCO MiniTrain

Clone the dataset repo and set paths below. COCO MiniTrain repository: https://github.com/giddyyupp/coco-minitrain You will create a deterministic train/val split.

Required outputs

  • train_ids.json and val_ids.json saved to disk
  • logged to W&B as artifacts (optional but encouraged)

3. PyTorch dataset and transforms

You must keep transforms simple initially. Use augmentations only after baseline correctness is established. Recommended minimal transforms:
  • Convert to tensor
  • (Optional) resize to a fixed shorter side (be consistent across runs)

4. Model: Faster R-CNN (torchvision)

You will use:
  • torchvision.models.detection.fasterrcnn_resnet50_fpn
You will also tune RPN and RoI head hyperparameters in later stages.

5. Training and evaluation

You will implement:
  • a training loop that logs loss components
  • COCO evaluation via pycocotools.cocoeval.COCOeval

Important notes

  • COCO category IDs are not always contiguous. Torchvision expects contiguous class indices when you replace heads.
  • For this assignment you will keep the default COCO label space and use the pretrained COCO model, then fine-tune on COCO MiniTrain.

6. Baseline run (required)

Run a baseline training job and log to W&B. Required:
  • train loss curves (total + components)
  • validation metrics: mAP, AP50, AP75
  • save the model checkpoint

7. Optuna + W&B: stage-wise hyperparameter optimization (required)

You will run Optuna studies in stages.
  • Stage 1: optimizer dynamics (LR, weight decay, momentum, warmup)
  • Stage 2: RPN hyperparameters
  • Stage 3: RoI head hyperparameters
  • Stage 4: post-processing calibration (no training)
You must use:
  • TPESampler
  • pruning (MedianPruner or HyperbandPruner)
Each trial must:
  1. Train for a small budget (e.g., 3–5 epochs),
  2. Report intermediate validation mAP via trial.report(...),
  3. Allow Optuna to prune underperforming trials.
Default objective: maxmAPval.\max \mathrm{mAP}_{\text{val}}.

8. Stage 2: RPN tuning (required)

Fix the best Stage 1 hyperparameters, then tune RPN knobs that affect proposal quality and recall. Suggested search space:
  • rpn_nms_thresh in [0.5,0.9][0.5, 0.9]
  • rpn_pre_nms_topk in [1000,4000][1000, 4000]
  • rpn_post_nms_topk in [300,2000][300, 2000]
  • rpn_fg_iou_thresh in [0.5,0.8][0.5, 0.8]
  • rpn_bg_iou_thresh in [0.0,0.4][0.0, 0.4]
  • rpn_batch_size_per_image in [128,512][128, 512]
  • rpn_positive_fraction in [0.25,0.75][0.25, 0.75]
You will implement this by mutating the torchvision model components:
  • model.rpn.* fields (where supported)
Note: torchvision does not expose every parameter as a public attribute in every version; implement what is available and document what you tuned.

9. Stage 3: RoI head tuning (required)

Fix Stage 1+2 best configuration and tune RoI head sampling and loss weighting. Suggested search space:
  • roi_batch_size_per_image in [128,512][128, 512]
  • roi_positive_fraction in [0.1,0.5][0.1, 0.5]
  • cls_loss_weight in [0.5,2.0][0.5, 2.0]
  • box_loss_weight in [0.5,2.0][0.5, 2.0]
Implementation note:
  • Torchvision ROIHeads exposes sampler parameters.
  • Loss weights might require applying weights to loss terms manually (by scaling loss_dict before summing). You will implement that by creating a custom train_one_epoch_weighted below.

10. Stage 4: post-processing calibration (required)

You will tune score threshold and NMS IoU threshold without retraining. Suggested ranges:
  • score_thresh in [0.01,0.5][0.01, 0.5]
  • box_nms_thresh in [0.3,0.7][0.3, 0.7]
In torchvision:
  • model.roi_heads.score_thresh
  • model.roi_heads.nms_thresh
  • model.roi_heads.detections_per_img
You will:
  1. Train one final model using the best Stage 1+2+3 configuration (longer epochs, e.g., 10–15).
  2. Run an Optuna study that only changes post-processing parameters and evaluates on val.

11. Final multi-seed retraining (required)

Retrain the best configuration (Stages 1–4) with 3 different seeds and report: mean mAP±std.\text{mean mAP} \pm \text{std}. You must log all runs to W&B and include the W&B links in your report.

12. Small-object transfer test: drones (extra credit)

You must evaluate:
  • baseline COCO MiniTrain fine-tuned model (Section 6)
  • tuned model (best configuration from Sections 7–11)
on the drone dataset defined in Assignment 3: https://aegean.ai/aiml-common/assignments/main/cv-spring-2026/assignment-3

Requirements

  1. Do not retune hyperparameters on drones initially.
  2. Compute at least:
    • mAP\mathrm{mAP}, AP50\mathrm{AP}_{50}, recall (or COCO AR)
  3. Provide qualitative results showing:
    • missed small drones
    • duplicates / NMS issues
    • low-confidence detections

Implementation note

You must make the drone dataset available in COCO format (images + instances JSON). Set the paths below accordingly.

13. Required written answers (include in your report)

Answer these questions using evidence (W&B plots, metrics, qualitative results):
  1. Which Stage (1–4) delivered the largest gain in mAP\mathrm{mAP}? Why?
  2. Which hyperparameters most influenced small-object recall on drones?
  3. Did increasing rpn_pre_nms_topk help drone detection? Explain using proposal reasoning.
  4. Did changing NMS thresholds change the duplicate-box failure mode? Provide examples.
  5. Is the tuned configuration robust across seeds? Use mean±std\text{mean}\pm\text{std}.