python
import json
import numpy as np
"""
ActivityNet 1.3 の注釈(activity_net.v1-3.min.json)を読み、時間方向の検出の平均 mAP を計算する
database[<YouTube の ID>] = {
'subset': 'training' | 'validation' | 'testing',
'duration': 動画の長さ(秒), 'resolution': ..., 'url': ...,
'annotations': [{'label': クラス名, 'segment': [開始の秒, 終了の秒]}, ...],
}
公式の評価コード(github.com/activitynet/ActivityNet の Evaluation/eval_detection.py)と同じ手順を小さく書いたもの
"""
with open('activity_net.v1-3.min.json') as f:
anno = json.load(f)
gt = {} # クラス名 -> [(動画の ID, 開始, 終了), ...]
for vid, v in anno['database'].items():
if v['subset'] != 'validation': # テスト用のラベルは公開されていないので、検証用で評価する
continue
for a in v['annotations']:
gt.setdefault(a['label'], []).append((vid, a['segment'][0], a['segment'][1]))
print(len(gt)) # 200
def t_iou(seg, segs):
# 1 つの区間と複数の区間の、時間方向の IoU
inter = np.clip(np.minimum(seg[1], segs[:, 1]) - np.maximum(seg[0], segs[:, 0]), 0, None)
union = (seg[1] - seg[0]) + (segs[:, 1] - segs[:, 0]) - inter
return inter / union
def average_precision(gts, preds, thr):
# gts: [(動画, 開始, 終了)]、preds: [(動画, 開始, 終了, 確信度)](同じクラス)
preds = sorted(preds, key=lambda p: -p[3])
by_vid = {}
for i, (vid, s, e) in enumerate(gts):
by_vid.setdefault(vid, []).append((i, s, e))
used = set()
tp = np.zeros(len(preds))
for k, (vid, s, e, _) in enumerate(preds):
cands = by_vid.get(vid, [])
if not cands:
continue
ious = t_iou((s, e), np.array([[c[1], c[2]] for c in cands]))
for j in np.argsort(-ious): # 重なりの大きい正解から順に、まだ使っていないものに対応させる
if ious[j] < thr:
break
if cands[j][0] not in used:
used.add(cands[j][0])
tp[k] = 1
break
tp_cum = np.cumsum(tp)
rec = tp_cum / max(len(gts), 1)
prec = tp_cum / np.arange(1, len(preds) + 1)
# VOC と同じく、適合率を右から単調にしてから面積を取る
mprec = np.concatenate([[0], prec, [0]])
mrec = np.concatenate([[0], rec, [1]])
for i in range(len(mprec) - 2, -1, -1):
mprec[i] = max(mprec[i], mprec[i + 1])
idx = np.where(mrec[1:] != mrec[:-1])[0] + 1
return float(np.sum((mrec[idx] - mrec[idx - 1]) * mprec[idx]))
def average_map(predictions, thresholds=np.linspace(0.5, 0.95, 10)):
# predictions: クラス名 -> [(動画, 開始, 終了, 確信度)]
maps = [np.mean([average_precision(g, predictions.get(c, []), t) for c, g in gt.items()]) for t in thresholds]
return float(np.mean(maps)), dict(zip(np.round(thresholds, 2), maps))