-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
60 lines (50 loc) · 1.57 KB
/
utils.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
import numpy as np
from sklearn.metrics import confusion_matrix
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
self.cnt += n
self.avg = self.sum / self.cnt
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res, target, pred.squeeze()
def output_metric(tar, pre):
matrix = confusion_matrix(tar, pre)
OA, AA_mean, Kappa, AA = cal_results(matrix)
return OA, AA_mean, Kappa, AA
def cal_results(matrix):
shape = np.shape(matrix)
number = 0
sum = 0
AA = np.zeros([shape[0]], dtype=np.float32)
for i in range(shape[0]):
number += matrix[i, i]
AA[i] = matrix[i, i] / np.sum(matrix[i, :])
sum += np.sum(matrix[i, :]) * np.sum(matrix[:, i])
OA = number / np.sum(matrix)
AA_mean = np.mean(AA)
pe = sum / (np.sum(matrix) ** 2)
Kappa = (OA - pe) / (1 - pe)
return OA, AA_mean, Kappa, AA
def print_args(args):
for k, v in zip(args.keys(), args.values()):
print("{0}: {1}".format(k,v))
class NonZeroClipper(object):
def __call__(self, module):
if hasattr(module, 'weight'):
w = module.weight.data
w.clamp_(1e-6, 1)