From 075e6b9fd04ddbc5dc3416b3873617006d11f58b Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:16:49 +0800 Subject: [PATCH 01/18] Fix E722, do not use bare 'except' --- models/yolo.py | 2 +- utils/datasets.py | 4 ++-- utils/downloads.py | 5 +++-- utils/general.py | 13 +++++++------ utils/metrics.py | 4 ++-- utils/plots.py | 6 +++--- utils/torch_utils.py | 4 ++-- 7 files changed, 20 insertions(+), 18 deletions(-) diff --git a/models/yolo.py b/models/yolo.py index 5d19aad5369f..e6f3afb76722 100644 --- a/models/yolo.py +++ b/models/yolo.py @@ -233,7 +233,7 @@ def parse_model(d, ch): # model_dict, input_channels(3) for j, a in enumerate(args): try: args[j] = eval(a) if isinstance(a, str) else a # eval strings - except: + except NameError: pass n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain diff --git a/utils/datasets.py b/utils/datasets.py index a54e29fd2908..553bf185d810 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -60,7 +60,7 @@ def exif_size(img): s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) - except: + except KeyError: pass return s @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except: + except AssertionError: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache diff --git a/utils/downloads.py b/utils/downloads.py index eafa3b7ac309..3313f319416b 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -59,12 +59,13 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] tag = response['tag_name'] # i.e. 'v1.0' - except: # fallback plan + except requests.exceptions.RequestException as e: # fallback plan + print(str(e)) # Print the general exception assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] try: tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] - except: + except subprocess.CalledProcessError: tag = 'v5.0' # current release if name in assets: diff --git a/utils/general.py b/utils/general.py index f2afb480cc63..628692bad34a 100755 --- a/utils/general.py +++ b/utils/general.py @@ -152,7 +152,7 @@ def is_colab(): try: import google.colab return True - except Exception as e: + except ImportError: return False @@ -160,6 +160,7 @@ def is_pip(): # Is file in a pip package? return 'site-packages' in Path(__file__).resolve().parts + def is_ascii(s=''): # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) s = str(s) # convert list, tuple, None, etc. to str @@ -741,11 +742,11 @@ def print_mutation(results, hyp, save_dir, bucket): data = pd.read_csv(evolve_csv) data = data.rename(columns=lambda x: x.strip()) # strip keys i = np.argmax(fitness(data.values[:, :7])) # - f.write(f'# YOLOv5 Hyperparameter Evolution Results\n' + - f'# Best generation: {i}\n' + - f'# Last generation: {len(data)}\n' + - f'# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' + - f'# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') + f.write('# YOLOv5 Hyperparameter Evolution Results\n' + + f'# Best generation: {i}\n' + + f'# Last generation: {len(data)}\n' + + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' + + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') yaml.safe_dump(hyp, f, sort_keys=False) if bucket: diff --git a/utils/metrics.py b/utils/metrics.py index 4f1b5e2d2c2d..0f8b69c12bd8 100644 --- a/utils/metrics.py +++ b/utils/metrics.py @@ -216,8 +216,8 @@ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps= ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared - rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + - (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared if DIoU: return iou - rho2 / c2 # DIoU elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 diff --git a/utils/plots.py b/utils/plots.py index 2f98d5b7e630..3172f380f063 100644 --- a/utils/plots.py +++ b/utils/plots.py @@ -54,8 +54,8 @@ def check_font(font='Arial.ttf', size=10): font = font if font.exists() else (CONFIG_DIR / font.name) try: return ImageFont.truetype(str(font) if font.exists() else font.name, size) - except Exception as e: # download if missing - url = "https://ultralytics.com/assets/" + font.name + except OSError: # download if missing + url = f"https://ultralytics.com/assets/{font.name}" print(f'Downloading {url} to {font}...') torch.hub.download_url_to_file(url, str(font), progress=False) return ImageFont.truetype(str(font), size) @@ -308,7 +308,7 @@ def plot_labels(labels, names=(), save_dir=Path('')): # matplotlib labels matplotlib.use('svg') # faster ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() - y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + _ = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195 ax[0].set_ylabel('instances') if 0 < len(names) < 30: diff --git a/utils/torch_utils.py b/utils/torch_utils.py index 352ecf572c9f..2a43f6a21b8c 100644 --- a/utils/torch_utils.py +++ b/utils/torch_utils.py @@ -51,7 +51,7 @@ def git_describe(path=Path(__file__).parent): # path must be a directory s = f'git -C {path} describe --tags --long --always' try: return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] - except subprocess.CalledProcessError as e: + except subprocess.CalledProcessError: return '' # not a git repository @@ -114,7 +114,7 @@ def profile(input, ops, n=10, device=None): tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward try: flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs - except: + except ImportError: flops = 0 try: From ca45db2811a911c1d1f03514f7ab68b80ec7e294 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:17:20 +0800 Subject: [PATCH 02/18] Remove used codes --- train.py | 1 - 1 file changed, 1 deletion(-) diff --git a/train.py b/train.py index 460c6cd77a0d..aca89e35b4f6 100644 --- a/train.py +++ b/train.py @@ -499,7 +499,6 @@ def main(opt, callbacks=Callbacks()): # DDP mode device = select_device(opt.device, batch_size=opt.batch_size) if LOCAL_RANK != -1: - from datetime import timedelta assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command' assert opt.batch_size % WORLD_SIZE == 0, '--batch-size must be multiple of CUDA device count' assert not opt.image_weights, '--image-weights argument is not compatible with DDP training' From 8abd12959ae12e30ee9cb5624202725680621c9f Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:25:46 +0800 Subject: [PATCH 03/18] Add FileNotFoundError in LoadImagesAndLabels --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index 553bf185d810..a3ac0ff8df02 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except AssertionError: + except (FileNotFoundError, AssertionError): cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache From e6ddf997e501de752a283447c0248cf350a7709f Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:32:34 +0800 Subject: [PATCH 04/18] Remove AssertionError --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index a3ac0ff8df02..09961ddd73d3 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except (FileNotFoundError, AssertionError): + except FileNotFoundError: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache From 671d2d6689fd9fa4a31f326173e52999ab9ec3d9 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:35:47 +0800 Subject: [PATCH 05/18] Ignore LoadImagesAndLabels --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index 09961ddd73d3..665c47811e32 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except FileNotFoundError: + except: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache From 2950d336819a0ca54a48fe434265585772fa934d Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 02:49:04 +0800 Subject: [PATCH 06/18] Ignore downloads.py --- utils/downloads.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/utils/downloads.py b/utils/downloads.py index 3313f319416b..eafa3b7ac309 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -59,13 +59,12 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] tag = response['tag_name'] # i.e. 'v1.0' - except requests.exceptions.RequestException as e: # fallback plan - print(str(e)) # Print the general exception + except: # fallback plan assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] try: tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] - except subprocess.CalledProcessError: + except: tag = 'v5.0' # current release if name in assets: From 3c7db3a019a6d1ca0433db07cd8d7cf9534d787e Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:01:34 +0800 Subject: [PATCH 07/18] Ignore torch_utils.py --- utils/torch_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/torch_utils.py b/utils/torch_utils.py index 2a43f6a21b8c..5d425f9d369e 100644 --- a/utils/torch_utils.py +++ b/utils/torch_utils.py @@ -114,7 +114,7 @@ def profile(input, ops, n=10, device=None): tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward try: flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs - except ImportError: + except: flops = 0 try: From ace2fc0986540494fa02c9cb066cb9f96549a2f9 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:07:09 +0800 Subject: [PATCH 08/18] Ignore train.py --- train.py | 1 + 1 file changed, 1 insertion(+) diff --git a/train.py b/train.py index aca89e35b4f6..460c6cd77a0d 100644 --- a/train.py +++ b/train.py @@ -499,6 +499,7 @@ def main(opt, callbacks=Callbacks()): # DDP mode device = select_device(opt.device, batch_size=opt.batch_size) if LOCAL_RANK != -1: + from datetime import timedelta assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command' assert opt.batch_size % WORLD_SIZE == 0, '--batch-size must be multiple of CUDA device count' assert not opt.image_weights, '--image-weights argument is not compatible with DDP training' From 92116c722c45e67d55c53b4e5d0bb817122c75b8 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:11:13 +0800 Subject: [PATCH 09/18] Ignore datasets.py --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index 665c47811e32..a54e29fd2908 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -60,7 +60,7 @@ def exif_size(img): s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) - except KeyError: + except: pass return s From 2fd2554813c38497048ffb5df0ccf2e7fffcae47 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:16:26 +0800 Subject: [PATCH 10/18] Enable utils/download.py --- utils/downloads.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/utils/downloads.py b/utils/downloads.py index eafa3b7ac309..5baab8946e47 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -59,12 +59,13 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] tag = response['tag_name'] # i.e. 'v1.0' - except: # fallback plan + except requests.exceptions.RequestException as e: # fallback plan + print(str(e)) # print the general exception assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] try: tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] - except: + except subprocess.CalledProcessError: tag = 'v5.0' # current release if name in assets: From 190547a728e7e5d32cc5368c3e937b2efb3670a9 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:19:30 +0800 Subject: [PATCH 11/18] Fixing exception in thop --- utils/torch_utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/utils/torch_utils.py b/utils/torch_utils.py index 5d425f9d369e..0948620ddeb8 100644 --- a/utils/torch_utils.py +++ b/utils/torch_utils.py @@ -112,10 +112,10 @@ def profile(input, ops, n=10, device=None): m = m.to(device) if hasattr(m, 'to') else m # device m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward - try: - flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs - except: + if thop is None: flops = 0 + else: + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs try: for _ in range(n): From 6a51eb30c993413d0b5d76b5d7c632a7c01e790c Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:20:52 +0800 Subject: [PATCH 12/18] Remove unused code --- train.py | 1 - 1 file changed, 1 deletion(-) diff --git a/train.py b/train.py index 460c6cd77a0d..aca89e35b4f6 100644 --- a/train.py +++ b/train.py @@ -499,7 +499,6 @@ def main(opt, callbacks=Callbacks()): # DDP mode device = select_device(opt.device, batch_size=opt.batch_size) if LOCAL_RANK != -1: - from datetime import timedelta assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command' assert opt.batch_size % WORLD_SIZE == 0, '--batch-size must be multiple of CUDA device count' assert not opt.image_weights, '--image-weights argument is not compatible with DDP training' From 02008efb615ab03e063a54d1033ef3ad4fb2ef28 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 03:27:17 +0800 Subject: [PATCH 13/18] Fixing exception in LoadImagesAndLabels --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index a54e29fd2908..8fa5fc2834a9 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except: + except FileNotFoundError: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache From 12de8fc78a840f647970c420c04009a901a2d399 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 15:40:45 +0800 Subject: [PATCH 14/18] Fixing exception in exif_size --- utils/datasets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/datasets.py b/utils/datasets.py index 8fa5fc2834a9..cd8503063c8c 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -60,7 +60,7 @@ def exif_size(img): s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) - except: + except AttributeError: pass return s From 0180e209f6136ad0ba4e10526a3d16d88aaa2536 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 15:55:37 +0800 Subject: [PATCH 15/18] Fixing exception in parse_model --- models/tf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/tf.py b/models/tf.py index bc6134291aca..5c81147f689a 100644 --- a/models/tf.py +++ b/models/tf.py @@ -268,7 +268,7 @@ def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3) for j, a in enumerate(args): try: args[j] = eval(a) if isinstance(a, str) else a # eval strings - except: + except NameError: pass n = max(round(n * gd), 1) if n > 1 else n # depth gain From bdb3e501d5dd3d38927693c77a81320d93bf7406 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sat, 2 Oct 2021 16:03:52 +0800 Subject: [PATCH 16/18] Ignore exceptions in requests --- utils/downloads.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/utils/downloads.py b/utils/downloads.py index 5baab8946e47..e9dea979ed10 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -59,8 +59,7 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] tag = response['tag_name'] # i.e. 'v1.0' - except requests.exceptions.RequestException as e: # fallback plan - print(str(e)) # print the general exception + except: # fallback plan assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] try: From 10e6d1d28528dde47cbdc6877b717b6d8159b691 Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sun, 3 Oct 2021 11:17:53 +0800 Subject: [PATCH 17/18] Revert the exception as suggested --- utils/datasets.py | 4 ++-- utils/metrics.py | 4 ++-- utils/plots.py | 6 +++--- utils/torch_utils.py | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/utils/datasets.py b/utils/datasets.py index cd8503063c8c..a54e29fd2908 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -60,7 +60,7 @@ def exif_size(img): s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) - except AttributeError: + except: pass return s @@ -409,7 +409,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash - except FileNotFoundError: + except: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache diff --git a/utils/metrics.py b/utils/metrics.py index 0f8b69c12bd8..4f1b5e2d2c2d 100644 --- a/utils/metrics.py +++ b/utils/metrics.py @@ -216,8 +216,8 @@ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps= ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared - rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 - + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared if DIoU: return iou - rho2 / c2 # DIoU elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 diff --git a/utils/plots.py b/utils/plots.py index 3172f380f063..2f98d5b7e630 100644 --- a/utils/plots.py +++ b/utils/plots.py @@ -54,8 +54,8 @@ def check_font(font='Arial.ttf', size=10): font = font if font.exists() else (CONFIG_DIR / font.name) try: return ImageFont.truetype(str(font) if font.exists() else font.name, size) - except OSError: # download if missing - url = f"https://ultralytics.com/assets/{font.name}" + except Exception as e: # download if missing + url = "https://ultralytics.com/assets/" + font.name print(f'Downloading {url} to {font}...') torch.hub.download_url_to_file(url, str(font), progress=False) return ImageFont.truetype(str(font), size) @@ -308,7 +308,7 @@ def plot_labels(labels, names=(), save_dir=Path('')): # matplotlib labels matplotlib.use('svg') # faster ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() - _ = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195 ax[0].set_ylabel('instances') if 0 < len(names) < 30: diff --git a/utils/torch_utils.py b/utils/torch_utils.py index 0948620ddeb8..352ecf572c9f 100644 --- a/utils/torch_utils.py +++ b/utils/torch_utils.py @@ -51,7 +51,7 @@ def git_describe(path=Path(__file__).parent): # path must be a directory s = f'git -C {path} describe --tags --long --always' try: return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] - except subprocess.CalledProcessError: + except subprocess.CalledProcessError as e: return '' # not a git repository @@ -112,10 +112,10 @@ def profile(input, ops, n=10, device=None): m = m.to(device) if hasattr(m, 'to') else m # device m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward - if thop is None: - flops = 0 - else: + try: flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs + except: + flops = 0 try: for _ in range(n): From 675234726b189e167fd8b78c5e5f862ffc76acce Mon Sep 17 00:00:00 2001 From: zhiqiang Date: Sun, 3 Oct 2021 11:20:12 +0800 Subject: [PATCH 18/18] Revert the exception as suggested --- utils/downloads.py | 2 +- utils/general.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/utils/downloads.py b/utils/downloads.py index e9dea979ed10..eafa3b7ac309 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -64,7 +64,7 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] try: tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] - except subprocess.CalledProcessError: + except: tag = 'v5.0' # current release if name in assets: diff --git a/utils/general.py b/utils/general.py index 628692bad34a..c2fcf5e9c7f9 100755 --- a/utils/general.py +++ b/utils/general.py @@ -742,11 +742,11 @@ def print_mutation(results, hyp, save_dir, bucket): data = pd.read_csv(evolve_csv) data = data.rename(columns=lambda x: x.strip()) # strip keys i = np.argmax(fitness(data.values[:, :7])) # - f.write('# YOLOv5 Hyperparameter Evolution Results\n' - + f'# Best generation: {i}\n' - + f'# Last generation: {len(data)}\n' - + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' - + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') + f.write('# YOLOv5 Hyperparameter Evolution Results\n' + + f'# Best generation: {i}\n' + + f'# Last generation: {len(data)}\n' + + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' + + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') yaml.safe_dump(hyp, f, sort_keys=False) if bucket: