InPeerReview commited on
Commit
840ef2c
·
verified ·
1 Parent(s): 8cce99f

Upload 3 files

Browse files
Files changed (3) hide show
  1. misc/caculate_metric.py +112 -0
  2. misc/metric_tools.py +230 -0
  3. misc/torchutils.py +83 -0
misc/caculate_metric.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ def calcuate_confusion_matrix(num_class:int, gt:torch.tensor, pred:torch.tensor):
5
+ gt_vector = gt.flatten()
6
+ pred_vector = pred.flatten()
7
+ mask = (gt_vector >= 0) & (gt_vector < num_class)
8
+ cm = torch.bincount(num_class * gt_vector[mask].to(dtype=int) + pred_vector[mask], minlength=num_class ** 2).reshape(num_class, num_class)
9
+ return cm
10
+
11
+ class segmengtion_metric(object):
12
+ def __init__(self, num_class:int, device:str):
13
+ self.num_class = num_class
14
+ self.device = device
15
+ self.confusion_matrix = torch.zeros((self.num_class, self.num_class)).to(self.device)
16
+
17
+
18
+ def clear(self):
19
+ self.confusion_matrix = torch.zeros((self.num_class, self.num_class)).to(self.device)
20
+
21
+
22
+ def update_confusion_matrix(self, gt, pred):
23
+ cm = calcuate_confusion_matrix(self.num_class, gt, pred)
24
+ self.confusion_matrix += cm
25
+
26
+ def get_matrix_per_batch(self, gt, pred):
27
+ confusion_matrix = calcuate_confusion_matrix(self.num_class, gt, pred)
28
+
29
+ tp = torch.diag(confusion_matrix)
30
+
31
+ sum_a1 = torch.sum(confusion_matrix, dim=1)
32
+
33
+ sum_a0 = torch.sum(confusion_matrix, dim=0)
34
+
35
+ acc = tp.sum() / (confusion_matrix.sum() + torch.finfo(type=torch.float32).eps)
36
+ recall = tp / (sum_a1 + torch.finfo(type=torch.float32).eps)
37
+ precision = tp / (sum_a0 + torch.finfo(type=torch.float32).eps)
38
+ f1 = (2 * recall * precision) / (recall + precision + torch.finfo(type=torch.float32).eps)
39
+ iou = tp / (sum_a1 + sum_a0 - tp + torch.finfo(type=torch.float32).eps)
40
+
41
+ cls_precision = dict(zip(['pre_class[{}]'.format(i) for i in range(self.num_class)], precision))
42
+ cls_recall = dict(zip(['rec_class[{}]'.format(i) for i in range(self.num_class)], recall))
43
+ cls_f1 = dict(zip(['f1_class[{}]'.format(i) for i in range(self.num_class)], f1))
44
+ cls_iou = dict(zip(['iou_class[{}]'.format(i) for i in range(self.num_class)], iou))
45
+
46
+ mean_precision = precision[precision != 0].mean()
47
+ mean_recall = recall[recall != 0].mean()
48
+ mean_iou = iou[iou != 0].mean()
49
+ mean_f1 = f1[f1 != 0].mean()
50
+
51
+ score_dict_batch = {'acc': acc, 'mean_pre': mean_precision, 'mean_rec': mean_recall, 'mIoU': mean_iou, 'mF1': mean_f1}
52
+ score_dict_batch.update(cls_precision)
53
+ score_dict_batch.update(cls_recall)
54
+ score_dict_batch.update(cls_iou)
55
+ score_dict_batch.update(cls_f1)
56
+
57
+ return score_dict_batch
58
+
59
+ def get_metric_dict_per_epoch(self):
60
+
61
+ tp = torch.diag(self.confusion_matrix)
62
+
63
+ sum_a1 = torch.sum(self.confusion_matrix, dim=1)
64
+
65
+ sum_a0 = torch.sum(self.confusion_matrix, dim=0)
66
+
67
+ acc = tp.sum() / (self.confusion_matrix.sum() + torch.finfo(type=torch.float32).eps)
68
+
69
+ recall = tp / (sum_a1 + torch.finfo(type=torch.float32).eps)
70
+
71
+ precision = tp / (sum_a0 + torch.finfo(type=torch.float32).eps)
72
+
73
+ f1 = (2 * recall * precision) / (recall + precision + torch.finfo(type=torch.float32).eps)
74
+
75
+ iou = tp / (sum_a1 + sum_a0 - tp + torch.finfo(type=torch.float32).eps)
76
+
77
+ cls_precision = dict(zip(['Precision_Class[{}]'.format(i) for i in range(self.num_class)], precision))
78
+ cls_recall = dict(zip(['Recall_Class[{}]'.format(i) for i in range(self.num_class)], recall))
79
+ cls_iou = dict(zip(['IoU_Class[{}]'.format(i) for i in range(self.num_class)], iou))
80
+ cls_f1 = dict(zip(['F1_Class[{}]'.format(i) for i in range(self.num_class)], f1))
81
+
82
+ mean_precision = precision.mean()
83
+ mean_recall = recall.mean()
84
+ mean_iou = iou.mean()
85
+ mean_f1 = f1.mean()
86
+ score_dict_epoch = {'Accuracy': acc, 'mean_Precision': mean_precision, 'mean_Recall': mean_recall,
87
+ 'mIoU': mean_iou, 'mF1': mean_f1}
88
+
89
+ score_dict_epoch.update(cls_precision)
90
+ score_dict_epoch.update(cls_recall)
91
+ score_dict_epoch.update(cls_iou)
92
+ score_dict_epoch.update(cls_f1)
93
+ return score_dict_epoch
94
+
95
+
96
+
97
+
98
+
99
+
100
+ if __name__=="__main__":
101
+ gt_label = torch.tensor([[0, 1, 2, 3, 1],
102
+ [1, 2, 2, 3, 4]])
103
+
104
+ pre_label = torch.tensor([[0, 1, 2, 3, 1],
105
+ [5, 1, 2, 1, 4]])
106
+
107
+ num_class = 6
108
+ metric = segmengtion_metric(6, 'cuda:0')
109
+ res = metric.get_matrix_per_batch(gt_label, pre_label)
110
+ res1 = metric.get_metric_dict_per_epoch()
111
+ print(res)
112
+ print(res1)
misc/metric_tools.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy import stats
3
+ import math
4
+
5
+ class AverageMeter(object):
6
+
7
+ def __init__(self):
8
+ self.initialized = False
9
+ self.val = None
10
+ self.avg = None
11
+ self.sum = None
12
+ self.count = None
13
+
14
+ def initialize(self, val, weight):
15
+ self.val = val
16
+ self.avg = val
17
+ self.sum = val * weight
18
+ self.count = weight
19
+ self.initialized = True
20
+
21
+ def update(self, val, weight=1):
22
+ if not self.initialized:
23
+ self.initialize(val, weight)
24
+ else:
25
+ self.add(val, weight)
26
+
27
+ def add(self, val, weight):
28
+ self.val = val
29
+ self.sum += val * weight
30
+ self.count += weight
31
+ self.avg = self.sum / self.count
32
+
33
+ def value(self):
34
+ return self.val
35
+
36
+ def average(self):
37
+ return self.avg
38
+
39
+ def get_scores(self):
40
+ scores_dict = cm2score(self.sum)
41
+ return scores_dict
42
+
43
+ def clear(self):
44
+ self.initialized = False
45
+
46
+
47
+ class ConfuseMatrixMeter(AverageMeter):
48
+
49
+ def __init__(self, n_class):
50
+ super(ConfuseMatrixMeter, self).__init__()
51
+ self.n_class = n_class
52
+
53
+ def update_cm(self, pr, gt, weight=1):
54
+
55
+ val = get_confuse_matrix(num_classes=self.n_class, label_gts=gt, label_preds=pr)
56
+ self.update(val, weight)
57
+ current_score = cm2F1(val)
58
+ return current_score
59
+
60
+ def get_scores(self):
61
+ scores_dict = cm2score(self.sum)
62
+ return scores_dict
63
+
64
+
65
+
66
+ def harmonic_mean(xs):
67
+ harmonic_mean = len(xs) / sum((x+1e-6)**-1 for x in xs)
68
+ return harmonic_mean
69
+
70
+
71
+ def cm2F1(confusion_matrix):
72
+ hist = confusion_matrix
73
+ n_class = hist.shape[0]
74
+ tp = np.diag(hist)
75
+ sum_a1 = hist.sum(axis=1)
76
+ sum_a0 = hist.sum(axis=0)
77
+
78
+ acc = tp.sum() / (hist.sum() + np.finfo(np.float32).eps)
79
+
80
+
81
+ recall = tp / (sum_a1 + np.finfo(np.float32).eps)
82
+
83
+ precision = tp / (sum_a0 + np.finfo(np.float32).eps)
84
+
85
+ F1 = 2 * recall * precision / (recall + precision + np.finfo(np.float32).eps)
86
+ mean_F1 = np.nanmean(F1)
87
+ return mean_F1
88
+
89
+
90
+ def cm2score(confusion_matrix):
91
+ hist = confusion_matrix
92
+ n_class = hist.shape[0]
93
+
94
+ if n_class > 2:
95
+
96
+ hist_fg = hist[1:, 1:]
97
+ c2hist = np.zeros((2, 2))
98
+ c2hist[0][0] = hist[0][0]
99
+ c2hist[0][1] = hist.sum(1)[0] - hist[0][0]
100
+ c2hist[1][0] = hist.sum(0)[0] - hist[0][0]
101
+ c2hist[1][1] = hist_fg.sum()
102
+ hist_n0 = hist.copy()
103
+ hist_n0[0][0] = 0
104
+ kappa_n0 = cal_kappa(hist_n0)
105
+ iu_scd = np.nan_to_num(np.diag(c2hist) / (c2hist.sum(1) + c2hist.sum(0) - np.diag(c2hist)))
106
+ IoU_fg = iu_scd[1]
107
+ IoU_mean = (iu_scd[0] + iu_scd[1]) / 2
108
+ Sek = (kappa_n0 * math.exp(IoU_fg)) / math.e
109
+ pixel_sum = hist.sum()
110
+ change_pred_sum = pixel_sum - hist.sum(1)[0].sum()
111
+ change_label_sum = pixel_sum - hist.sum(0)[0].sum()
112
+ change_ratio = change_label_sum / pixel_sum
113
+ SC_TP = np.diag(hist[1:, 1:]).sum()
114
+ SC_Precision = np.nan_to_num(SC_TP / change_pred_sum) + np.finfo(np.float32).eps
115
+ SC_Recall = np.nan_to_num(SC_TP / change_label_sum) + np.finfo(np.float32).eps
116
+ Fscd = stats.hmean([SC_Precision, SC_Recall])
117
+
118
+
119
+ tp = np.diag(hist)
120
+ sum_a1 = hist.sum(axis=1)
121
+ sum_a0 = hist.sum(axis=0)
122
+
123
+ acc = tp.sum() / (hist.sum() + np.finfo(np.float32).eps)
124
+
125
+
126
+ recall = tp / (sum_a1 + np.finfo(np.float32).eps)
127
+
128
+ precision = tp / (sum_a0 + np.finfo(np.float32).eps)
129
+
130
+ F1 = 2*recall * precision / (recall + precision + np.finfo(np.float32).eps)
131
+
132
+ mean_F1 = np.nanmean(F1)
133
+
134
+ iu = tp / (sum_a1 + hist.sum(axis=0) - tp + np.finfo(np.float32).eps)
135
+ mean_iu = np.nanmean(iu)
136
+
137
+ freq = sum_a1 / (hist.sum() + np.finfo(np.float32).eps)
138
+ fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
139
+
140
+ cls_iou = dict(zip(['iou_'+str(i) for i in range(n_class)], iu))
141
+
142
+ cls_precision = dict(zip(['precision_'+str(i) for i in range(n_class)], precision))
143
+ cls_recall = dict(zip(['recall_'+str(i) for i in range(n_class)], recall))
144
+ cls_F1 = dict(zip(['F1_'+str(i) for i in range(n_class)], F1))
145
+
146
+ if n_class > 2:
147
+ score_dict = {'acc': acc, 'miou': mean_iu, 'mf1':mean_F1, 'SCD_Sek':Sek, 'Fscd':Fscd, 'SCD_IoU_mean':IoU_mean}
148
+ else:
149
+ score_dict = {'acc': acc, 'miou': mean_iu, 'mf1':mean_F1}
150
+ score_dict.update(cls_iou)
151
+ score_dict.update(cls_F1)
152
+ score_dict.update(cls_precision)
153
+ score_dict.update(cls_recall)
154
+ return score_dict
155
+
156
+
157
+ def get_confuse_matrix(num_classes, label_gts, label_preds):
158
+
159
+ def __fast_hist(label_gt, label_pred):
160
+
161
+ mask = (label_gt >= 0) & (label_gt < num_classes)
162
+ hist = np.bincount(num_classes * label_gt[mask].astype(int) + label_pred[mask],
163
+ minlength=num_classes**2).reshape(num_classes, num_classes)
164
+ return hist
165
+ confusion_matrix = np.zeros((num_classes, num_classes))
166
+ for lt, lp in zip(label_gts, label_preds):
167
+ confusion_matrix += __fast_hist(lt.flatten(), lp.flatten())
168
+ return confusion_matrix
169
+
170
+
171
+ def get_mIoU(num_classes, label_gts, label_preds):
172
+ confusion_matrix = get_confuse_matrix(num_classes, label_gts, label_preds)
173
+ score_dict = cm2score(confusion_matrix)
174
+ return score_dict['miou']
175
+
176
+ def fast_hist(a, b, n):
177
+ k = (a >= 0) & (a < n)
178
+ return np.bincount(n * a[k].astype(int) + b[k], minlength=n ** 2).reshape(n, n)
179
+
180
+ def get_hist(image, label, num_class):
181
+ hist = np.zeros((num_class, num_class))
182
+ hist += fast_hist(image.flatten(), label.flatten(), num_class)
183
+ return hist
184
+
185
+ def cal_kappa(hist):
186
+ if hist.sum() == 0:
187
+ po = 0
188
+ pe = 1
189
+ kappa = 0
190
+ else:
191
+ po = np.diag(hist).sum() / hist.sum()
192
+ pe = np.matmul(hist.sum(1), hist.sum(0).T) / hist.sum() ** 2
193
+ if pe == 1:
194
+ kappa = 0
195
+ else:
196
+ kappa = (po - pe) / (1 - pe)
197
+ return kappa
198
+
199
+ def SCDD_eval_all(preds, labels, num_class):
200
+ hist = np.zeros((num_class, num_class))
201
+ for pred, label in zip(preds, labels):
202
+ infer_array = np.array(pred)
203
+ unique_set = set(np.unique(infer_array))
204
+ assert unique_set.issubset(set([0, 1, 2, 3, 4, 5, 6])), "unrecognized label number"
205
+ label_array = np.array(label)
206
+ assert infer_array.shape == label_array.shape, "The size of prediction and target must be the same"
207
+ hist += get_hist(infer_array, label_array, num_class)
208
+
209
+ hist_fg = hist[1:, 1:]
210
+ c2hist = np.zeros((2, 2))
211
+ c2hist[0][0] = hist[0][0]
212
+ c2hist[0][1] = hist.sum(1)[0] - hist[0][0]
213
+ c2hist[1][0] = hist.sum(0)[0] - hist[0][0]
214
+ c2hist[1][1] = hist_fg.sum()
215
+ hist_n0 = hist.copy()
216
+ hist_n0[0][0] = 0
217
+ kappa_n0 = cal_kappa(hist_n0)
218
+ iu = np.diag(c2hist) / (c2hist.sum(1) + c2hist.sum(0) - np.diag(c2hist))
219
+ IoU_fg = iu[1]
220
+ IoU_mean = (iu[0] + iu[1]) / 2
221
+ Sek = (kappa_n0 * math.exp(IoU_fg)) / math.e
222
+
223
+ pixel_sum = hist.sum()
224
+ change_pred_sum = pixel_sum - hist.sum(1)[0].sum()
225
+ change_label_sum = pixel_sum - hist.sum(0)[0].sum()
226
+ SC_TP = np.diag(hist[1:, 1:]).sum()
227
+ SC_Precision = SC_TP / change_pred_sum
228
+ SC_Recall = SC_TP / change_label_sum
229
+ Fscd = stats.hmean([SC_Precision, SC_Recall])
230
+ return Fscd, IoU_mean, Sek
misc/torchutils.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch import Tensor
4
+ from torch.optim import lr_scheduler
5
+ from typing import Iterable, Set, Tuple
6
+ import logging
7
+ import os
8
+
9
+ logger = logging.getLogger('base')
10
+
11
+ def simplex(t: Tensor, axis=1) -> bool:
12
+ _sum = t.sum(axis).float()
13
+ _ones = torch.ones_like(_sum, dtype=torch.float32)
14
+ return torch.allclose(_sum, _ones)
15
+
16
+ def one_hot(t: Tensor, axis=1) -> bool:
17
+ return simplex(t, axis) and sset(t, [0, 1])
18
+
19
+ def uniq(a: Tensor) -> Set:
20
+ return set(torch.unique(a.cpu()).numpy())
21
+
22
+ def sset(a: Tensor, sub: Iterable) -> bool:
23
+ return uniq(a).issubset(sub)
24
+
25
+ def class2one_hot(seg: Tensor, C: int) -> Tensor:
26
+ if len(seg.shape) == 2: # (H, W) 的情况
27
+ seg = seg.unsqueeze(dim=0)
28
+ assert sset(seg, list(range(C))), "输入 Tensor 中的类别索引超出范围!"
29
+
30
+ if seg.ndim == 4:
31
+ seg = seg.squeeze(dim=1)
32
+
33
+ b, w, h = seg.shape # 获取 batch 维度、宽度、高度
34
+ res = torch.stack([seg == c for c in range(C)], dim=1).int()
35
+ assert res.shape == (b, C, w, h)
36
+ assert one_hot(res), "转换后的 Tensor 不是 one-hot 编码!"
37
+
38
+ return res
39
+
40
+ def get_scheduler(optimizer, args):
41
+ """返回学习率调度器"""
42
+ if args['scheduler']['lr_policy'] == 'linear':
43
+ def lambda_rule(epoch):
44
+ return 1.0 - epoch / float(args['n_epoch'] + 1)
45
+ return lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
46
+
47
+ elif args['scheduler']['lr_policy'] == 'step':
48
+ step_size = args['n_epoch'] // args['scheduler']['n_steps']
49
+ return lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=args['scheduler']['gamma'])
50
+
51
+ else:
52
+ raise NotImplementedError(f"学习率策略 [{args['scheduler']['lr_policy']}] 未实现!")
53
+
54
+ def save_network(opt, epoch, cd_model, optimizer, is_best_model=False):
55
+ """ 保存当前 epoch 的模型和优化器参数 """
56
+
57
+ os.makedirs(opt['path_cd']['checkpoint'], exist_ok=True)
58
+
59
+ cd_gen_path = os.path.join(opt['path_cd']['checkpoint'], f'cd_model_E{epoch}_gen.pth')
60
+ cd_opt_path = os.path.join(opt['path_cd']['checkpoint'], f'cd_model_E{epoch}_opt.pth')
61
+
62
+ best_cd_gen_path = os.path.join(opt['path_cd']['checkpoint'], 'best_cd_model_gen.pth')
63
+ best_cd_opt_path = os.path.join(opt['path_cd']['checkpoint'], 'best_cd_model_opt.pth')
64
+
65
+ network = cd_model.module if isinstance(cd_model, nn.DataParallel) else cd_model
66
+ state_dict = {key: param.cpu() for key, param in network.state_dict().items()}
67
+
68
+ torch.save(state_dict, cd_gen_path)
69
+ if is_best_model:
70
+ torch.save(state_dict, best_cd_gen_path)
71
+
72
+ opt_state = {
73
+ 'epoch': epoch,
74
+ 'scheduler': None,
75
+ 'optimizer': optimizer.state_dict()
76
+ }
77
+ torch.save(opt_state, cd_opt_path)
78
+ if is_best_model:
79
+ torch.save(opt_state, best_cd_opt_path)
80
+
81
+ logger.info(f'✅ 当前模型已保存至 [{cd_gen_path}]')
82
+ if is_best_model:
83
+ logger.info(f'🏆 最佳模型已更新至 [{best_cd_gen_path}]')