mAP recorded during training
This commit is contained in:
parent
9dbc3ec1c4
commit
45c5567723
68
test.py
68
test.py
|
@ -11,7 +11,7 @@ parser.add_argument('-data_config_path', type=str, default='cfg/coco.data', help
|
||||||
parser.add_argument('-weights_path', type=str, default='weights/yolov3.pt', help='path to weights file')
|
parser.add_argument('-weights_path', type=str, default='weights/yolov3.pt', help='path to weights file')
|
||||||
parser.add_argument('-class_path', type=str, default='data/coco.names', help='path to class label file')
|
parser.add_argument('-class_path', type=str, default='data/coco.names', help='path to class label file')
|
||||||
parser.add_argument('-iou_thres', type=float, default=0.5, help='iou threshold required to qualify as detected')
|
parser.add_argument('-iou_thres', type=float, default=0.5, help='iou threshold required to qualify as detected')
|
||||||
parser.add_argument('-conf_thres', type=float, default=0.5, help='object confidence threshold')
|
parser.add_argument('-conf_thres', type=float, default=0.3, help='object confidence threshold')
|
||||||
parser.add_argument('-nms_thres', type=float, default=0.45, help='iou threshold for non-maximum suppression')
|
parser.add_argument('-nms_thres', type=float, default=0.45, help='iou threshold for non-maximum suppression')
|
||||||
parser.add_argument('-n_cpu', type=int, default=0, help='number of cpu threads to use during batch generation')
|
parser.add_argument('-n_cpu', type=int, default=0, help='number of cpu threads to use during batch generation')
|
||||||
parser.add_argument('-img_size', type=int, default=416, help='size of each image dimension')
|
parser.add_argument('-img_size', type=int, default=416, help='size of each image dimension')
|
||||||
|
@ -21,40 +21,40 @@ print(opt)
|
||||||
cuda = torch.cuda.is_available()
|
cuda = torch.cuda.is_available()
|
||||||
device = torch.device('cuda:0' if cuda else 'cpu')
|
device = torch.device('cuda:0' if cuda else 'cpu')
|
||||||
|
|
||||||
# Configure run
|
|
||||||
data_config = parse_data_config(opt.data_config_path)
|
def main(opt):
|
||||||
num_classes = int(data_config['classes'])
|
# Configure run
|
||||||
if platform == 'darwin': # MacOS (local)
|
data_config = parse_data_config(opt.data_config_path)
|
||||||
|
nC = int(data_config['classes']) # number of classes (80 for COCO)
|
||||||
|
if platform == 'darwin': # MacOS (local)
|
||||||
test_path = data_config['valid']
|
test_path = data_config['valid']
|
||||||
else: # linux (cloud, i.e. gcp)
|
else: # linux (cloud, i.e. gcp)
|
||||||
test_path = '../coco/5k.part'
|
test_path = '../coco/5k.part'
|
||||||
|
|
||||||
# Initiate model
|
# Initiate model
|
||||||
model = Darknet(opt.cfg, opt.img_size)
|
model = Darknet(opt.cfg, opt.img_size)
|
||||||
|
|
||||||
# Load weights
|
# Load weights
|
||||||
if opt.weights_path.endswith('.weights'): # darknet format
|
if opt.weights_path.endswith('.weights'): # darknet format
|
||||||
load_weights(model, opt.weights_path)
|
load_weights(model, opt.weights_path)
|
||||||
elif opt.weights_path.endswith('.pt'): # pytorch format
|
elif opt.weights_path.endswith('.pt'): # pytorch format
|
||||||
checkpoint = torch.load(opt.weights_path, map_location='cpu')
|
checkpoint = torch.load(opt.weights_path, map_location='cpu')
|
||||||
model.load_state_dict(checkpoint['model'])
|
model.load_state_dict(checkpoint['model'])
|
||||||
del checkpoint
|
del checkpoint
|
||||||
|
|
||||||
model.to(device).eval()
|
model.to(device).eval()
|
||||||
|
|
||||||
# Get dataloader
|
# Get dataloader
|
||||||
# dataset = load_images_with_labels(test_path)
|
# dataset = load_images_with_labels(test_path)
|
||||||
# dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batch_size, shuffle=False, num_workers=opt.n_cpu)
|
# dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batch_size, shuffle=False, num_workers=opt.n_cpu)
|
||||||
dataloader = load_images_and_labels(test_path, batch_size=opt.batch_size, img_size=opt.img_size)
|
dataloader = load_images_and_labels(test_path, batch_size=opt.batch_size, img_size=opt.img_size)
|
||||||
|
|
||||||
print('Compute mAP...')
|
print('Compute mAP...')
|
||||||
|
|
||||||
nC = 80 # number of classes
|
mAP = 0
|
||||||
correct = 0
|
outputs, mAPs, TP, confidence, pred_class, target_class = [], [], [], [], [], []
|
||||||
targets = None
|
AP_accum, AP_accum_count = np.zeros(nC), np.zeros(nC)
|
||||||
outputs, mAPs, TP, confidence, pred_class, target_class = [], [], [], [], [], []
|
for batch_i, (imgs, targets) in enumerate(dataloader):
|
||||||
AP_accum, AP_accum_count = np.zeros(nC), np.zeros(nC)
|
|
||||||
for batch_i, (imgs, targets) in enumerate(dataloader):
|
|
||||||
imgs = imgs.to(device)
|
imgs = imgs.to(device)
|
||||||
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
|
@ -81,7 +81,6 @@ for batch_i, (imgs, targets) in enumerate(dataloader):
|
||||||
|
|
||||||
# If no annotations add number of detections as incorrect
|
# If no annotations add number of detections as incorrect
|
||||||
if annotations.size(0) == 0:
|
if annotations.size(0) == 0:
|
||||||
target_cls = []
|
|
||||||
# correct.extend([0 for _ in range(len(detections))])
|
# correct.extend([0 for _ in range(len(detections))])
|
||||||
mAPs.append(0)
|
mAPs.append(0)
|
||||||
continue
|
continue
|
||||||
|
@ -108,7 +107,8 @@ for batch_i, (imgs, targets) in enumerate(dataloader):
|
||||||
correct.append(0)
|
correct.append(0)
|
||||||
|
|
||||||
# Compute Average Precision (AP) per class
|
# Compute Average Precision (AP) per class
|
||||||
AP, AP_class = ap_per_class(tp=correct, conf=detections[:, 4], pred_cls=detections[:, 6], target_cls=target_cls)
|
AP, AP_class = ap_per_class(tp=correct, conf=detections[:, 4], pred_cls=detections[:, 6],
|
||||||
|
target_cls=target_cls)
|
||||||
|
|
||||||
# Accumulate AP per class
|
# Accumulate AP per class
|
||||||
AP_accum_count += np.bincount(AP_class, minlength=nC)
|
AP_accum_count += np.bincount(AP_class, minlength=nC)
|
||||||
|
@ -121,12 +121,18 @@ for batch_i, (imgs, targets) in enumerate(dataloader):
|
||||||
mAPs.append(mAP)
|
mAPs.append(mAP)
|
||||||
|
|
||||||
# Print image mAP and running mean mAP
|
# Print image mAP and running mean mAP
|
||||||
print('+ Sample [%d/%d] AP: %.4f (%.4f)' % (len(mAPs), len(dataloader) * opt.batch_size, mAP, np.mean(mAPs)))
|
print(
|
||||||
|
'+ Sample [%d/%d] AP: %.4f (%.4f)' % (len(mAPs), len(dataloader) * opt.batch_size, mAP, np.mean(mAPs)))
|
||||||
|
|
||||||
# Print mAP per class
|
# Print mAP per class
|
||||||
classes = load_classes(opt.class_path) # Extracts class labels from file
|
classes = load_classes(opt.class_path) # Extracts class labels from file
|
||||||
for i, c in enumerate(classes):
|
for i, c in enumerate(classes):
|
||||||
print('%15s: %-.4f' % (c, AP_accum[i] / AP_accum_count[i]))
|
print('%15s: %-.4f' % (c, AP_accum[i] / AP_accum_count[i]))
|
||||||
|
|
||||||
# Print mAP
|
# Print mAP
|
||||||
print('Mean Average Precision: %.4f' % np.mean(mAPs))
|
print('Mean Average Precision: %.4f' % np.mean(mAPs))
|
||||||
|
return mAP
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
mAP = main(opt)
|
||||||
|
|
19
train.py
19
train.py
|
@ -1,5 +1,6 @@
|
||||||
import argparse
|
import argparse
|
||||||
import time
|
import time
|
||||||
|
import test
|
||||||
|
|
||||||
from models import *
|
from models import *
|
||||||
from utils.datasets import *
|
from utils.datasets import *
|
||||||
|
@ -103,10 +104,10 @@ def main(opt):
|
||||||
# scheduler.step()
|
# scheduler.step()
|
||||||
|
|
||||||
# Update scheduler (manual) at 0, 54, 61 epochs to 1e-3, 1e-4, 1e-5
|
# Update scheduler (manual) at 0, 54, 61 epochs to 1e-3, 1e-4, 1e-5
|
||||||
if epoch < 50:
|
if epoch > 50:
|
||||||
lr = 1e-4
|
|
||||||
else:
|
|
||||||
lr = 1e-5
|
lr = 1e-5
|
||||||
|
else:
|
||||||
|
lr = 1e-4
|
||||||
for g in optimizer.param_groups:
|
for g in optimizer.param_groups:
|
||||||
g['lr'] = lr
|
g['lr'] = lr
|
||||||
|
|
||||||
|
@ -160,10 +161,6 @@ def main(opt):
|
||||||
t1 = time.time()
|
t1 = time.time()
|
||||||
print(s)
|
print(s)
|
||||||
|
|
||||||
# Write epoch results
|
|
||||||
with open('results.txt', 'a') as file:
|
|
||||||
file.write(s + '\n')
|
|
||||||
|
|
||||||
# Update best loss
|
# Update best loss
|
||||||
loss_per_target = rloss['loss'] / rloss['nT']
|
loss_per_target = rloss['loss'] / rloss['nT']
|
||||||
if loss_per_target < best_loss:
|
if loss_per_target < best_loss:
|
||||||
|
@ -184,6 +181,14 @@ def main(opt):
|
||||||
if (epoch > 0) & (epoch % 5 == 0):
|
if (epoch > 0) & (epoch % 5 == 0):
|
||||||
os.system('cp weights/latest.pt weights/backup' + str(epoch) + '.pt')
|
os.system('cp weights/latest.pt weights/backup' + str(epoch) + '.pt')
|
||||||
|
|
||||||
|
# Calculate mAP
|
||||||
|
test.opt.weights_path = 'weights/latest.pt'
|
||||||
|
mAP = test.main(test.opt)
|
||||||
|
|
||||||
|
# Write epoch results
|
||||||
|
with open('results.txt', 'a') as file:
|
||||||
|
file.write(s + '%11.3g' % mAP + '\n')
|
||||||
|
|
||||||
# Save final model
|
# Save final model
|
||||||
dt = time.time() - t0
|
dt = time.time() - t0
|
||||||
print('Finished %g epochs in %.2fs (%.2fs/epoch)' % (epoch, dt, dt / (epoch + 1)))
|
print('Finished %g epochs in %.2fs (%.2fs/epoch)' % (epoch, dt, dt / (epoch + 1)))
|
||||||
|
|
|
@ -11,7 +11,7 @@ gsutil cp gs://ultralytics/yolov3.pt yolov3/weights
|
||||||
python3 detect.py
|
python3 detect.py
|
||||||
|
|
||||||
# Test
|
# Test
|
||||||
python3 test.py -img_size 416 -weights_path weights/latest.pt -conf_thres 0.1
|
python3 test.py -img_size 416 -weights_path weights/latest.pt -conf_thres 0.5
|
||||||
|
|
||||||
# Download and Test
|
# Download and Test
|
||||||
sudo rm -rf yolov3 && git clone https://github.com/ultralytics/yolov3 && cd yolov3
|
sudo rm -rf yolov3 && git clone https://github.com/ultralytics/yolov3 && cd yolov3
|
||||||
|
|
|
@ -435,7 +435,7 @@ def plot_results():
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
plt.figure(figsize=(16, 8))
|
plt.figure(figsize=(16, 8))
|
||||||
s = ['X', 'Y', 'Width', 'Height', 'Objectness', 'Classification', 'Total Loss', 'Precision', 'Recall']
|
s = ['X', 'Y', 'Width', 'Height', 'Objectness', 'Classification', 'Total Loss', 'Precision', 'Recall', 'mAP']
|
||||||
for f in ('results.txt',):
|
for f in ('results.txt',):
|
||||||
results = np.loadtxt(f, usecols=[2, 3, 4, 5, 6, 7, 8, 9, 10]).T
|
results = np.loadtxt(f, usecols=[2, 3, 4, 5, 6, 7, 8, 9, 10]).T
|
||||||
for i in range(9):
|
for i in range(9):
|
||||||
|
|
Loading…
Reference in New Issue