-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathevaluation.py
More file actions
168 lines (133 loc) · 7.62 KB
/
evaluation.py
File metadata and controls
168 lines (133 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
from torchmetrics.detection.mean_ap import MeanAveragePrecision
import json
from torch import Tensor
import pandas as pd
from evalutils.scorers import score_detection
import os
import yaml
import numpy as np
from typing import Dict
class MIDOG2021Evaluation():
def __init__(self,path):
self._predictions_file = os.path.join(path, 'mitotic-figures.json')
self._gt_file = os.path.join(path, 'ground-truth.json')
self._output_file = os.path.join(path, 'metrics.json')
with open(os.path.join(path, "config.yaml"), 'r') as stream:
self.config = yaml.safe_load(stream)
self.val_gt, self.test_gt = {}, {}
self.load_gt()
self.cases = pd.read_csv('datasets_xvalidation.csv', delimiter=";")
self.case_to_tumor = {'%03d.tiff' % d.loc['Slide'] : d.loc['Tumor'] for _, d in self.cases.iterrows()}
def load_gt(self):
self.gt = json.load(open(self._gt_file,'r'))
val_files = json.loads(self.config['x-validation']['value']['valid'])
for key, value in self.gt.items():
if key in val_files:
self.val_gt.update({key:value})
else:
self.test_gt.update({key:value})
def load_predictions(self):
predictions_json = json.load(open(self._predictions_file,'r'))
predictions={}
for fname, pred in predictions_json.items():
if (fname not in self.gt):
print('Warning: Found predictions for image ',fname,'which is not part of the ground truth.')
continue
if 'points' not in pred:
print('Warning: Wrong format. Field points is not part of detections.')
continue
points=[]
for point in pred['points']:
detected_class = 1 if 'name' not in point or point['name']=='mitotic figure' else 0
detected_thr = 0.5 if 'probability' not in point else point['probability']
if 'name' not in point:
print('Warning: Old format. Field name is not part of detections.')
if 'probability' not in point:
print('Warning: Old format. Field probability is not part of detections.')
if 'point' not in point:
print('Warning: Point is not part of points structure.')
continue
points.append([*point['point'][0:3], detected_class, detected_thr])
predictions[fname]=points
self.predictions=predictions
@property
def _metrics(self) -> Dict:
""" Returns the calculated case and aggregate results """
return {
"case": self._case_results,
"aggregates": self._aggregate_results,
}
def score(self, val=True, det=0.5):
cases = list(self.val_gt.keys()) if val else list(self.test_gt.keys())
self._case_results={}
self.map_metric = MeanAveragePrecision(box_format='xyxy', iou_type='bbox', max_detection_thresholds=[1,10,1e6], rec_thresholds=np.arange(0,1.01,0.01).tolist())
tumor_types = list(self.cases[self.cases['Slide'].isin([int(c[:3]) for c in cases])]['Tumor'].unique())
self.per_tumor_map_metric = {d: MeanAveragePrecision(box_format='xyxy', iou_type='bbox', max_detection_thresholds=[1,10,1e6], rec_thresholds=np.arange(0,1.01,0.01).tolist()) for d in tumor_types}
for idx, case in enumerate(cases):
if case not in self.predictions:
print('Warning: No prediction for file: ',case)
continue
# Filter out all predictions with class==0, retain predictions with class==1
filtered_predictions = [(x,y,0) for x,y,z,cls,sc in self.predictions[case] if cls==1 and sc > det]
bbox_size = 0.01125 # equals to 7.5mm distance for horizontal distance at 0.5 IOU
pred_dict = [{'boxes': Tensor([[x-bbox_size,y-bbox_size, x+bbox_size, y+bbox_size] for (x,y,z,_,_) in self.predictions[case]]),
'labels': Tensor([1,]*len(self.predictions[case])),
'scores': Tensor([sc for (x,y,z,_,sc) in self.predictions[case]])}]
target_dict = [{'boxes': Tensor([[x-bbox_size,y-bbox_size, x+bbox_size, y+bbox_size] for (x,y,z) in self.gt[case]]),
'labels' : Tensor([1,]*len(self.gt[case]))}]
self.map_metric.update(pred_dict,target_dict)
self.per_tumor_map_metric[self.case_to_tumor[case]].update(pred_dict,target_dict)
sc = score_detection(ground_truth=self.gt[case],predictions=filtered_predictions,radius=7.5E-3)._asdict()
self._case_results[case] = sc
self._aggregate_results = self.score_aggregates()
def save(self):
with open(self._output_file, "w") as f:
f.write(json.dumps(self._metrics))
def evaluate(self):
self.load_predictions()
thresh = self.find_threshold()
self.score(val=True, det=thresh)
self._aggregate_results['det_threshold'] = thresh
self.save()
def find_threshold(self):
f1_scores = {}
for thresh in np.arange(0.5, 1, 0.01):
self.score(det=thresh)
f1_scores.update({thresh: self._aggregate_results['f1_score']})
return max(f1_scores, key=f1_scores.get)
def score_aggregates(self):
# per tumor stats
per_tumor = {d : {'tp': 0, 'fp':0, 'fn':0} for d in self.per_tumor_map_metric}
tp,fp,fn = 0,0,0
for s in self._case_results:
tp += self._case_results[s]["true_positives"]
fp += self._case_results[s]["false_positives"]
fn += self._case_results[s]["false_negatives"]
per_tumor[self.case_to_tumor[s]]['tp'] += self._case_results[s]["true_positives"]
per_tumor[self.case_to_tumor[s]]['fp'] += self._case_results[s]["false_positives"]
per_tumor[self.case_to_tumor[s]]['fn'] += self._case_results[s]["false_negatives"]
aggregate_results=dict()
eps = 1E-6
aggregate_results["precision"] = tp / (tp + fp + eps)
aggregate_results["recall"] = tp / (tp + fn + eps)
aggregate_results["f1_score"] = (2 * tp + eps) / ((2 * tp) + fp + fn + eps)
metrics_values = self.map_metric.compute()
aggregate_results["mAP"] = metrics_values['map_50'].tolist()
for tumor in per_tumor:
aggregate_results[f'{tumor}_precision'] = per_tumor[tumor]['tp'] / (per_tumor[tumor]['tp'] + per_tumor[tumor]['fp'] + eps)
aggregate_results[f'{tumor}_recall'] = per_tumor[tumor]['tp'] / (per_tumor[tumor]['tp'] + per_tumor[tumor]['fn'] + eps)
aggregate_results[f'{tumor}_f1'] = (2 * per_tumor[tumor]['tp'] + eps) / ((2 * per_tumor[tumor]['tp']) + per_tumor[tumor]['fp'] + per_tumor[tumor]['fn'] + eps)
pt_metrics_values = self.per_tumor_map_metric[tumor].compute()
aggregate_results[f"{tumor}_mAP"] = pt_metrics_values['map_50'].tolist()
return aggregate_results
def evaluate(directory):
for root, dirs, files in os.walk(directory):
for dir in dirs:
with open(os.path.join(directory, dir, "files", "wandb-summary.json"), 'r') as f:
data = json.load(f)
# Training is done but model has not yet been evaluated
if os.path.exists(os.path.join(directory, dir, "files", "mitotic-figures.json")):
evaluation = MIDOG2021Evaluation(os.path.join(directory, dir, "files"))
print("Evaluating", dir)
evaluation.evaluate()
break