-
Notifications
You must be signed in to change notification settings - Fork 23
/
utils.py
173 lines (138 loc) · 4.85 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
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
import random
import torch
import os
import time
import numpy as np
import pprint as pprint
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import matplotlib
_utils_pp = pprint.PrettyPrinter()
def pprint(x):
_utils_pp.pprint(x)
def set_seed(seed):
if seed == 0:
print(' random seed')
torch.backends.cudnn.benchmark = True
else:
print('manual seed:', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def set_gpu(args):
gpu_list = [int(x) for x in args.gpu.split(',')]
print('use gpu:', gpu_list)
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
return gpu_list.__len__()
def ensure_path(path):
if os.path.exists(path):
pass
else:
print('create folder:', path)
os.makedirs(path)
class Averager():
def __init__(self):
self.n = 0
self.v = 0
def add(self, x):
self.v = (self.v * self.n + x) / (self.n + 1)
self.n += 1
def item(self):
return self.v
class Timer():
def __init__(self):
self.o = time.time()
def measure(self, p=1):
x = (time.time() - self.o) / p
x = int(x)
if x >= 3600:
return '{:.1f}h'.format(x / 3600)
if x >= 60:
return '{}m'.format(round(x / 60))
return '{}s'.format(x)
def count_acc(logits, label):
pred = torch.argmax(logits, dim=1)
if torch.cuda.is_available():
return (pred == label).type(torch.cuda.FloatTensor).mean().item()
else:
return (pred == label).type(torch.FloatTensor).mean().item()
def count_acc_topk(x,y,k=5):
_,maxk = torch.topk(x,k,dim=-1)
total = y.size(0)
test_labels = y.view(-1,1)
#top1=(test_labels == maxk[:,0:1]).sum().item()
topk=(test_labels == maxk).sum().item()
return float(topk/total)
def count_acc_taskIL(logits, label,args):
basenum=args.base_class
incrementnum=(args.num_classes-args.base_class)/args.way
for i in range(len(label)):
currentlabel=label[i]
if currentlabel<basenum:
logits[i,basenum:]=-1e9
else:
space=int((currentlabel-basenum)/args.way)
low=basenum+space*args.way
high=low+args.way
logits[i,:low]=-1e9
logits[i,high:]=-1e9
pred = torch.argmax(logits, dim=1)
if torch.cuda.is_available():
return (pred == label).type(torch.cuda.FloatTensor).mean().item()
else:
return (pred == label).type(torch.FloatTensor).mean().item()
def confmatrix(logits,label,filename):
font={'family':'FreeSerif','size':18}
matplotlib.rc('font',**font)
matplotlib.rcParams.update({'font.family':'FreeSerif','font.size':18})
plt.rcParams["font.family"]="FreeSerif"
pred = torch.argmax(logits, dim=1)
cm=confusion_matrix(label, pred,normalize='true')
#print(cm)
clss=len(cm)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(cm,cmap=plt.cm.jet)
if clss<=100:
plt.yticks([0,19,39,59,79,99],[0,20,40,60,80,100],fontsize=16)
plt.xticks([0,19,39,59,79,99],[0,20,40,60,80,100],fontsize=16)
elif clss<=200:
plt.yticks([0,39,79,119,159,199],[0,40,80,120,160,200],fontsize=16)
plt.xticks([0,39,79,119,159,199],[0,40,80,120,160,200],fontsize=16)
else:
plt.yticks([0,199,399,599,799,999],[0,200,400,600,800,1000],fontsize=16)
plt.xticks([0,199,399,599,799,999],[0,200,400,600,800,1000],fontsize=16)
plt.xlabel('Predicted Label',fontsize=20)
plt.ylabel('True Label',fontsize=20)
plt.tight_layout()
plt.savefig(filename+'.pdf',bbox_inches='tight')
plt.close()
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(cm,cmap=plt.cm.jet)
cbar = plt.colorbar(cax) # This line includes the color bar
cbar.ax.tick_params(labelsize=16)
if clss<=100:
plt.yticks([0,19,39,59,79,99],[0,20,40,60,80,100],fontsize=16)
plt.xticks([0,19,39,59,79,99],[0,20,40,60,80,100],fontsize=16)
elif clss<=200:
plt.yticks([0,39,79,119,159,199],[0,40,80,120,160,200],fontsize=16)
plt.xticks([0,39,79,119,159,199],[0,40,80,120,160,200],fontsize=16)
else:
plt.yticks([0,199,399,599,799,999],[0,200,400,600,800,1000],fontsize=16)
plt.xticks([0,199,399,599,799,999],[0,200,400,600,800,1000],fontsize=16)
plt.xlabel('Predicted Label',fontsize=20)
plt.ylabel('True Label',fontsize=20)
plt.tight_layout()
plt.savefig(filename+'_cbar.pdf',bbox_inches='tight')
plt.close()
return cm
def save_list_to_txt(name, input_list):
f = open(name, mode='w')
for item in input_list:
f.write(str(item) + '\n')
f.close()