
Plot Diagnostic Evaluations and Performance Curves for YOLO Models
Source:R/utils_yolo_train.R
plot.yolo_train.RdGenerates high-resolution, publication-ready base R vector graphics for evaluating trained YOLO models. Supports multi-panel overview dashboards, confusion matrices (raw counts and normalized rates), precision-recall (PR) curves, confidence vs. F1-score curves, and epoch-wise loss/metric progressions.
Usage
# S3 method for class 'yolo_train'
plot(
x,
which = c("all", "metrics", "confusion_matrix_norm", "confusion_matrix", "pr_curve",
"f1_curve", "results", "labels"),
native = TRUE,
bg = "white",
mar = 0.5,
ncol = NULL,
nrow = NULL,
digits = 3,
save = FALSE,
file_name = NULL,
width = NULL,
height = NULL,
dpi = 300,
...
)Arguments
- x
An object of class
yolo_trainor character path/name of a model.- which
Which plot to display. One of:
"all"(default): A 2x2 high-resolution diagnostic dashboard with Loss curves, Validation mAP progression, Confusion Matrix, and Precision-Recall curve."metrics": High-resolution native R vector curves plotting loss, mAP, precision, and recall progression fromresults.csv."confusion_matrix_norm": Normalized confusion matrix heatmap (counts + rates)."confusion_matrix": Raw count confusion matrix heatmap."pr_curve": Precision-Recall (PR) curve with shaded area under the curve and mAP50."f1_curve": F1 score vs. Confidence curve."results": Alias for"metrics"."labels": Dataset label distribution and bounding box correlogram (if available).
- native
Logical. When
TRUE(default), renders crisp, resizable native R base graphic vector plots directly from metrics and CSV evaluation tables rather than displaying raster image files.- bg
Background color for native plots. Defaults to
"white".- mar
Plot margins passed to base graphics. Defaults to
0.5.- ncol
Optional integer. Number of columns in multi-panel layout.
- nrow
Optional integer. Number of rows in multi-panel layout.
- digits
Integer. Number of decimal digits for statistical displays (default
3).- save
Logical. If
TRUE, saves the generated plot to a file. Defaults toFALSE.- file_name
Optional character string. Custom file name or path to save the plot (e.g.
"metrics.png","dashboard.pdf"). If not specified andsave = TRUE, a default filename based on the model name and plotted metric is automatically generated.- width
Numeric. Width of the output plot. If
<= 50, interpreted as inches; if> 50, interpreted as pixels. Defaults to10inches for the multi-panel dashboard (which = "all"),9for metrics curves, and7for single curves.- height
Numeric. Height of the output plot. If
<= 50, interpreted as inches; if> 50, interpreted as pixels. Defaults to8inches for the multi-panel dashboard (which = "all"), and6for single curves.- dpi
Numeric. Resolution in dots per inch (DPI) for raster formats (PNG, JPEG, TIFF). Defaults to
300.- ...
Additional arguments passed to base graphics.
Details
Diagnostic Evaluation Statistics and Mathematical Formulas
1. Spatial Overlap (Intersection over Union, IoU): Given a predicted bounding box or segmentation mask \(\mathcal{B}_{\text{pred}}\) and a ground truth annotation \(\mathcal{B}_{\text{true}}\), the spatial overlap is quantified by the Jaccard index: $$\text{IoU} = \frac{|\mathcal{B}_{\text{pred}} \cap \mathcal{B}_{\text{true}}|}{|\mathcal{B}_{\text{pred}} \cup \mathcal{B}_{\text{true}}|}$$ A detection is designated as a True Positive (TP) if \(\text{IoU} \ge \text{threshold}\) (typically \(0.50\)) and the predicted class matches ground truth.
2. Confusion Matrix with Background Class: Object detection models must detect both the presence and location of objects. Hence, detections can fail by predicting an incorrect class, by hallucinating an object on the background, or by failing to detect a real object. The evaluation matrix \(M\) of dimensions \((N_c + 1) \times (N_c + 1)\) includes the background class:
Cell \((i, j)\) for \(i, j \le N_c\): Ground truth object of class \(i\) predicted as class \(j\). Diagonal entries \(M(i, i)\) represent True Positives (TP).
Last column \((i, N_c + 1)\): Ground truth object of class \(i\) completely missed by the model (misclassified as background, i.e., False Negatives, FN).
Last row \((N_c + 1, j)\): Background region falsely predicted as an object of class \(j\) (i.e., False Positives, FP).
The row-normalized confusion matrix computes the empirical conditional probability \(P(\hat{Y} = j \mid Y = i)\): $$M_{\text{norm}}(i, j) = P(\hat{Y} = j \mid Y = i) = \frac{M(i, j)}{\sum_{k=1}^{N_c + 1} M(i, k)}$$ The diagonal entry \(M_{\text{norm}}(i, i)\) corresponds directly to the per-class Sensitivity (Recall). Conversely, the column-normalized entry represents the empirical precision \(P(Y = i \mid \hat{Y} = j)\): $$M_{\text{prec}}(i, j) = P(Y = i \mid \hat{Y} = j) = \frac{M(i, j)}{\sum_{k=1}^{N_c + 1} M(k, j)}$$
3. Precision and Recall: At any given confidence threshold \(\tau \in [0, 1]\): $$\text{Precision}(\tau) = \frac{\text{TP}(\tau)}{\text{TP}(\tau) + \text{FP}(\tau)}$$ $$\text{Recall}(\tau) = \frac{\text{TP}(\tau)}{\text{TP}(\tau) + \text{FN}(\tau)}$$ Precision measures the accuracy of positive predictions (minimizing false alarms), while Recall measures the completeness of coverage (minimizing missed objects).
4. F1-Score vs. Confidence Curve: The F1-score is the harmonic mean of Precision and Recall as a function of the confidence threshold \(\tau\): $$F_1(\tau) = 2 \times \frac{\text{Precision}(\tau) \times \text{Recall}(\tau)}{\text{Precision}(\tau) + \text{Recall}(\tau)} = \frac{2\,\text{TP}(\tau)}{2\,\text{TP}(\tau) + \text{FP}(\tau) + \text{FN}(\tau)}$$ The peak of this curve identifies the optimal operating threshold \(\tau^*\) that maximizes the harmonic trade-off: $$\tau^* = \arg\max_{\tau} F_1(\tau)$$
5. Precision-Recall (PR) Curve and Average Precision (AP): As the confidence threshold \(\tau\) ranges from 1 down to 0, recall monotonically increases from 0 to 1, while precision generally declines. The interpolated precision \(p_{\text{interp}}(r)\) at recall level \(r\) is the maximum precision achieved at any recall \(\tilde{r} \ge r\): $$p_{\text{interp}}(r) = \max_{\tilde{r} \ge r} p(\tilde{r})$$ Average Precision (AP) is the integral area under this interpolated curve, numerically approximated via the 101-point COCO evaluation grid: $$\text{AP} = \int_{0}^{1} p_{\text{interp}}(r)\,dr \approx \frac{1}{101} \sum_{k=0}^{100} p_{\text{interp}}\left(\frac{k}{100}\right)$$
6. Mean Average Precision (mAP):
mAP@50 (mAP50): Mean AP across all \(N_c\) target classes evaluated at an IoU threshold of \(0.50\): $$\text{mAP50} = \frac{1}{N_c} \sum_{c=1}^{N_c} \text{AP}_c^{(0.50)}$$
mAP@50-95 (mAP50-95): The primary metric of the COCO benchmark, computed as the unweighted mean of mAP across 10 IoU thresholds from \(0.50\) to \(0.95\) in steps of \(0.05\): $$\text{mAP50-95} = \frac{1}{10 \cdot N_c} \sum_{k=0}^{9} \sum_{c=1}^{N_c} \text{AP}_c^{(0.50 + 0.05k)}$$
Interpretation Guide for Diagnostic Plots
which = "all": Displays a 2x2 publication-ready dashboard combining: (1) Training & Validation Loss curves (detecting divergence, underfitting, or overfitting), (2) Validation mAP progression across epochs (with the best epoch highlighted with a star), (3) Normalized Confusion Matrix (identifying frequent misclassifications and background leakage), and (4) Precision-Recall curve with shaded area under the curve (quantifying overall detector precision).which = "confusion_matrix": Displays raw detection counts across all classes and background. High counts in the bottom row indicate excessive false positive background detections; high counts in the rightmost column indicate missed objects.which = "confusion_matrix_norm": Displays normalized conditional probabilities. The diagonal values represent per-class sensitivity (percentage of true objects correctly detected).which = "pr_curve": A steep curve maintaining precision close to 1.0 across high recall indicates a highly robust model with minimal false positives.which = "f1_curve": Used to choose the ideal confidence threshold for downstream inference inimage_detect_dlorimage_segment_dl.which = "metrics": Displays a 2x3 panel of detailed epoch-by-epoch loss curves (box, class, mask), precision, recall, and learning rate schedules.
Examples
if (FALSE) { # interactive()
library(pliman)
# Load diagnostics from a previously trained model
res <- yolo_results("capsulas_det")
# Inspect training summary and plot 2x2 diagnostic dashboard
print(res)
plot(res)
# Save high-resolution 300 DPI publication plots:
plot(res, save = TRUE)
plot(
res,
which = "confusion_matrix_norm",
save = TRUE,
file_name = "fig_cm.png",
width = 8,
height = 7,
dpi = 300
)
plot(res, which = "metrics", save = TRUE, file_name = "fig_metrics.pdf", width = 9, height = 6)
# Plot individual evaluation curves in high-resolution vector format:
plot(res, which = "confusion_matrix")
plot(res, which = "confusion_matrix_norm")
plot(res, which = "pr_curve")
plot(res, which = "f1_curve")
plot(res, which = "metrics")
}