-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
244 lines (197 loc) · 7.13 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.gridspec as gsp
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
from torch.autograd import Variable
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as tf
class GaussianNoise(nn.Module):
def __init__(self, batch_size, input_shape=(1, 28, 28), std=0.05):
super(GaussianNoise, self).__init__()
self.shape = (batch_size,) + input_shape
self.noise = Variable(torch.zeros(self.shape).cuda())
self.std = std
def forward(self, x):
self.noise.data.normal_(0, std=self.std)
return x + self.noise
def prepare_mnist():
# normalize data
m = (0.1307,)
st = (0.3081,)
normalize = tf.Normalize(m, st)
# load train data
train_dataset = datasets.MNIST(
root='../data',
train=True,
transform=tf.Compose([tf.ToTensor(), normalize]),
download=True)
# load test data
test_dataset = datasets.MNIST(
root='../data',
train=False,
transform=tf.Compose([tf.ToTensor(), normalize]))
return train_dataset, test_dataset
def prepare_emnist():
# Details in https://www.simonwenkel.com/2019/07/16/exploring-EMNIST.html
# normalize data
m = (0.1307,)
st = (0.3081,)
normalize = tf.Normalize(m, st)
# load train data
train_dataset = datasets.EMNIST(
root='../data', split="digits",
train=True,
transform=tf.Compose([tf.ToTensor(), normalize]),
download=True)
# load test data
test_dataset = datasets.EMNIST(
root='../data', split="digits",
train=False,
transform=tf.Compose([tf.ToTensor(), normalize]))
return train_dataset, test_dataset
def prepare_fashion_mnist():
m = (0.5,)
st = (0.5,)
normalize = tf.Normalize(m, st)
train_set = datasets.FashionMNIST("../data", download=True, transform=
tf.Compose([tf.ToTensor(),normalize]))
test_set = datasets.FashionMNIST("../data", download=True, train=False, transform=
tf.Compose([tf.ToTensor(),normalize]))
return train_set, test_set
def prepare_kmnist():
m = (0.5,)
st = (0.5,)
normalize = tf.Normalize(m, st)
train_set = datasets.KMNIST("../data", download=True, transform=
tf.Compose([tf.ToTensor(),normalize]))
test_set = datasets.KMNIST("../data", download=True, train=False, transform=
tf.Compose([tf.ToTensor(),normalize]))
return train_set, test_set
def ramp_up(epoch, max_epochs, max_val, mult):
if epoch == 0:
return 0.
elif epoch >= max_epochs:
return max_val
return max_val * np.exp(mult * (1. - float(epoch) / max_epochs) ** 2)
def weight_schedule(epoch, max_epochs, max_val, mult, n_labeled, n_samples):
max_val = max_val * (float(n_labeled) / n_samples)
return ramp_up(epoch, max_epochs, max_val, mult)
def calc_metrics(model, loader):
correct = 0
total = 0
for i, (samples, labels) in enumerate(loader):
samples = Variable(samples.cuda(), volatile=True)
labels = Variable(labels.cuda())
outputs = model(samples)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels.data.view_as(predicted)).sum()
acc = 100 * float(correct) / total
return acc
def savetime():
return datetime.now().strftime('%Y_%m_%d_%H%M%S')
def save_losses(losses, sup_losses, unsup_losses, fname, labels=None):
plt.style.use('ggplot')
# color palette from Randy Olson
colors = [
(31, 119, 180),
(174, 199, 232),
(255, 127, 14),
(255, 187, 120),
(44, 160, 44),
(152, 223, 138),
(214, 39, 40),
(255, 152, 150),
(148, 103, 189),
(197, 176, 213),
(140, 86, 75),
(196, 156, 148),
(227, 119, 194),
(247, 182, 210),
(127, 127, 127),
(199, 199, 199),
(188, 189, 34),
(219, 219, 141),
(23, 190, 207),
(158, 218, 229)]
colors = [(float(c[0]) / 255, float(c[1]) / 255, float(c[2]) / 255) for c in colors]
fig, axs = plt.subplots(3, 1, figsize=(12, 18))
for i in range(3):
axs[i].tick_params(axis="both", which="both", bottom="off", top="off",
labelbottom="on", left="off", right="off", labelleft="on")
for i in range(len(losses)):
axs[0].plot(losses[i], color=colors[i])
axs[1].plot(sup_losses[i], color=colors[i])
axs[2].plot(unsup_losses[i], color=colors[i])
axs[0].set_title('Overall loss', fontsize=14)
axs[1].set_title('Supervised loss', fontsize=14)
axs[2].set_title('Unsupervised loss', fontsize=14)
if labels is not None:
axs[0].legend(labels)
axs[1].legend(labels)
axs[2].legend(labels)
plt.savefig(fname)
def save_exp(time, losses, sup_losses, unsup_losses,
accs, accs_best, idxs, **kwargs):
def save_txt(fname, accs, **kwargs):
with open(fname, 'w') as fp:
fp.write('GLOB VARS\n')
fp.write('n_exp = {}\n'.format(kwargs['n_exp']))
fp.write('k = {}\n'.format(kwargs['k']))
fp.write('MODEL VARS\n')
fp.write('drop = {}\n'.format(kwargs['drop']))
fp.write('std = {}\n'.format(kwargs['std']))
fp.write('fm1 = {}\n'.format(kwargs['fm1']))
fp.write('fm2 = {}\n'.format(kwargs['fm2']))
fp.write('w_norm = {}\n'.format(kwargs['w_norm']))
fp.write('OPTIM VARS\n')
fp.write('lr = {}\n'.format(kwargs['lr']))
fp.write('beta2 = {}\n'.format(kwargs['beta2']))
fp.write('num_epochs = {}\n'.format(kwargs['num_epochs']))
fp.write('batch_size = {}\n'.format(kwargs['batch_size']))
fp.write('TEMP ENSEMBLING VARS\n')
fp.write('alpha = {}\n'.format(kwargs['alpha']))
fp.write('data_norm = {}\n'.format(kwargs['data_norm']))
fp.write('divide_by_bs = {}\n'.format(kwargs['divide_by_bs']))
fp.write('\nRESULTS\n')
fp.write('best accuracy : {}\n'.format(np.max(accs)))
fp.write('accuracy : {} (+/- {})\n'.format(np.mean(accs), np.std(accs)))
fp.write('accs : {}\n'.format(accs))
labels = ['seed_' + str(sd) for sd in kwargs['seeds']]
if not os.path.isdir('exps'):
os.mkdir('exps')
time_dir = os.path.join('exps', time)
if not os.path.isdir(time_dir):
os.mkdir(time_dir)
fname_bst = os.path.join('exps', time, 'training_best.png')
fname_fig = os.path.join('exps', time, 'training_all.png')
fname_smr = os.path.join('exps', time, 'summary.txt')
fname_sd = os.path.join('exps', time, 'seed_samples')
best = np.argmax(accs_best)
save_losses([losses[best]], [sup_losses[best]], [unsup_losses[best]], fname_bst)
save_losses(losses, sup_losses, unsup_losses, fname_fig, labels=labels)
for seed, indices in zip(kwargs['seeds'], idxs):
save_seed_samples(fname_sd + '_seed' + str(seed) + '.png', indices)
save_txt(fname_smr, accs_best, **kwargs)
def save_seed_samples(fname, indices):
#Modify this across different datasets
train_dataset, test_dataset = prepare_kmnist()
imgs = train_dataset.train_data[indices.numpy().astype(int)]
plt.style.use('classic')
fig = plt.figure(figsize=(15, 60))
gs = gsp.GridSpec(20, 5, width_ratios=[1, 1, 1, 1, 1],
wspace=0.0, hspace=0.0)
for ll in range(100):
i = ll // 5
j = ll % 5
img = imgs[ll].numpy()
ax = plt.subplot(gs[i, j])
ax.tick_params(axis="both", which="both", bottom="off", top="off",
labelbottom="off", left="off", right="off", labelleft="off")
ax.imshow(img)
plt.savefig(fname)