-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluate.py
212 lines (146 loc) · 6.02 KB
/
evaluate.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""
The evaluate.py needs two arguments,
--root (compulsary) - root directory of Cityscapes
--model_path (compulsary) - path of the saved_model
The trained model is evaluated on Cityscapes validation dataset. The metrics we calculate are,
accuracy, f1-score, sensitivity, jaccardSimilarity, diceScore, IoU.
We use the gt with label 255 as negative and 0-19 are postivies for all metrics except IoU. FN - (gt == 255) and (pred in (0-19)).
While for Iou, we ignore the 255, and calculate with 0-19 classes only. This is done to ensure the results can be compared with other
networks for Cityscapes.
"""
import torch
import collections
import torch.nn.functional as F
import numpy as np
import cv2
from model import model
from tabulate import tabulate
from sklearn import metrics
from torch.utils.data import DataLoader
from cityscapes import CityScapes
from tqdm import tqdm
from arg_parser import evaluate
class Evaluate:
def __init__(self, dataset, net):
self.net = net
self.ds = dataset
self.n_classes = 19
self.steps = 0
self.metrics = collections.defaultdict(dict)
self.class_metrics = dict()
self.macro_metrics = dict()
self.ignore_lb = torch.tensor(self.ds.ignore_lb, dtype=torch.int64).cuda() if torch.cuda.is_available() else torch.tensor(self.ds.ignore_lb, dtype=torch.int64)
def __call__(self, im, lb):
self.net.eval()
with torch.no_grad():
out = self.net(im)
preds = out.argmax(dim=1)
lb_flat = lb.view(-1)
preds_flat = preds.view(-1)
self.append_class_wise(lb_flat, preds_flat)
self.steps += 1
self.net.train()
def append_class_wise(self, lb_flat, preds_flat):
gto = (lb_flat == self.ignore_lb)
gtn = (lb_flat != self.ignore_lb)
for class_id in range(0, self.n_classes):
gt = (lb_flat == class_id)
pred = (preds_flat == class_id)
eq = torch.logical_and(gt, pred)
ne = torch.not_equal(gt, pred)
tp = int(torch.count_nonzero(torch.logical_and(eq, gtn)))
tn = int(torch.count_nonzero(torch.logical_and(eq, gto)))
fp = int(torch.count_nonzero(torch.logical_and(ne, gtn)))
fn = int(torch.count_nonzero(torch.logical_and(ne, gto)))
try: self.metrics[class_id]['tn'] += tn
except KeyError: self.metrics[class_id]['tn'] = tn
try: self.metrics[class_id]['fp'] += fp
except KeyError: self.metrics[class_id]['fp'] = fp
try: self.metrics[class_id]['fn'] += fn
except KeyError: self.metrics[class_id]['fn'] = fn
try: self.metrics[class_id]['tp'] += tp
except KeyError: self.metrics[class_id]['tp'] = tp
def compute_metrics(self):
macro_metrics = {
'IoU': 0
}
class_metrics = dict()
for class_id in range(0, self.n_classes):
tp = self.metrics[class_id]['tp']
fp = self.metrics[class_id]['fp']
fn = self.metrics[class_id]['fn']
tn = self.metrics[class_id]['tn']
try: iou = tp / (tp + fp)
except ZeroDivisionError: iou = 0
class_info = self.ds.get_class_info(class_id)
class_metrics[class_info['name']] = {
'IoU': iou
}
macro_metrics['IoU'] += iou
macro_metrics['IoU'] /= self.n_classes
self.macro_metrics = macro_metrics
self.class_metrics = class_metrics
def __str__(self):
self.compute_metrics()
macro_table = [["mean", *[round(f, 3) for f in self.macro_metrics.values()]]]
macro_table = tabulate(macro_table, headers=self.macro_metrics.keys(), tablefmt="pretty")
micro_table = [[k, *[round(f, 3) for f in v.values()]] for k, v in self.class_metrics.items()]
micro_table = tabulate(micro_table, headers=self.macro_metrics.keys(), tablefmt="pretty")
table = f'{macro_table}\n\n{micro_table}'
return table
def loss(self):
mean = list()
for f in self.macro_metrics.values():
mean.append(f)
return 1 - (sum(mean) / len(mean))
def evaluate_net(args, net):
scale = 1
cropsize = [int(2048 * scale), int(1024 * scale)]
cityscapes_path = args.cityscapes_path
ds = CityScapes(cityscapes_path, cropsize=cropsize, mode='val')
dl = DataLoader(ds,
batch_size=8,
shuffle=False,
num_workers=8,
pin_memory=True)
evaluate = Evaluate(ds, net)
print('Evaluate model')
for impth, im, lb in tqdm(dl):
with torch.no_grad():
if torch.cuda.is_available():
im = im.cuda()
lb = lb.cuda()
evaluate(im, lb)
return evaluate
def main(args):
scale = 1
cropsize = [int(2048 * scale), int(1024 * scale)]
cityscapes_path = args.cityscapes_path
ds = CityScapes(cityscapes_path, cropsize=cropsize, mode='val')
n_classes = ds.n_classes
dl = DataLoader(ds,
batch_size=10,
shuffle=False,
num_workers=8,
pin_memory=True,
drop_last=True)
net = model.get_network(n_classes)
saved_path = args.saved_model
print(saved_path)
loaded_model = torch.load(saved_path, map_location=torch.device('cuda') if torch.cuda.is_available() else 'cpu')
state_dict = loaded_model['state_dict']
net.load_state_dict(state_dict, strict=False)
if torch.cuda.is_available():
net.cuda()
net.eval()
evaluate = Evaluate(ds, net)
for images, im, lb in tqdm(dl):
with torch.no_grad():
if torch.cuda.is_available():
im = im.cuda()
lb = lb.cuda()
evaluate(im, lb)
print(evaluate)
if __name__ == "__main__":
args = evaluate()
main(args)