Skip to content

Commit 5ce4318

Browse files
author
KaiyangZhou
committed
linting code
1 parent 2a9f44a commit 5ce4318

33 files changed

+97
-65
lines changed

.flake8

+16-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,18 @@
11
[flake8]
2-
ignore = E261, E501, W293
2+
ignore =
3+
# At least two spaces before inline comment
4+
E261,
5+
# Line lengths are recommended to be no greater than 79 characters
6+
E501,
7+
# Missing whitespace around arithmetic operator
8+
E226,
9+
# Blank line contains whitespace
10+
W293,
11+
# Do not use bare 'except'
12+
E722,
13+
# Line break after binary operator
14+
W504,
15+
# isort found an import in the wrong position
16+
I001
317
max-line-length = 79
4-
exclude = __init__.py, build
18+
exclude = __init__.py, build, torchreid/metrics/rank_cylib/

docs/conf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
# You can specify multiple suffix as a list of string:
5858
#
5959
source_suffix = ['.rst', '.md']
60-
#source_suffix = '.rst'
60+
# source_suffix = '.rst'
6161
source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'}
6262

6363
# The master toctree document.

linter.sh

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
echo "Running isort"
12
isort -y -sp .
3+
echo "Done"
24

3-
yapf -i -r -vv . -e build
5+
echo "Running yapf"
6+
yapf -i -r -vv -e build .
7+
echo "Done"
8+
9+
echo "Running flake8"
10+
flake8 .
11+
echo "Done"

projects/DML/dml.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
from __future__ import division, print_function, absolute_import
2-
import time
3-
import datetime
42
import torch
53
from torch.nn import functional as F
64

7-
from torchreid import metrics
85
from torchreid.utils import open_all_layers, open_specified_layers
96
from torchreid.engine import Engine
107
from torchreid.losses import TripletLoss, CrossEntropyLoss

projects/DML/main.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import os
21
import sys
32
import copy
43
import time
@@ -15,8 +14,8 @@
1514

1615
from dml import ImageDMLEngine
1716
from default_config import (
18-
imagedata_kwargs, optimizer_kwargs, videodata_kwargs, engine_run_kwargs,
19-
get_default_config, lr_scheduler_kwargs
17+
imagedata_kwargs, optimizer_kwargs, engine_run_kwargs, get_default_config,
18+
lr_scheduler_kwargs
2019
)
2120

2221

projects/OSNet_AIN/osnet_search.py

+18
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,24 @@
1010
##########
1111
# Basic layers
1212
##########
13+
class IBN(nn.Module):
14+
"""Instance + Batch Normalization."""
15+
16+
def __init__(self, num_channels):
17+
super(IBN, self).__init__()
18+
half1 = int(num_channels / 2)
19+
self.half = half1
20+
half2 = num_channels - half1
21+
self.IN = nn.InstanceNorm2d(half1, affine=NORM_AFFINE)
22+
self.BN = nn.BatchNorm2d(half2, affine=NORM_AFFINE)
23+
24+
def forward(self, x):
25+
split = torch.split(x, self.half, 1)
26+
out1 = self.IN(split[0].contiguous())
27+
out2 = self.BN(split[1].contiguous())
28+
return torch.cat((out1, out2), 1)
29+
30+
1331
class ConvLayer(nn.Module):
1432
"""Convolution layer (conv + bn + relu)."""
1533

projects/OSNet_AIN/softmax_nas.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
from __future__ import division, print_function, absolute_import
2-
import time
3-
import datetime
42

53
from torchreid import metrics
6-
from torchreid.utils import (
7-
AverageMeter, open_all_layers, open_specified_layers
8-
)
94
from torchreid.engine import Engine
105
from torchreid.losses import CrossEntropyLoss
116

@@ -58,7 +53,7 @@ def forward_backward(self, data):
5853
lmda = self.init_lmda
5954
else:
6055
lmda = self.init_lmda * self.lmda_decay_rate**(
61-
epoch // self.lmda_decay_step
56+
self.epoch // self.lmda_decay_step
6257
)
6358
if lmda < self.min_lmda:
6459
lmda = self.min_lmda

scripts/main.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import os
21
import sys
32
import time
43
import os.path as osp

setup.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ def get_requirements(filename='requirements.txt'):
4545
setup(
4646
name='torchreid',
4747
version=find_version(),
48-
description=
49-
'A library for deep learning person re-identification in PyTorch',
48+
description='A library for deep learning person re-ID in PyTorch',
5049
author='Kaiyang Zhou',
5150
license='MIT',
5251
long_description=readme(),

torchreid/data/datamanager.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def num_train_cams(self):
7070
"""Returns the number of training cameras."""
7171
return self._num_train_cams
7272

73-
def return_query_and_gallery_by_name(self, name):
73+
def fetch_qg(self, name):
7474
"""Returns query and gallery of a test dataset, each containing
7575
tuples of (img_path(s), pid, camid).
7676

torchreid/data/datasets/dataset.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -238,9 +238,9 @@ def __repr__(self):
238238
' gallery | {:5d} | {:7d} | {:9d}\n' \
239239
' ----------------------------------------\n' \
240240
' items: images/tracklets for image/video dataset\n'.format(
241-
num_train_pids, len(self.train), num_train_cams,
242-
num_query_pids, len(self.query), num_query_cams,
243-
num_gallery_pids, len(self.gallery), num_gallery_cams
241+
num_train_pids, len(self.train), num_train_cams,
242+
num_query_pids, len(self.query), num_query_cams,
243+
num_gallery_pids, len(self.gallery), num_gallery_cams
244244
)
245245

246246
return msg

torchreid/data/datasets/image/cuhk03.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,8 @@ def _extract_img(image_type):
151151
img_paths = _process_images(
152152
camp[pid, :], campid, pid, imgs_dir
153153
)
154-
assert len(img_paths
155-
) > 0, 'campid{}-pid{} has no images'.format(
156-
campid, pid
157-
)
154+
assert len(img_paths) > 0, \
155+
'campid{}-pid{} has no images'.format(campid, pid)
158156
meta_data.append((campid + 1, pid + 1, img_paths))
159157
print(
160158
'- done camera pair {} with {} identities'.format(

torchreid/data/datasets/image/dukemtmcreid.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ def process_dir(self, dir_path, relabel=False):
6161
pid, camid = map(int, pattern.search(img_path).groups())
6262
assert 1 <= camid <= 8
6363
camid -= 1 # index starts from 0
64-
if relabel: pid = pid2label[pid]
64+
if relabel:
65+
pid = pid2label[pid]
6566
data.append((img_path, pid, camid))
6667

6768
return data

torchreid/data/datasets/image/ilids.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class iLIDS(ImageDataset):
1818
1919
Dataset statistics:
2020
- identities: 119.
21-
- images: 476.
21+
- images: 476.
2222
- cameras: 8 (not explicitly provided).
2323
"""
2424
dataset_dir = 'ilids'

torchreid/data/datasets/image/msmt17.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from ..dataset import ImageDataset
55

6-
##### Log #####
6+
# Log
77
# 22.01.2019
88
# - add v2
99
# - v1 and v2 differ in dir names

torchreid/data/datasets/image/viper.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,8 @@ def prepare_split(self):
8383
np.random.shuffle(order)
8484
train_idxs = order[:num_train_pids]
8585
test_idxs = order[num_train_pids:]
86-
assert not bool(
87-
set(train_idxs)
88-
& set(test_idxs)
89-
), 'Error: train and test overlap'
86+
assert not bool(set(train_idxs) & set(test_idxs)), \
87+
'Error: train and test overlap'
9088

9189
train = []
9290
for pid, idx in enumerate(train_idxs):

torchreid/data/datasets/video/mars.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ def process_data(
9898
if pid == -1:
9999
continue # junk images are just ignored
100100
assert 1 <= camid <= 6
101-
if relabel: pid = pid2label[pid]
101+
if relabel:
102+
pid = pid2label[pid]
102103
camid -= 1 # index starts from 0
103104
img_names = names[start_index - 1:end_index]
104105

torchreid/data/transforms.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
from collections import deque
55
import torch
66
from PIL import Image
7-
from torchvision.transforms import *
7+
from torchvision.transforms import (
8+
Resize, Compose, ToTensor, Normalize, ColorJitter, RandomHorizontalFlip
9+
)
810

911

1012
class Random2DTranslation(object):
@@ -279,8 +281,13 @@ def build_transforms(
279281
transform_tr += [RandomHorizontalFlip()]
280282

281283
if 'random_crop' in transforms:
282-
print('+ random crop (enlarge to {}x{} and ' \
283-
'crop {}x{})'.format(int(round(height*1.125)), int(round(width*1.125)), height, width))
284+
print(
285+
'+ random crop (enlarge to {}x{} and '
286+
'crop {}x{})'.format(
287+
int(round(height * 1.125)), int(round(width * 1.125)), height,
288+
width
289+
)
290+
)
284291
transform_tr += [Random2DTranslation(height, width)]
285292

286293
if 'random_patch' in transforms:

torchreid/engine/engine.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -428,8 +428,7 @@ def _feature_extraction(data_loader):
428428
if visrank:
429429
visualize_ranked_results(
430430
distmat,
431-
self.datamanager.
432-
return_query_and_gallery_by_name(dataset_name),
431+
self.datamanager.fetch_qg(dataset_name),
433432
self.datamanager.data_type,
434433
width=self.datamanager.width,
435434
height=self.datamanager.height,

torchreid/engine/image/softmax.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
from __future__ import division, print_function, absolute_import
2-
import time
3-
import datetime
42

53
from torchreid import metrics
64
from torchreid.losses import CrossEntropyLoss

torchreid/engine/image/triplet.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
from __future__ import division, print_function, absolute_import
2-
import time
3-
import datetime
42

53
from torchreid import metrics
64
from torchreid.losses import TripletLoss, CrossEntropyLoss

torchreid/engine/video/triplet.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ class VideoTripletEngine(ImageTripletEngine, VideoSoftmaxEngine):
2222
Default is "avg" (average). Choices are ["avg", "max"].
2323
2424
Examples::
25-
25+
2626
import torch
2727
import torchreid
2828
# Each batch contains batch_size*seq_len images
29-
# Each identity is sampled with num_instances tracklets
29+
# Each identity is sampled with num_instances tracklets
3030
datamanager = torchreid.data.VideoDataManager(
3131
root='path/to/reid-data',
3232
sources='mars',

torchreid/metrics/distance.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,9 @@ def euclidean_squared_distance(input1, input2):
5757
torch.Tensor: distance matrix.
5858
"""
5959
m, n = input1.size(0), input2.size(0)
60-
distmat = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n) + \
61-
torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
60+
mat1 = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n)
61+
mat2 = torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
62+
distmat = mat1 + mat2
6263
distmat.addmm_(1, -2, input1, input2.t())
6364
return distmat
6465

torchreid/models/hacnn.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,8 @@ def transform_theta(self, theta_i, region_idx):
300300
theta = torch.zeros(theta_i.size(0), 2, 3)
301301
theta[:, :, :2] = scale_factors
302302
theta[:, :, -1] = theta_i
303-
if self.use_gpu: theta = theta.cuda()
303+
if self.use_gpu:
304+
theta = theta.cuda()
304305
return theta
305306

306307
def forward(self, x):

torchreid/models/inceptionresnetv2.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,9 @@ def forward(self, x):
249249
return out
250250

251251

252-
##################### Model Definition #########################
253-
254-
252+
# ----------------
253+
# Model Definition
254+
# ----------------
255255
class InceptionResNetV2(nn.Module):
256256
"""Inception-ResNet-V2.
257257

torchreid/models/mlfn.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ def init_pretrained_weights(model, model_url):
260260
def mlfn(num_classes, loss='softmax', pretrained=True, **kwargs):
261261
model = MLFN(num_classes, loss, **kwargs)
262262
if pretrained:
263-
#init_pretrained_weights(model, model_urls['imagenet'])
263+
# init_pretrained_weights(model, model_urls['imagenet'])
264264
import warnings
265265
warnings.warn(
266266
'The imagenet pretrained weights need to be manually downloaded from {}'

torchreid/models/mobilenetv2.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def mobilenetv2_x1_0(num_classes, loss, pretrained=True, **kwargs):
246246
**kwargs
247247
)
248248
if pretrained:
249-
#init_pretrained_weights(model, model_urls['mobilenetv2_x1_0'])
249+
# init_pretrained_weights(model, model_urls['mobilenetv2_x1_0'])
250250
import warnings
251251
warnings.warn(
252252
'The imagenet pretrained weights need to be manually downloaded from {}'
@@ -265,7 +265,7 @@ def mobilenetv2_x1_4(num_classes, loss, pretrained=True, **kwargs):
265265
**kwargs
266266
)
267267
if pretrained:
268-
#init_pretrained_weights(model, model_urls['mobilenetv2_x1_4'])
268+
# init_pretrained_weights(model, model_urls['mobilenetv2_x1_4'])
269269
import warnings
270270
warnings.warn(
271271
'The imagenet pretrained weights need to be manually downloaded from {}'

torchreid/models/nasnet.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
pretrained_settings = {
2727
'nasnetamobile': {
2828
'imagenet': {
29-
#'url': 'https://github.com/veronikayurchuk/pretrained-models.pytorch/releases/download/v1.0/nasnetmobile-7e03cead.pth.tar',
29+
# 'url': 'https://github.com/veronikayurchuk/pretrained-models.pytorch/releases/download/v1.0/nasnetmobile-7e03cead.pth.tar',
3030
'url':
3131
'http://data.lip6.fr/cadene/pretrainedmodels/nasnetamobile-7e03cead.pth',
3232
'input_space': 'RGB',

torchreid/models/shufflenet.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ def __init__(
4545
assert stride in [1, 2], 'Warning: stride must be either 1 or 2'
4646
self.stride = stride
4747
mid_channels = out_channels // 4
48-
if stride == 2: out_channels -= in_channels
48+
if stride == 2:
49+
out_channels -= in_channels
4950
# group conv is not applied to first conv1x1 at stage 2
5051
num_groups_conv1x1 = num_groups if group_conv1x1 else 1
5152
self.conv1 = nn.Conv2d(
@@ -71,7 +72,8 @@ def __init__(
7172
mid_channels, out_channels, 1, groups=num_groups, bias=False
7273
)
7374
self.bn3 = nn.BatchNorm2d(out_channels)
74-
if stride == 2: self.shortcut = nn.AvgPool2d(3, stride=2, padding=1)
75+
if stride == 2:
76+
self.shortcut = nn.AvgPool2d(3, stride=2, padding=1)
7577

7678
def forward(self, x):
7779
out = F.relu(self.bn1(self.conv1(x)))
@@ -187,7 +189,7 @@ def init_pretrained_weights(model, model_url):
187189
def shufflenet(num_classes, loss='softmax', pretrained=True, **kwargs):
188190
model = ShuffleNet(num_classes, loss, **kwargs)
189191
if pretrained:
190-
#init_pretrained_weights(model, model_urls['imagenet'])
192+
# init_pretrained_weights(model, model_urls['imagenet'])
191193
import warnings
192194
warnings.warn(
193195
'The imagenet pretrained weights need to be manually downloaded from {}'

torchreid/models/squeezenet.py

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import torch
66
import torch.nn as nn
77
import torch.utils.model_zoo as model_zoo
8-
from torch.utils import model_zoo as model_zoo
98

109
__all__ = ['squeezenet1_0', 'squeezenet1_1', 'squeezenet1_0_fc512']
1110

0 commit comments

Comments
 (0)