|
|
|
|
|
import matplotlib.pyplot as plt |
|
import numpy as np |
|
|
|
|
|
def fitness(x): |
|
|
|
w = [0.0, 0.0, 0.1, 0.9] |
|
return (x[:, :4] * w).sum(1) |
|
|
|
|
|
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, fname='precision-recall_curve.png'): |
|
""" Compute the average precision, given the recall and precision curves. |
|
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. |
|
# Arguments |
|
tp: True positives (nparray, nx1 or nx10). |
|
conf: Objectness value from 0-1 (nparray). |
|
pred_cls: Predicted object classes (nparray). |
|
target_cls: True object classes (nparray). |
|
plot: Plot precision-recall curve at [email protected] |
|
fname: Plot filename |
|
# Returns |
|
The average precision as computed in py-faster-rcnn. |
|
""" |
|
|
|
|
|
i = np.argsort(-conf) |
|
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] |
|
|
|
|
|
unique_classes = np.unique(target_cls) |
|
|
|
|
|
px, py = np.linspace(0, 1, 1000), [] |
|
pr_score = 0.1 |
|
s = [unique_classes.shape[0], tp.shape[1]] |
|
ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s) |
|
for ci, c in enumerate(unique_classes): |
|
i = pred_cls == c |
|
n_l = (target_cls == c).sum() |
|
n_p = i.sum() |
|
|
|
if n_p == 0 or n_l == 0: |
|
continue |
|
else: |
|
|
|
fpc = (1 - tp[i]).cumsum(0) |
|
tpc = tp[i].cumsum(0) |
|
|
|
|
|
recall = tpc / (n_l + 1e-16) |
|
r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) |
|
|
|
|
|
precision = tpc / (tpc + fpc) |
|
p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) |
|
|
|
|
|
for j in range(tp.shape[1]): |
|
ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) |
|
if j == 0: |
|
py.append(np.interp(px, mrec, mpre)) |
|
|
|
|
|
f1 = 2 * p * r / (p + r + 1e-16) |
|
|
|
if plot: |
|
py = np.stack(py, axis=1) |
|
fig, ax = plt.subplots(1, 1, figsize=(5, 5)) |
|
ax.plot(px, py, linewidth=0.5, color='grey') |
|
ax.plot(px, py.mean(1), linewidth=2, color='blue', label='all classes %.3f [email protected]' % ap[:, 0].mean()) |
|
ax.set_xlabel('Recall') |
|
ax.set_ylabel('Precision') |
|
ax.set_xlim(0, 1) |
|
ax.set_ylim(0, 1) |
|
plt.legend() |
|
fig.tight_layout() |
|
fig.savefig(fname, dpi=200) |
|
|
|
return p, r, ap, f1, unique_classes.astype('int32') |
|
|
|
|
|
def compute_ap(recall, precision): |
|
""" Compute the average precision, given the recall and precision curves. |
|
Source: https://github.com/rbgirshick/py-faster-rcnn. |
|
# Arguments |
|
recall: The recall curve (list). |
|
precision: The precision curve (list). |
|
# Returns |
|
The average precision as computed in py-faster-rcnn. |
|
""" |
|
|
|
|
|
mrec = recall |
|
mpre = precision |
|
|
|
|
|
mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) |
|
|
|
|
|
method = 'interp' |
|
if method == 'interp': |
|
x = np.linspace(0, 1, 101) |
|
ap = np.trapz(np.interp(x, mrec, mpre), x) |
|
else: |
|
i = np.where(mrec[1:] != mrec[:-1])[0] |
|
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) |
|
|
|
return ap, mpre, mrec |
|
|