Skip to content

Commit cea0152

Browse files
committed
fix logger
1 parent f1598fe commit cea0152

File tree

3 files changed

+7
-48
lines changed

3 files changed

+7
-48
lines changed

__init__.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ def train(modelWrapper, data, hyp, opt, device):
6262
cuda = device.type != 'cpu'
6363
init_seeds(2 + rank)
6464

65-
print('.......', opt.data)
6665
with open(opt.data) as f:
6766
data_dict = yaml.load(f, Loader=yaml.FullLoader)
6867
with torch_distributed_zero_first(rank):
@@ -159,14 +158,14 @@ def train(modelWrapper, data, hyp, opt, device):
159158
logger.info('Image sizes %g train, %g test\n'
160159
'Using %g dataloader workers\nLogging results to %s\n'
161160
'Starting training for %g epochs...' % (imgsz, imgsz_test, dataloader.num_workers, log_dir, epochs))
162-
161+
logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'targets', 'img_size'))
163162
for epoch in range(start_epoch, epochs):
163+
logger.info('Epoch: ' + str(epoch))
164164
model.train()
165165

166166
mloss = torch.zeros(4, device=device) # mean losses
167167
pbar = enumerate(dataloader)
168-
logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'targets', 'img_size'))
169-
pbar = tqdm(pbar, total=nb) # progress bar
168+
170169
optimizer.zero_grad()
171170
for i, (imgs, targets, paths, _) in pbar:
172171
ni = i + nb * epoch # number integrated batches (since train start)
@@ -206,7 +205,6 @@ def train(modelWrapper, data, hyp, opt, device):
206205
mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
207206
s = ('%10s' * 2 + '%10.4g' * 6) % (
208207
'%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
209-
pbar.set_description(s)
210208

211209
# Plot
212210
if ni < 3:
@@ -215,7 +213,7 @@ def train(modelWrapper, data, hyp, opt, device):
215213

216214

217215
# end batch ------------------------------------------------------------------------------------------------
218-
216+
logger.info(s)
219217
# Scheduler
220218
lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard
221219
scheduler.step()
@@ -241,7 +239,7 @@ def train(modelWrapper, data, hyp, opt, device):
241239
fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected]]
242240
if fi > best_fitness:
243241
best_fitness = fi
244-
print('----best map', fi)
242+
logger.info('Current Best Map: ' + str(fi))
245243

246244
# Save model
247245
with open(results_file, 'r') as f: # create checkpoint

evaluate.py

+2-40
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def test(data,
8686
p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
8787
loss = torch.zeros(3, device=device)
8888
jdict, stats, ap, ap_class = [], [], [], []
89-
for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
89+
for batch_i, (img, targets, paths, shapes) in enumerate(dataloader):
9090
img = img.to(device, non_blocking=True)
9191
img = img.half() if half else img.float() # uint8 to fp16/32
9292
img /= 255.0 # 0 - 255 to 0.0 - 1.0
@@ -135,20 +135,6 @@ def test(data,
135135
# Clip boxes to image bounds
136136
clip_coords(pred, (height, width))
137137

138-
# Append to pycocotools JSON dictionary
139-
if save_json:
140-
# [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
141-
image_id = Path(paths[si]).stem
142-
box = pred[:, :4].clone() # xyxy
143-
scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
144-
box = xyxy2xywh(box) # xywh
145-
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
146-
for p, b in zip(pred.tolist(), box.tolist()):
147-
jdict.append({'image_id': int(image_id) if image_id.isnumeric() else image_id,
148-
'category_id': coco91class[int(p[5])],
149-
'bbox': [round(x, 3) for x in b],
150-
'score': round(p[4], 5)})
151-
152138
# Assign all predictions as incorrect
153139
correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
154140
if nl:
@@ -211,31 +197,7 @@ def test(data,
211197
# Print speeds
212198
t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
213199
if not training:
214-
print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
215-
216-
# Save JSON
217-
if save_json and len(jdict):
218-
f = 'detections_val2017_%s_results.json' % \
219-
(weights.split(os.sep)[-1].replace('.pt', '') if isinstance(weights, str) else '') # filename
220-
print('\nCOCO mAP with pycocotools... saving %s...' % f)
221-
with open(f, 'w') as file:
222-
json.dump(jdict, file)
223-
224-
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
225-
from pycocotools.coco import COCO
226-
from pycocotools.cocoeval import COCOeval
227-
228-
imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files]
229-
cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
230-
cocoDt = cocoGt.loadRes(f) # initialize COCO pred api
231-
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
232-
cocoEval.params.imgIds = imgIds # image IDs to evaluate
233-
cocoEval.evaluate()
234-
cocoEval.accumulate()
235-
cocoEval.summarize()
236-
map, map50 = cocoEval.stats[:2] # update results ([email protected]:0.95, [email protected])
237-
except Exception as e:
238-
print('ERROR: pycocotools unable to run: %s' % e)
200+
print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
239201

240202
# Return results
241203
model.float() # for training

tools/datasets.py

-1
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,6 @@ def preprocess(data):
10011001
names, trainRootDir = preprocess_help(data, 'train')
10021002
valnames, valRootDir = preprocess_help(data, 'val')
10031003
testnames, testRootDir = preprocess_help(data, 'test')
1004-
print('------names', names, valnames, testnames)
10051004
test = val = train = os.path.join(trainRootDir, 'images', 'train')
10061005
if (len(valnames) > 0):
10071006
val = os.path.join(valRootDir, 'images', 'val')

0 commit comments

Comments
 (0)