From 567397d67ae173fb82e06672a763cc28c5cfeb2b Mon Sep 17 00:00:00 2001
From: jbutle55 <justin.butler12@hotmail.ca>
Date: Fri, 29 Jul 2022 06:06:23 -0600
Subject: [PATCH] Fix confusion matrix update when no predictions are made
 (#8748)

* Fix confusion matrix update when no predictions are made

* Update metrics.py

* Simply confusion matrix changes

* Simply confusion matrix fix

Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
---
 utils/metrics.py | 6 ++++++
 val.py           | 2 ++
 2 files changed, 8 insertions(+)

diff --git a/utils/metrics.py b/utils/metrics.py
index 6bba4cfe2..9bf084c78 100644
--- a/utils/metrics.py
+++ b/utils/metrics.py
@@ -139,6 +139,12 @@ class ConfusionMatrix:
         Returns:
             None, updates confusion matrix accordingly
         """
+        if detections is None:
+            gt_classes = labels.int()
+            for i, gc in enumerate(gt_classes):
+                self.matrix[self.nc, gc] += 1  # background FN
+            return
+
         detections = detections[detections[:, 4] > self.conf]
         gt_classes = labels[:, 0].int()
         detection_classes = detections[:, 5].int()
diff --git a/val.py b/val.py
index b0cc8e7f1..48207a113 100644
--- a/val.py
+++ b/val.py
@@ -228,6 +228,8 @@ def run(
             if npr == 0:
                 if nl:
                     stats.append((correct, *torch.zeros((2, 0), device=device), labels[:, 0]))
+                    if plots:
+                        confusion_matrix.process_batch(detections=None, labels=labels[:, 0])
                 continue
 
             # Predictions