/
miou.py
67 lines (59 loc) · 2.12 KB
/
miou.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
# -*- coding: utf-8 -*-
"""MiOU.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1slvaAyzBRlB4dgEO7hhxpH1CFEhwVAZa
"""
def MiOU(pred_mask,mask,n_classes):
pred_mask = F.softmax(pred_mask, dim=1)
pred_mask = torch.argmax(pred_mask,dim=1)
pred_mask = pred_mask.contiguous().view(-1)
iou_per_class = []
for j in range(n_classes):
intersect=0
union=smooth
for i in range(pred_mask.shape[0]):
if pred_mask[i]==j and mask[i]==j:
intersect+=1
if pred_mask[i]==j:
union+=1
if mask[i]==j:
union+=1
iou=intersect/union
iou_per_class.append(iou)
return np.mean(iou_per_class)
import tensorflow as tf
def MiOU(pred_mask,mask,n_classes):
pred_mask = F.softmax(pred_mask, dim=1)
pred_mask = torch.argmax(pred_mask,dim=1)
pred_mask = pred_mask.contiguous().view(-1)
pred_oht = tf.one_hot(pred_mask,depth=24)
mask = mask.contiguous().view(-1)
mask_oht = tf.one_hot(pred_mask,depth=24)
mulplication=mask_oht*pred_oht
intersection=mulplication.sum(1)
union=mask_oht.sum(1)+pred_oht.sum(1)
iou=[]
for i in range(intersection.shape[0]):
iou_cls=intersection[i]/(union[i]+1)
iou.append(iou_cls)
miou=np.mean(iou)
return miou
def MiOU(output,label,n_class,batch_size):
with torch.no_grad():
pred_mask = F.softmax(pred_mask, dim=1)
pred_mask = torch.argmax(pred_mask, dim=1)
pred_mask = pred_mask.contiguous().view(-1)
mask = mask.contiguous().view(-1)
iou_per_class = []
for clas in range(0, n_classes): #loop per pixel class
true_class = pred_mask == clas
true_label = mask == clas
if true_label.long().sum().item() == 0: #no exist label in this loop
iou_per_class.append(np.nan)
else:
intersect = torch.logical_and(true_class, true_label).sum().float().item()
union = torch.logical_or(true_class, true_label).sum().float().item()
iou = intersect / (union +1)
iou_per_class.append(iou)
return np.nanmean(iou_per_class)