Skip to content

Commit cba4303

Browse files
Bordaglenn-jocher
andauthored
Fix 6 Flake8 issues (#6541)
* F541 * F821 * F841 * E741 * E302 * E722 * Apply suggestions from code review * Update general.py * Update datasets.py * Update export.py * Update plots.py * Update plots.py Co-authored-by: Glenn Jocher <[email protected]>
1 parent e1a6a0b commit cba4303

10 files changed

Lines changed: 55 additions & 56 deletions

File tree

export.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def export_saved_model(model, im, file, dynamic,
244244

245245
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
246246
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow
247-
y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
247+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
248248
inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
249249
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
250250
keras_model = keras.Model(inputs=inputs, outputs=outputs)
@@ -407,16 +407,17 @@ def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
407407
tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs')) # TensorFlow exports
408408
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)
409409

410-
# Checks
411-
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
412-
opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
413-
414410
# Load PyTorch model
415411
device = select_device(device)
416412
assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
417413
model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
418414
nc, names = model.nc, model.names # number of classes, class names
419415

416+
# Checks
417+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
418+
opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
419+
assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
420+
420421
# Input
421422
gs = int(max(model.stride)) # grid size (max stride)
422423
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
@@ -438,7 +439,8 @@ def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
438439

439440
for _ in range(2):
440441
y = model(im) # dry runs
441-
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")
442+
shape = tuple(y[0].shape) # model output shape
443+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
442444

443445
# Exports
444446
f = [''] * 10 # exported filenames

models/tf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,13 +427,13 @@ def run(weights=ROOT / 'yolov5s.pt', # weights path
427427
# PyTorch model
428428
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
429429
model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)
430-
y = model(im) # inference
430+
_ = model(im) # inference
431431
model.info()
432432

433433
# TensorFlow model
434434
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
435435
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
436-
y = tf_model.predict(im) # inference
436+
_ = tf_model.predict(im) # inference
437437

438438
# Keras model
439439
im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)

setup.cfg

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,13 @@ ignore =
3030
E731 # Do not assign a lambda expression, use a def
3131
F405 # name may be undefined, or defined from star imports: module
3232
E402 # module level import not at top of file
33-
F841 # local variable name is assigned to but never used
34-
E741 # do not use variables named ‘l’, ‘O’, or ‘I’
35-
F821 # undefined name name
36-
E722 # do not use bare except, specify exception instead
3733
F401 # module imported but unused
3834
W504 # line break after binary operator
3935
E127 # continuation line over-indented for visual indent
4036
W504 # line break after binary operator
4137
E231 # missing whitespace after ‘,’, ‘;’, or ‘:’
4238
E501 # line too long
4339
F403 # ‘from module import *’ used; unable to detect undefined names
44-
E302 # expected 2 blank lines, found 0
45-
F541 # f-string without any placeholders
4640

4741

4842
[isort]

utils/datasets.py

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def exif_size(img):
5959
s = (s[1], s[0])
6060
elif rotation == 8: # rotation 90
6161
s = (s[1], s[0])
62-
except:
62+
except Exception:
6363
pass
6464

6565
return s
@@ -420,7 +420,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r
420420
cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
421421
assert cache['version'] == self.cache_version # same version
422422
assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash
423-
except:
423+
except Exception:
424424
cache, exists = self.cache_labels(cache_path, prefix), False # cache
425425

426426
# Display cache
@@ -514,13 +514,13 @@ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
514514
with Pool(NUM_THREADS) as pool:
515515
pbar = tqdm(pool.imap(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),
516516
desc=desc, total=len(self.img_files))
517-
for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
517+
for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
518518
nm += nm_f
519519
nf += nf_f
520520
ne += ne_f
521521
nc += nc_f
522522
if im_file:
523-
x[im_file] = [l, shape, segments]
523+
x[im_file] = [lb, shape, segments]
524524
if msg:
525525
msgs.append(msg)
526526
pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt"
@@ -627,8 +627,8 @@ def __getitem__(self, index):
627627
@staticmethod
628628
def collate_fn(batch):
629629
img, label, path, shapes = zip(*batch) # transposed
630-
for i, l in enumerate(label):
631-
l[:, 0] = i # add target image index for build_targets()
630+
for i, lb in enumerate(label):
631+
lb[:, 0] = i # add target image index for build_targets()
632632
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
633633

634634
@staticmethod
@@ -645,15 +645,15 @@ def collate_fn4(batch):
645645
if random.random() < 0.5:
646646
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', align_corners=False)[
647647
0].type(img[i].type())
648-
l = label[i]
648+
lb = label[i]
649649
else:
650650
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
651-
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
651+
lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
652652
img4.append(im)
653-
label4.append(l)
653+
label4.append(lb)
654654

655-
for i, l in enumerate(label4):
656-
l[:, 0] = i # add target image index for build_targets()
655+
for i, lb in enumerate(label4):
656+
lb[:, 0] = i # add target image index for build_targets()
657657

658658
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
659659

@@ -743,6 +743,7 @@ def load_mosaic9(self, index):
743743
s = self.img_size
744744
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
745745
random.shuffle(indices)
746+
hp, wp = -1, -1 # height, width previous
746747
for i, index in enumerate(indices):
747748
# Load image
748749
img, _, (h, w) = load_image(self, index)
@@ -906,30 +907,30 @@ def verify_image_label(args):
906907
if os.path.isfile(lb_file):
907908
nf = 1 # label found
908909
with open(lb_file) as f:
909-
l = [x.split() for x in f.read().strip().splitlines() if len(x)]
910-
if any([len(x) > 8 for x in l]): # is segment
911-
classes = np.array([x[0] for x in l], dtype=np.float32)
912-
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
913-
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
914-
l = np.array(l, dtype=np.float32)
915-
nl = len(l)
910+
lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
911+
if any([len(x) > 8 for x in lb]): # is segment
912+
classes = np.array([x[0] for x in lb], dtype=np.float32)
913+
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
914+
lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
915+
lb = np.array(lb, dtype=np.float32)
916+
nl = len(lb)
916917
if nl:
917-
assert l.shape[1] == 5, f'labels require 5 columns, {l.shape[1]} columns detected'
918-
assert (l >= 0).all(), f'negative label values {l[l < 0]}'
919-
assert (l[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {l[:, 1:][l[:, 1:] > 1]}'
920-
_, i = np.unique(l, axis=0, return_index=True)
918+
assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
919+
assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
920+
assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
921+
_, i = np.unique(lb, axis=0, return_index=True)
921922
if len(i) < nl: # duplicate row check
922-
l = l[i] # remove duplicates
923+
lb = lb[i] # remove duplicates
923924
if segments:
924925
segments = segments[i]
925926
msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'
926927
else:
927928
ne = 1 # label empty
928-
l = np.zeros((0, 5), dtype=np.float32)
929+
lb = np.zeros((0, 5), dtype=np.float32)
929930
else:
930931
nm = 1 # label missing
931-
l = np.zeros((0, 5), dtype=np.float32)
932-
return im_file, l, shape, segments, nm, nf, ne, nc, msg
932+
lb = np.zeros((0, 5), dtype=np.float32)
933+
return im_file, lb, shape, segments, nm, nf, ne, nc, msg
933934
except Exception as e:
934935
nc = 1
935936
msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'

utils/downloads.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,12 @@ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads i
6262
response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
6363
assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
6464
tag = response['tag_name'] # i.e. 'v1.0'
65-
except: # fallback plan
65+
except Exception: # fallback plan
6666
assets = ['yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
6767
'yolov5n6.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
6868
try:
6969
tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
70-
except:
70+
except Exception:
7171
tag = 'v6.0' # current release
7272

7373
if name in assets:

utils/general.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), insta
295295
for r in requirements:
296296
try:
297297
pkg.require(r)
298-
except Exception as e: # DistributionNotFound or VersionConflict if requirements not met
298+
except Exception: # DistributionNotFound or VersionConflict if requirements not met
299299
s = f"{prefix} {r} not found and is required by YOLOv5"
300300
if install:
301301
LOGGER.info(f"{s}, attempting auto-update...")
@@ -699,16 +699,16 @@ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=Non
699699
output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
700700
for xi, x in enumerate(prediction): # image index, image inference
701701
# Apply constraints
702-
# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
702+
x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
703703
x = x[xc[xi]] # confidence
704704

705705
# Cat apriori labels if autolabelling
706706
if labels and len(labels[xi]):
707-
l = labels[xi]
708-
v = torch.zeros((len(l), nc + 5), device=x.device)
709-
v[:, :4] = l[:, 1:5] # box
707+
lb = labels[xi]
708+
v = torch.zeros((len(lb), nc + 5), device=x.device)
709+
v[:, :4] = lb[:, 1:5] # box
710710
v[:, 4] = 1.0 # conf
711-
v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
711+
v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls
712712
x = torch.cat((x, v), 0)
713713

714714
# If none remain process next image
@@ -783,7 +783,8 @@ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_op
783783

784784

785785
def print_mutation(results, hyp, save_dir, bucket):
786-
evolve_csv, results_csv, evolve_yaml = save_dir / 'evolve.csv', save_dir / 'results.csv', save_dir / 'hyp_evolve.yaml'
786+
evolve_csv = save_dir / 'evolve.csv'
787+
evolve_yaml = save_dir / 'hyp_evolve.yaml'
787788
keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
788789
'val/box_loss', 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps]
789790
keys = tuple(x.strip() for x in keys)

utils/loggers/wandb/wandb_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def download_model_artifact(self, opt):
288288
model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
289289
assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
290290
modeldir = model_artifact.download()
291-
epochs_trained = model_artifact.metadata.get('epochs_trained')
291+
# epochs_trained = model_artifact.metadata.get('epochs_trained')
292292
total_epochs = model_artifact.metadata.get('total_epochs')
293293
is_finished = total_epochs is None
294294
assert not is_finished, 'training is finished, can only resume incomplete runs.'

utils/metrics.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=
239239
return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
240240
return iou # IoU
241241

242+
242243
def box_iou(box1, box2):
243244
# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
244245
"""

utils/plots.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def check_pil_font(font=FONT, size=10):
5454
font = font if font.exists() else (CONFIG_DIR / font.name)
5555
try:
5656
return ImageFont.truetype(str(font) if font.exists() else font.name, size)
57-
except Exception as e: # download if missing
57+
except Exception: # download if missing
5858
check_font(font)
5959
try:
6060
return ImageFont.truetype(str(font), size)
@@ -340,7 +340,7 @@ def plot_labels(labels, names=(), save_dir=Path('')):
340340
matplotlib.use('svg') # faster
341341
ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
342342
y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
343-
# [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
343+
[y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
344344
ax[0].set_ylabel('instances')
345345
if 0 < len(names) < 30:
346346
ax[0].set_xticks(range(len(names)))

utils/torch_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def git_describe(path=Path(__file__).parent): # path must be a directory
4949
s = f'git -C {path} describe --tags --long --always'
5050
try:
5151
return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
52-
except subprocess.CalledProcessError as e:
52+
except subprocess.CalledProcessError:
5353
return '' # not a git repository
5454

5555

@@ -59,7 +59,7 @@ def device_count():
5959
try:
6060
cmd = 'nvidia-smi -L | wc -l'
6161
return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])
62-
except Exception as e:
62+
except Exception:
6363
return 0
6464

6565

@@ -124,7 +124,7 @@ def profile(input, ops, n=10, device=None):
124124
tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
125125
try:
126126
flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs
127-
except:
127+
except Exception:
128128
flops = 0
129129

130130
try:
@@ -135,7 +135,7 @@ def profile(input, ops, n=10, device=None):
135135
try:
136136
_ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
137137
t[2] = time_sync()
138-
except Exception as e: # no backward method
138+
except Exception: # no backward method
139139
# print(e) # for debug
140140
t[2] = float('nan')
141141
tf += (t[1] - t[0]) * 1000 / n # ms per op forward

0 commit comments

Comments
 (0)