
Train and Fine-Tune YOLO Models for Segmentation or Detection
Source:R/utils_yolo_train.R
yolo_train.RdHigh-level training interface for Ultralytics YOLO models (YOLO26, YOLO11, YOLOv8)
in pliman. Supports instance segmentation (task = "segment") and object
detection (task = "detect"), live formatted training progress, early stopping,
automatic .pt and .onnx export, and rich S3 diagnostic visualization (plot()).
Usage
yolo_train(
data = "yolo_dataset",
model = "yolo26n-seg",
epochs = 50,
imgsz = 640,
batch = 16,
device = "auto",
output_dir = pliman_model_dir(),
output_name = NULL,
results_dir = NULL,
export_pt = TRUE,
resume = FALSE,
checkpoint = TRUE,
checkpoint_onnx = FALSE,
as_job = FALSE,
patience = 15,
lr0 = 0.01,
lrf = 0.01,
optimizer = "auto",
close_mosaic = 10,
amp = NULL,
plots = FALSE,
verbose = TRUE,
progress = NULL,
workers = if (.Platform$OS.type == "windows") 0L else 4L,
auto_install = TRUE,
...
)Arguments
- data
Path to the dataset directory (e.g.
"yolo_dataset"or"pasta"), or to a dataset YAML configuration file (e.g."pasta/data.yaml"or"pasta/dataset.yaml"). Can also be ayolo_datasetobject returned byyolo_dataset_export(),yolo_dataset_autolabel(), oryolo_dataset_tiling(). Defaults to"yolo_dataset".- model
Base pre-trained model architecture to fine-tune. Defaults to
"yolo26n-seg". Can be"yolo26n-seg","yolo26s-seg","yolo11n-seg","yolo26n", or path to a.ptfile.- epochs
Number of training epochs (default
50).- imgsz
Input image resolution for training (default
640).- batch
Batch size (default
16).- device
Device to train on:
"auto"(default),"0"(GPU 0),"cpu", etc.- output_dir
Target directory to save the final exported
.onnxmodel. Defaults topliman_model_dir().- output_name
Filename of the exported model. If
NULL(default), an informative name is automatically created (e.g."yolo_custom_seg.onnx").- results_dir
Directory where training plots, confusion matrices, and
results.csvare permanently preserved. IfNULL(default), creates a folder named<output_name>_resultsinsideoutput_dir.- export_pt
Logical. If
TRUE(default), also exports the PyTorch.ptweights (e.g.,model.pt) alongside the.onnxmodel, allowing future re-training or fine-tuning on more complex datasets.- resume
Logical (
TRUEto automatically resume from the latest checkpoint) or character path pointing to an existinglast.ptcheckpoint file. Defaults toFALSE.- checkpoint
Logical. If
TRUE(default), continuously saves real-time checkpoints: mirrorslast.ptandresults.csvafter each epoch, and copiesbest.ptdirectly toresults_dirandoutput_dirimmediately whenever a new*(best)epoch is reached. This guarantees no progress is lost even if training is interrupted. Defaults toTRUE.- checkpoint_onnx
Logical. If
TRUE, also generates and updates a checkpoint.onnxmodel in real-time whenever a new*(best)epoch is achieved. Defaults toFALSE.- as_job
Logical. If
TRUEand running inside RStudio, launches the training as an asynchronous RStudio Background Job, immediately freeing up the R console while live progress and epoch tables stream in RStudio's "Jobs" tab. Checkpoints continue to be saved in real time, and the resulting model object is automatically saved tomodel_res.rdsinsideresults_dir. Defaults toFALSE.- patience
Early stopping patience in epochs. Defaults to
15.- lr0
Initial learning rate (default
0.01).- lrf
Final learning rate fraction (default
0.01).- optimizer
Optimizer to use (
"auto","SGD","Adam","AdamW","RMSProp"). Default is"auto".- close_mosaic
Disable mosaic augmentation in the last N epochs. Default is
10.- amp
Automatic Mixed Precision (AMP). Set to
FALSEto disable AMP if GPU checks fail. Default isNULL(auto-detected).- plots
Logical. If
FALSE(default), suppresses generation of low-resolution matplotlib raster image files from YOLO; native vector plots are generated directly in R from exported CSV data.- verbose
Logical. Whether to display informative CLI messages during training and export. Defaults to
TRUE.- progress
Optional logical or
NULL. Whether to display a live progress indicator during training (defaults toNULL, following interactive/verbose defaults).- workers
Number of worker threads for data loading. Defaults to
0on Windows and4on Linux/macOS.- auto_install
Logical. If
TRUE, automatically installs missing dependencies viapip. Defaults toTRUE.- ...
Additional arguments passed directly to
model.train()in Ultralytics (e.g.weight_decay = 0.0005,momentum = 0.937,mosaic = 0.5,mixup = 0.1,degrees = 10,box = 7.5,cls = 0.5).
Value
An object of class yolo_train containing:
model_file: Path to the exported.onnxmodel ready forpliman.pt_file: Path to the saved.ptPyTorch weights (ifexport_pt = TRUE).results_dir: Directory containing training plots, metrics, and logs.plots: Named list of file paths to generated diagnostic plots.metrics: Data frame of per-epoch loss and mAP progressions (results.csv).confusion_matrix: Data frame of the final confusion matrix (counts).confusion_matrix_norm: Data frame of the normalized confusion matrix.pr_curve: Data frame of the Precision-Recall curve.f1_curve: Data frame of the F1 vs Confidence curve.best_metrics: Data frame row of the best performing epoch.epochs: Number of epochs trained.elapsed_sec: Elapsed training time in seconds.elapsed_formatted: Formatted training time (e.g."3h 35m 14s").task: Task type ("segment"or"detect").call: Matched function call.
Details
Training Lifecycle and Pipeline
Dataset Structure Verification: Inspects bounding box and polygon coordinates in
data.yamlto confirm task configuration, automatically reconciling task mismatches (e.g. bounding box dataset with segmentation model).Hardware Acceleration: Auto-detects NVIDIA CUDA GPUs with cuDNN acceleration, falling back gracefully to multi-threaded CPU processing.
Pre-trained Weights: Automatically verifies or downloads official pre-trained YOLO weights from NEPEM repositories.
Training Execution: Runs Ultralytics training with real-time CLI feedback, early stopping patience, and automated learning rate scheduling.
Pure Numerical Evaluation Export: Extracts tabular CSV metrics (
confusion_matrix.csv,confusion_matrix_normalized.csv,pr_curve.csv,f1_curve.csv, andresults.csv) while suppressing low-resolution matplotlib raster images.Dual Model Export: Saves both PyTorch
.ptweights (enabling future fine-tuning or transfer learning) and optimized.onnxmodels (for pure C++ inference via ONNX Runtime inplimanwithout requiring Python).
Loss Functions and Mathematical Formulations
YOLO models optimize a composite multi-task objective balancing bounding box regression, classification, boundary distribution focal loss, and (for instance segmentation) pixel-wise mask prediction: $$\mathcal{L}_{\text{total}} = \lambda_{\text{box}} \mathcal{L}_{\text{box}} + \lambda_{\text{cls}} \mathcal{L}_{\text{cls}} + \lambda_{\text{dfl}} \mathcal{L}_{\text{dfl}} + \lambda_{\text{seg}} \mathcal{L}_{\text{seg}}$$
1. Complete IoU (CIoU) Bounding Box Loss (\(\mathcal{L}_{\text{box}}\)): Bounding box regression uses the Complete IoU loss, which penalizes bounding box overlap error, normalized distance between center coordinates, and aspect ratio discrepancy: $$\mathcal{L}_{\text{CIoU}} = 1 - \text{IoU} + \frac{\rho^2(b, b^{\text{gt}})}{c^2} + \alpha v$$ where \(\rho(b, b^{\text{gt}})\) is the Euclidean distance between the center points of predicted box \(b\) and ground truth box \(b^{\text{gt}}\), \(c\) is the diagonal length of the smallest enclosing bounding box covering both boxes, and \(v\) quantifies aspect ratio consistency: $$v = \frac{4}{\pi^2} \left( \arctan\frac{w^{\text{gt}}}{h^{\text{gt}}} - \arctan\frac{w}{h} \right)^2$$ $$\alpha = \frac{v}{(1 - \text{IoU}) + v}$$
2. Classification Loss (\(\mathcal{L}_{\text{cls}}\)): Class probabilities are optimized using Binary Cross-Entropy (BCE) with sigmoid activation across all classes: $$\mathcal{L}_{\text{cls}} = -\frac{1}{N_c} \sum_{c=1}^{N_c} \left[ y_c \log(\hat{y}_c) + (1 - y_c) \log(1 - \hat{y}_c) \right]$$ where \(y_c \in \{0, 1\}\) represents ground truth class membership and \(\hat{y}_c \in [0, 1]\) is the predicted class probability.
3. Instance Segmentation Mask Loss (\(\mathcal{L}_{\text{seg}}\)): For segmentation models, a pixel-wise binary cross-entropy loss compares the predicted prototype mask \(\hat{M}\) with the ground truth binary mask \(M\) across mask domain \(\Omega\): $$\mathcal{L}_{\text{seg}} = -\frac{1}{|\Omega|} \sum_{(x,y) \in \Omega} \left[ M(x,y) \log \hat{M}(x,y) + (1 - M(x,y)) \log(1 - \hat{M}(x,y)) \right]$$
4. Distribution Focal Loss (\(\mathcal{L}_{\text{dfl}}\)): DFL models continuous bounding box coordinates \(y\) as probability distributions over discrete bins \(\{y_i, y_{i+1}\}\) around the target edges: $$\mathcal{L}_{\text{dfl}}(S_i, S_{i+1}) = -\left[ (y_{i+1} - y) \log(S_i) + (y - y_i) \log(S_{i+1}) \right]$$ where \(S_i\) and \(S_{i+1}\) are softmax probabilities of adjacent integer anchor bins satisfying \(y_i \le y \le y_{i+1}\). This enables flexible sub-pixel boundary localization even under heavy occlusion or blurred object boundaries.
5. Cosine Annealing Learning Rate Schedule: During the warm-up phase (\(t < T_{\text{warm}}\)), the learning rate increases linearly from 0 to \(\eta_0\). For remaining epochs (\(t \ge T_{\text{warm}}\)), the learning rate decays according to a cosine annealing schedule: $$\eta_t = \eta_{\text{final}} + \frac{1}{2} (\eta_0 - \eta_{\text{final}}) \left( 1 + \cos\left( \frac{t - T_{\text{warm}}}{T_{\text{max}} - T_{\text{warm}}} \pi \right) \right)$$ where \(\eta_0 = \text{lr0}\) and \(\eta_{\text{final}} = \text{lr0} \times \text{lrf}\).
Examples
if (FALSE) { # interactive()
library(pliman)
# 1. Train a custom coffee grain segmentation model with real-time checkpointing
model_res <- yolo_train(
data = "dataset_cafe", # or "dataset_cafe/data.yaml"
model = "yolo26n-seg",
epochs = 30,
output_name = "cafe_seg.onnx"
)
# 2. Resume training seamlessly from the last saved checkpoint if interrupted:
yolo_train(data = "dataset_cafe", resume = TRUE, epochs = 50)
# Inspect training summary and plot diagnostic dashboard
print(model_res)
plot(model_res)
# Plot specific evaluation curves:
plot(model_res, which = "confusion_matrix")
plot(model_res, which = "pr_curve")
plot(model_res, which = "metrics")
# Run inference with your new model directly in pliman!
img <- image_import("cafe.jpeg")
seg <- image_segment_dl(img, model = model_res$model_file, type = "highlight")
}