Spaces:
Sleeping
Sleeping
Commit
·
d0c450a
1
Parent(s):
99e2d9c
Minor fix
Browse files- utils/downloads.py +103 -0
- utils/metrics.py +397 -0
utils/downloads.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
+
import urllib
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_url(url, check=True):
|
| 12 |
+
# Check if string is URL and check if URL exists
|
| 13 |
+
try:
|
| 14 |
+
url = str(url)
|
| 15 |
+
result = urllib.parse.urlparse(url)
|
| 16 |
+
assert all([result.scheme, result.netloc]) # check if is url
|
| 17 |
+
return (urllib.request.urlopen(url).getcode() == 200) if check else True # check if exists online
|
| 18 |
+
except (AssertionError, urllib.request.HTTPError):
|
| 19 |
+
return False
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def gsutil_getsize(url=''):
|
| 23 |
+
# gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
|
| 24 |
+
s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
|
| 25 |
+
return eval(s.split(' ')[0]) if len(s) else 0 # bytes
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def url_getsize(url='https://ultralytics.com/images/bus.jpg'):
|
| 29 |
+
# Return downloadable file size in bytes
|
| 30 |
+
response = requests.head(url, allow_redirects=True)
|
| 31 |
+
return int(response.headers.get('content-length', -1))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
|
| 35 |
+
# Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
|
| 36 |
+
from utils.general import LOGGER
|
| 37 |
+
|
| 38 |
+
file = Path(file)
|
| 39 |
+
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
|
| 40 |
+
try: # url1
|
| 41 |
+
LOGGER.info(f'Downloading {url} to {file}...')
|
| 42 |
+
torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
|
| 43 |
+
assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
|
| 44 |
+
except Exception as e: # url2
|
| 45 |
+
if file.exists():
|
| 46 |
+
file.unlink() # remove partial downloads
|
| 47 |
+
LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
|
| 48 |
+
os.system(f"curl -# -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
|
| 49 |
+
finally:
|
| 50 |
+
if not file.exists() or file.stat().st_size < min_bytes: # check
|
| 51 |
+
if file.exists():
|
| 52 |
+
file.unlink() # remove partial downloads
|
| 53 |
+
LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
|
| 54 |
+
LOGGER.info('')
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def attempt_download(file, repo='ultralytics/yolov5', release='v7.0'):
|
| 58 |
+
# Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v7.0', etc.
|
| 59 |
+
from utils.general import LOGGER
|
| 60 |
+
|
| 61 |
+
def github_assets(repository, version='latest'):
|
| 62 |
+
# Return GitHub repo tag (i.e. 'v7.0') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...])
|
| 63 |
+
if version != 'latest':
|
| 64 |
+
version = f'tags/{version}' # i.e. tags/v7.0
|
| 65 |
+
response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api
|
| 66 |
+
return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets
|
| 67 |
+
|
| 68 |
+
file = Path(str(file).strip().replace("'", ''))
|
| 69 |
+
if not file.exists():
|
| 70 |
+
# URL specified
|
| 71 |
+
name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
|
| 72 |
+
if str(file).startswith(('http:/', 'https:/')): # download
|
| 73 |
+
url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
|
| 74 |
+
file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
|
| 75 |
+
if Path(file).is_file():
|
| 76 |
+
LOGGER.info(f'Found {url} locally at {file}') # file already exists
|
| 77 |
+
else:
|
| 78 |
+
safe_download(file=file, url=url, min_bytes=1E5)
|
| 79 |
+
return file
|
| 80 |
+
|
| 81 |
+
# GitHub assets
|
| 82 |
+
assets = [f'yolov5{size}{suffix}.pt' for size in 'nsmlx' for suffix in ('', '6', '-cls', '-seg')] # default
|
| 83 |
+
try:
|
| 84 |
+
tag, assets = github_assets(repo, release)
|
| 85 |
+
except Exception:
|
| 86 |
+
try:
|
| 87 |
+
tag, assets = github_assets(repo) # latest release
|
| 88 |
+
except Exception:
|
| 89 |
+
try:
|
| 90 |
+
tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
|
| 91 |
+
except Exception:
|
| 92 |
+
tag = release
|
| 93 |
+
|
| 94 |
+
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
|
| 95 |
+
if name in assets:
|
| 96 |
+
url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror
|
| 97 |
+
safe_download(
|
| 98 |
+
file,
|
| 99 |
+
url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
|
| 100 |
+
min_bytes=1E5,
|
| 101 |
+
error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}')
|
| 102 |
+
|
| 103 |
+
return str(file)
|
utils/metrics.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import warnings
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from utils import TryExcept, threaded
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fitness(x):
|
| 13 |
+
# Model fitness as a weighted combination of metrics
|
| 14 |
+
w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
|
| 15 |
+
return (x[:, :4] * w).sum(1)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def smooth(y, f=0.05):
|
| 19 |
+
# Box filter of fraction f
|
| 20 |
+
nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
|
| 21 |
+
p = np.ones(nf // 2) # ones padding
|
| 22 |
+
yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
|
| 23 |
+
return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16, prefix=""):
|
| 27 |
+
""" Compute the average precision, given the recall and precision curves.
|
| 28 |
+
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
|
| 29 |
+
# Arguments
|
| 30 |
+
tp: True positives (nparray, nx1 or nx10).
|
| 31 |
+
conf: Objectness value from 0-1 (nparray).
|
| 32 |
+
pred_cls: Predicted object classes (nparray).
|
| 33 |
+
target_cls: True object classes (nparray).
|
| 34 |
+
plot: Plot precision-recall curve at mAP@0.5
|
| 35 |
+
save_dir: Plot save directory
|
| 36 |
+
# Returns
|
| 37 |
+
The average precision as computed in py-faster-rcnn.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# Sort by objectness
|
| 41 |
+
i = np.argsort(-conf)
|
| 42 |
+
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
|
| 43 |
+
|
| 44 |
+
# Find unique classes
|
| 45 |
+
unique_classes, nt = np.unique(target_cls, return_counts=True)
|
| 46 |
+
nc = unique_classes.shape[0] # number of classes, number of detections
|
| 47 |
+
|
| 48 |
+
# Create Precision-Recall curve and compute AP for each class
|
| 49 |
+
px, py = np.linspace(0, 1, 1000), [] # for plotting
|
| 50 |
+
ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
|
| 51 |
+
for ci, c in enumerate(unique_classes):
|
| 52 |
+
i = pred_cls == c
|
| 53 |
+
n_l = nt[ci] # number of labels
|
| 54 |
+
n_p = i.sum() # number of predictions
|
| 55 |
+
if n_p == 0 or n_l == 0:
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
# Accumulate FPs and TPs
|
| 59 |
+
fpc = (1 - tp[i]).cumsum(0)
|
| 60 |
+
tpc = tp[i].cumsum(0)
|
| 61 |
+
|
| 62 |
+
# Recall
|
| 63 |
+
recall = tpc / (n_l + eps) # recall curve
|
| 64 |
+
r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
|
| 65 |
+
|
| 66 |
+
# Precision
|
| 67 |
+
precision = tpc / (tpc + fpc) # precision curve
|
| 68 |
+
p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
|
| 69 |
+
|
| 70 |
+
# AP from recall-precision curve
|
| 71 |
+
for j in range(tp.shape[1]):
|
| 72 |
+
ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
|
| 73 |
+
if plot and j == 0:
|
| 74 |
+
py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
|
| 75 |
+
|
| 76 |
+
# Compute F1 (harmonic mean of precision and recall)
|
| 77 |
+
f1 = 2 * p * r / (p + r + eps)
|
| 78 |
+
names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
|
| 79 |
+
names = dict(enumerate(names)) # to dict
|
| 80 |
+
if plot:
|
| 81 |
+
plot_pr_curve(px, py, ap, Path(save_dir) / f'{prefix}PR_curve.png', names)
|
| 82 |
+
plot_mc_curve(px, f1, Path(save_dir) / f'{prefix}F1_curve.png', names, ylabel='F1')
|
| 83 |
+
plot_mc_curve(px, p, Path(save_dir) / f'{prefix}P_curve.png', names, ylabel='Precision')
|
| 84 |
+
plot_mc_curve(px, r, Path(save_dir) / f'{prefix}R_curve.png', names, ylabel='Recall')
|
| 85 |
+
|
| 86 |
+
i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
|
| 87 |
+
p, r, f1 = p[:, i], r[:, i], f1[:, i]
|
| 88 |
+
tp = (r * nt).round() # true positives
|
| 89 |
+
fp = (tp / (p + eps) - tp).round() # false positives
|
| 90 |
+
return tp, fp, p, r, f1, ap, unique_classes.astype(int)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def compute_ap(recall, precision):
|
| 94 |
+
""" Compute the average precision, given the recall and precision curves
|
| 95 |
+
# Arguments
|
| 96 |
+
recall: The recall curve (list)
|
| 97 |
+
precision: The precision curve (list)
|
| 98 |
+
# Returns
|
| 99 |
+
Average precision, precision curve, recall curve
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
# Append sentinel values to beginning and end
|
| 103 |
+
mrec = np.concatenate(([0.0], recall, [1.0]))
|
| 104 |
+
mpre = np.concatenate(([1.0], precision, [0.0]))
|
| 105 |
+
|
| 106 |
+
# Compute the precision envelope
|
| 107 |
+
mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
|
| 108 |
+
|
| 109 |
+
# Integrate area under curve
|
| 110 |
+
method = 'interp' # methods: 'continuous', 'interp'
|
| 111 |
+
if method == 'interp':
|
| 112 |
+
x = np.linspace(0, 1, 101) # 101-point interp (COCO)
|
| 113 |
+
ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
|
| 114 |
+
else: # 'continuous'
|
| 115 |
+
i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
|
| 116 |
+
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
|
| 117 |
+
|
| 118 |
+
return ap, mpre, mrec
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class ConfusionMatrix:
|
| 122 |
+
# Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
|
| 123 |
+
def __init__(self, nc, conf=0.25, iou_thres=0.45):
|
| 124 |
+
self.matrix = np.zeros((nc + 1, nc + 1))
|
| 125 |
+
self.nc = nc # number of classes
|
| 126 |
+
self.conf = conf
|
| 127 |
+
self.iou_thres = iou_thres
|
| 128 |
+
|
| 129 |
+
def process_batch(self, detections, labels):
|
| 130 |
+
"""
|
| 131 |
+
Return intersection-over-union (Jaccard index) of boxes.
|
| 132 |
+
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
|
| 133 |
+
Arguments:
|
| 134 |
+
detections (Array[N, 6]), x1, y1, x2, y2, conf, class
|
| 135 |
+
labels (Array[M, 5]), class, x1, y1, x2, y2
|
| 136 |
+
Returns:
|
| 137 |
+
None, updates confusion matrix accordingly
|
| 138 |
+
"""
|
| 139 |
+
if detections is None:
|
| 140 |
+
gt_classes = labels.int()
|
| 141 |
+
for gc in gt_classes:
|
| 142 |
+
self.matrix[self.nc, gc] += 1 # background FN
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
detections = detections[detections[:, 4] > self.conf]
|
| 146 |
+
gt_classes = labels[:, 0].int()
|
| 147 |
+
detection_classes = detections[:, 5].int()
|
| 148 |
+
iou = box_iou(labels[:, 1:], detections[:, :4])
|
| 149 |
+
|
| 150 |
+
x = torch.where(iou > self.iou_thres)
|
| 151 |
+
if x[0].shape[0]:
|
| 152 |
+
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
|
| 153 |
+
if x[0].shape[0] > 1:
|
| 154 |
+
matches = matches[matches[:, 2].argsort()[::-1]]
|
| 155 |
+
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
|
| 156 |
+
matches = matches[matches[:, 2].argsort()[::-1]]
|
| 157 |
+
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
|
| 158 |
+
else:
|
| 159 |
+
matches = np.zeros((0, 3))
|
| 160 |
+
|
| 161 |
+
n = matches.shape[0] > 0
|
| 162 |
+
m0, m1, _ = matches.transpose().astype(int)
|
| 163 |
+
for i, gc in enumerate(gt_classes):
|
| 164 |
+
j = m0 == i
|
| 165 |
+
if n and sum(j) == 1:
|
| 166 |
+
self.matrix[detection_classes[m1[j]], gc] += 1 # correct
|
| 167 |
+
else:
|
| 168 |
+
self.matrix[self.nc, gc] += 1 # true background
|
| 169 |
+
|
| 170 |
+
if n:
|
| 171 |
+
for i, dc in enumerate(detection_classes):
|
| 172 |
+
if not any(m1 == i):
|
| 173 |
+
self.matrix[dc, self.nc] += 1 # predicted background
|
| 174 |
+
|
| 175 |
+
def matrix(self):
|
| 176 |
+
return self.matrix
|
| 177 |
+
|
| 178 |
+
def tp_fp(self):
|
| 179 |
+
tp = self.matrix.diagonal() # true positives
|
| 180 |
+
fp = self.matrix.sum(1) - tp # false positives
|
| 181 |
+
# fn = self.matrix.sum(0) - tp # false negatives (missed detections)
|
| 182 |
+
return tp[:-1], fp[:-1] # remove background class
|
| 183 |
+
|
| 184 |
+
@TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')
|
| 185 |
+
def plot(self, normalize=True, save_dir='', names=()):
|
| 186 |
+
import seaborn as sn
|
| 187 |
+
|
| 188 |
+
array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
|
| 189 |
+
array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
|
| 190 |
+
|
| 191 |
+
fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
|
| 192 |
+
nc, nn = self.nc, len(names) # number of classes, names
|
| 193 |
+
sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
|
| 194 |
+
labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
|
| 195 |
+
ticklabels = (names + ['background']) if labels else "auto"
|
| 196 |
+
with warnings.catch_warnings():
|
| 197 |
+
warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
|
| 198 |
+
sn.heatmap(array,
|
| 199 |
+
ax=ax,
|
| 200 |
+
annot=nc < 30,
|
| 201 |
+
annot_kws={
|
| 202 |
+
"size": 8},
|
| 203 |
+
cmap='Blues',
|
| 204 |
+
fmt='.2f',
|
| 205 |
+
square=True,
|
| 206 |
+
vmin=0.0,
|
| 207 |
+
xticklabels=ticklabels,
|
| 208 |
+
yticklabels=ticklabels).set_facecolor((1, 1, 1))
|
| 209 |
+
ax.set_ylabel('True')
|
| 210 |
+
ax.set_ylabel('Predicted')
|
| 211 |
+
ax.set_title('Confusion Matrix')
|
| 212 |
+
fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
|
| 213 |
+
plt.close(fig)
|
| 214 |
+
|
| 215 |
+
def print(self):
|
| 216 |
+
for i in range(self.nc + 1):
|
| 217 |
+
print(' '.join(map(str, self.matrix[i])))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class WIoU_Scale:
|
| 221 |
+
''' monotonous: {
|
| 222 |
+
None: origin v1
|
| 223 |
+
True: monotonic FM v2
|
| 224 |
+
False: non-monotonic FM v3
|
| 225 |
+
}
|
| 226 |
+
momentum: The momentum of running mean'''
|
| 227 |
+
|
| 228 |
+
iou_mean = 1.
|
| 229 |
+
monotonous = False
|
| 230 |
+
_momentum = 1 - 0.5 ** (1 / 7000)
|
| 231 |
+
_is_train = True
|
| 232 |
+
|
| 233 |
+
def __init__(self, iou):
|
| 234 |
+
self.iou = iou
|
| 235 |
+
self._update(self)
|
| 236 |
+
|
| 237 |
+
@classmethod
|
| 238 |
+
def _update(cls, self):
|
| 239 |
+
if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
|
| 240 |
+
cls._momentum * self.iou.detach().mean().item()
|
| 241 |
+
|
| 242 |
+
@classmethod
|
| 243 |
+
def _scaled_loss(cls, self, gamma=1.9, delta=3):
|
| 244 |
+
if isinstance(self.monotonous, bool):
|
| 245 |
+
if self.monotonous:
|
| 246 |
+
return (self.iou.detach() / self.iou_mean).sqrt()
|
| 247 |
+
else:
|
| 248 |
+
beta = self.iou.detach() / self.iou_mean
|
| 249 |
+
alpha = delta * torch.pow(gamma, beta - delta)
|
| 250 |
+
return beta / alpha
|
| 251 |
+
return 1
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, MDPIoU=False, feat_h=640, feat_w=640, eps=1e-7):
|
| 255 |
+
# Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
|
| 256 |
+
|
| 257 |
+
# Get the coordinates of bounding boxes
|
| 258 |
+
if xywh: # transform from xywh to xyxy
|
| 259 |
+
(x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
|
| 260 |
+
w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
|
| 261 |
+
b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
|
| 262 |
+
b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
|
| 263 |
+
else: # x1, y1, x2, y2 = box1
|
| 264 |
+
b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
|
| 265 |
+
b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
|
| 266 |
+
w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
|
| 267 |
+
w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
|
| 268 |
+
|
| 269 |
+
# Intersection area
|
| 270 |
+
inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
|
| 271 |
+
(torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
|
| 272 |
+
|
| 273 |
+
# Union Area
|
| 274 |
+
union = w1 * h1 + w2 * h2 - inter + eps
|
| 275 |
+
|
| 276 |
+
# IoU
|
| 277 |
+
iou = inter / union
|
| 278 |
+
if CIoU or DIoU or GIoU:
|
| 279 |
+
cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
|
| 280 |
+
ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
|
| 281 |
+
if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
|
| 282 |
+
c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
|
| 283 |
+
rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
|
| 284 |
+
if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
|
| 285 |
+
v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
|
| 286 |
+
with torch.no_grad():
|
| 287 |
+
alpha = v / (v - iou + (1 + eps))
|
| 288 |
+
return iou - (rho2 / c2 + v * alpha) # CIoU
|
| 289 |
+
return iou - rho2 / c2 # DIoU
|
| 290 |
+
c_area = cw * ch + eps # convex area
|
| 291 |
+
return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
|
| 292 |
+
elif MDPIoU:
|
| 293 |
+
d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
|
| 294 |
+
d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
|
| 295 |
+
mpdiou_hw_pow = feat_h ** 2 + feat_w ** 2
|
| 296 |
+
return iou - d1 / mpdiou_hw_pow - d2 / mpdiou_hw_pow # MPDIoU
|
| 297 |
+
return iou # IoU
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def box_iou(box1, box2, eps=1e-7):
|
| 301 |
+
# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
|
| 302 |
+
"""
|
| 303 |
+
Return intersection-over-union (Jaccard index) of boxes.
|
| 304 |
+
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
|
| 305 |
+
Arguments:
|
| 306 |
+
box1 (Tensor[N, 4])
|
| 307 |
+
box2 (Tensor[M, 4])
|
| 308 |
+
Returns:
|
| 309 |
+
iou (Tensor[N, M]): the NxM matrix containing the pairwise
|
| 310 |
+
IoU values for every element in boxes1 and boxes2
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
|
| 314 |
+
(a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)
|
| 315 |
+
inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)
|
| 316 |
+
|
| 317 |
+
# IoU = inter / (area1 + area2 - inter)
|
| 318 |
+
return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def bbox_ioa(box1, box2, eps=1e-7):
|
| 322 |
+
"""Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
|
| 323 |
+
box1: np.array of shape(nx4)
|
| 324 |
+
box2: np.array of shape(mx4)
|
| 325 |
+
returns: np.array of shape(nxm)
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
# Get the coordinates of bounding boxes
|
| 329 |
+
b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
|
| 330 |
+
b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
|
| 331 |
+
|
| 332 |
+
# Intersection area
|
| 333 |
+
inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \
|
| 334 |
+
(np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)
|
| 335 |
+
|
| 336 |
+
# box2 area
|
| 337 |
+
box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
|
| 338 |
+
|
| 339 |
+
# Intersection over box2 area
|
| 340 |
+
return inter_area / box2_area
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def wh_iou(wh1, wh2, eps=1e-7):
|
| 344 |
+
# Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
|
| 345 |
+
wh1 = wh1[:, None] # [N,1,2]
|
| 346 |
+
wh2 = wh2[None] # [1,M,2]
|
| 347 |
+
inter = torch.min(wh1, wh2).prod(2) # [N,M]
|
| 348 |
+
return inter / (wh1.prod(2) + wh2.prod(2) - inter + eps) # iou = inter / (area1 + area2 - inter)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# Plots ----------------------------------------------------------------------------------------------------------------
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@threaded
|
| 355 |
+
def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
|
| 356 |
+
# Precision-recall curve
|
| 357 |
+
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
|
| 358 |
+
py = np.stack(py, axis=1)
|
| 359 |
+
|
| 360 |
+
if 0 < len(names) < 21: # display per-class legend if < 21 classes
|
| 361 |
+
for i, y in enumerate(py.T):
|
| 362 |
+
ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
|
| 363 |
+
else:
|
| 364 |
+
ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
|
| 365 |
+
|
| 366 |
+
ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
|
| 367 |
+
ax.set_xlabel('Recall')
|
| 368 |
+
ax.set_ylabel('Precision')
|
| 369 |
+
ax.set_xlim(0, 1)
|
| 370 |
+
ax.set_ylim(0, 1)
|
| 371 |
+
ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
|
| 372 |
+
ax.set_title('Precision-Recall Curve')
|
| 373 |
+
fig.savefig(save_dir, dpi=250)
|
| 374 |
+
plt.close(fig)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@threaded
|
| 378 |
+
def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
|
| 379 |
+
# Metric-confidence curve
|
| 380 |
+
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
|
| 381 |
+
|
| 382 |
+
if 0 < len(names) < 21: # display per-class legend if < 21 classes
|
| 383 |
+
for i, y in enumerate(py):
|
| 384 |
+
ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
|
| 385 |
+
else:
|
| 386 |
+
ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
|
| 387 |
+
|
| 388 |
+
y = smooth(py.mean(0), 0.05)
|
| 389 |
+
ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
|
| 390 |
+
ax.set_xlabel(xlabel)
|
| 391 |
+
ax.set_ylabel(ylabel)
|
| 392 |
+
ax.set_xlim(0, 1)
|
| 393 |
+
ax.set_ylim(0, 1)
|
| 394 |
+
ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
|
| 395 |
+
ax.set_title(f'{ylabel}-Confidence Curve')
|
| 396 |
+
fig.savefig(save_dir, dpi=250)
|
| 397 |
+
plt.close(fig)
|