在这里插入代码片
AP = {}
AR = {}
min_area = {}
for label in range(generator.num_classes()):
false_positives = np.zeros((0,))
true_positives = np.zeros((0,))
scores = np.zeros((0,))
num_annotations = 0.0
for i in range(len(generator)):
detections = all_detections[i][label]
annotations = all_annotations[i][label]
num_annotations += annotations.shape[0]
detected_annotations = []
for d in detections:
scores = np.append(scores, d[4])
if annotations.shape[0] == 0:
false_positives = np.append(false_positives, 1)
true_positives = np.append(true_positives, 0)
continue
# calculate min area
for d_i in range(detections.shape[0]):
width = min([detections[d_i][2], detections[d_i][3]])
if width < min_area.get(label, 1e10):
min_area[label] = width
overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations)
assigned_annotation = np.argmax(overlaps, axis=1)
max_overlap = overlaps[0, assigned_annotation]
if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations:
false_positives = np.append(false_positives, 0)
true_positives = np.append(true_positives, 1)
detected_annotations.append(assigned_annotation)
else:
false_positives = np.append(false_positives, 1)
true_positives = np.append(true_positives, 0)
# no annotations -> AP for this class is 0 (is this correct?)
if num_annotations == 0:
average_precisions[label] = 0, 0
continue
# sort by score
indices = np.argsort(-scores)
false_positives = false_positives[indices]
true_positives = true_positives[indices]
# compute false positives and true positives
false_positives = np.cumsum(false_positives)
true_positives = np.cumsum(true_positives)
# compute recall and precision
recall = true_positives / num_annotations
precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps)
# compute average precision
average_precision = _compute_ap(recall, precision)
average_precisions[label] = average_precision, num_annotations
AP[label] = precision
AR[label] = recall
# np.savez('tmp/res.npy', ap=average_precisions, p=AP, r=AR)
def cal_mean(d):
return np.array(list(d.values())).mean()
print('\nmAP:')
for label in range(generator.num_classes()):
label_name = generator.label_to_name(label)
print('{}: {}'.format(label_name, average_precisions[label][0]))
print(f'overall mAP: {cal_mean(average_precisions)}')
# print('\nAP AR:')
# for label in range(generator.num_classes()):
# label_name = generator.label_to_name(label)
# print(f'{label_name}: AP: {AP[label]} AR: {AR[label]}')
# print(f'\n overall AP: {cal_mean(AP):.3f} AR: {cal_mean((AR)):.3f}')
print('min width: ', min_area)
return average_precisions