-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
153 lines (122 loc) · 4.11 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
import os
import glob
import torch
import pandas as pd
import seaborn as sn
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from torch.optim.lr_scheduler import _LRScheduler
from sklearn.metrics import confusion_matrix
from PIL import Image
def set_lr(optimizer, lrs):
if(len(lrs) == 1):
for param in optimizer.param_groups:
param['lr'] = lrs[0]
else:
for i, param in enumerate(optimizer.param_groups):
param['lr'] = lrs[i]
def set_base_lr(optimizer, lrs):
if(len(lrs) == 1):
for param in optimizer.param_groups:
param['initial_lr'] = lrs[0]
else:
for i, param in enumerate(optimizer.param_groups):
param['initial_lr'] = lrs[i]
def get_lr(optimizer):
optim_param_groups = optimizer.param_groups
if(len(optim_param_groups) == 1):
return optim_param_groups[0]['lr']
else:
lrs = []
for param in optim_param_groups:
lrs.append(param['lr'])
return lrs
def get_children_groups(model_children, param_places):
cur_place = 0
children_groups = []
for param_place in param_places:
children_groups.append(model_children[cur_place:param_place])
cur_place = param_place
return children_groups
def get_params(children):
params_use_grad = []
for child in children:
for param in child.parameters():
if(param.requires_grad == True):
params_use_grad.append(param)
return params_use_grad
def get_optimizer(model, lrs, param_places):
model_children = list(model.children())
# only 1 learning rate
if(len(lrs) == 1):
# from the model's childrens, only get the parameters that use grad
param_use_grad = get_params(model_children)
# set an Adam optimizer with the params that use grad, and the lr
optimizer = optim.Adam(param_use_grad, lrs[0])
# multiple learning rates
else:
# from the param_places, get chunks of children from model_children
# children_groups is a list, and each item will be a list of children
children_groups = get_children_groups(model_children, param_places)
# from children_groups, get each of its children group's grad using params
# param_groups_use_grad is a list, and each item will be a list of params that use grad
param_groups_use_grad = []
for children_group in children_groups:
param_group_use_grad = get_params(children_group)
param_groups_use_grad.append(param_group_use_grad)
# zip param_groups_use_grad together with lrs
# in order to feed in the corresponding lr to a given param_group
param_groups_use_grad_with_lrs = zip(param_groups_use_grad, lrs)
optimizer = optim.Adam([{'params' : p, 'lr' : l}
for p, l in param_groups_use_grad_with_lrs])
return optimizer
def freeze_until(model, idx):
for i, child in enumerate(model.children()):
if(i <= idx):
for param in child.parameters():
param.requires_grad = False
else:
for param in child.parameters():
param.requires_grad = True
def histogram_sizes(img_dir, h_lim = None, w_lim = None):
hs, ws = [], []
for file in glob.iglob(os.path.join(img_dir, '**/*.*')):
try:
with Image.open(file) as im:
h, w = im.size
hs.append(h)
ws.append(w)
except:
print('Not an Image file')
if(h_lim is not None and w_lim is not None):
hs = [h for h in hs if h<h_lim]
ws = [w for w in ws if w<w_lim]
plt.figure('Height')
plt.hist(hs)
plt.figure('Width')
plt.hist(ws)
plt.show()
return hs, ws
def plot_confusion_matrix(model, dl, names, classes_count, device, figsize):
true_label = []
predicted_label = []
for batch in dl:
(images, labels) = batch
y_real = list(labels.data.cpu().numpy())
y_pred = list(torch.argmax(model(images.to(device)), dim=1).data.cpu().numpy())
true_label.extend(y_real)
predicted_label.extend(y_pred)
cm = confusion_matrix(true_label, predicted_label)
names_with_cnt = [str(name) + ' : ' + str(cnt) for name, cnt in zip(names, classes_count)]
df = pd.DataFrame(cm, index = names_with_cnt, columns = names_with_cnt)
plt.figure(figsize = figsize)
ax = plt.subplot(111)
sn.heatmap(df, annot = True, ax = ax, fmt='g')
plt.show()
def freeze_cur_bn(module):
classname = module.__class__.__name__
if(classname.find('BatchNorm') != -1):
module.eval()
def freeze_bn(model):
model.apply(freeze_cur_bn)