/
utils.py
283 lines (217 loc) · 7.71 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import logging
import zipfile
import gzip
import requests
import pickle
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import optim
# see as well: LambdaLR, StepLR, ReduceLROnPlateau, MultiStepLR, ExponentialLR
from torch.optim.lr_scheduler import CosineAnnealingLR
log = logging.getLogger(__name__)
class CustomDataLoader:
"""Preprocess batches in a dataloader."""
def __init__(self, dl, func):
self.dl, self.func = dl, func
def __len__(self):
return len(self.dl)
def __iter__(self):
for b in self.dl: yield (self.func(*b))
def fit(epochs, model, loss_func, opt, train_dl, valid_dl):
"""Train model for for a given number of epochs.
Parameters
-----------
epochs : :obj:`int`
Number fo epochs .
model : subclass of :obj:`nn.Module`
The model.
loss_func : :obj:`callable`
Loss function accepting two parameters: (pred, true)
opt : :obj:`torch.optim`
Optimization routine.
train_dl : :obj:`DataLoader`
Data loader for the training set.
valid_dl : :obj:`DataLoader`
Data loader for the validation set.
Note
-----
Using model.train() in train() and model.eval() in evaluate() changes the
behavior of some of the layers in the model. For example, Dropout and
BatchNorm should be turned off during evaluation and on during training.
"""
def train():
"""Train model for one epoch."""
model.train()
for batch_index, (xb, yb) in enumerate(train_dl):
loss = loss_func(model(xb), yb)
loss.backward()
opt.step()
opt.zero_grad()
def evaluate():
"""Evaluate model using the validation set."""
model.eval()
with torch.no_grad():
loss, n = 0, 0
for xb, yb in valid_dl:
n += len(xb)
loss += loss_func(model(xb), yb) * len(xb)
return loss/n
for epoch in range(epochs):
train()
log.info('epoch {}: {}'.format(epoch, evaluate()))
def count_parameters(model):
"""Return the number of parameters in a model.
https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/9
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def get_mnist(data_dir):
"""Get MNIST data.
Parameters
-----------
data_dir : :obj:`str`
Diretcory where to store the MNIST dataset.
Returns
--------
:obj:`tuple(torch.FloatTensor)`
Training and validation sets.
"""
url = 'http://deeplearning.net/data/mnist/'
filename = "mnist.pkl.gz"
path = Path(data_dir, filename)
if not path.exists():
r = requests.get(url + filename)
with open(path, 'wb') as h:
h.write(r.content)
with gzip.open(path, "rb") as h:
(x_train, y_train), (x_valid, y_valid), _ = pickle.load(h, encoding="latin-1")
return map(torch.tensor, (x_train, y_train, x_valid, y_valid))
def get_hymenoptera(data_dir):
"""Get HYMENOPTERA data.
I saw it in the following tutorial:
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
Parameters
-----------
data_dir : :obj:`str`
Diretcory where to store the dataset.
"""
url = 'https://download.pytorch.org/tutorial/'
filename = "hymenoptera_data.zip"
path = Path(data_dir, filename)
if not path.exists():
r = requests.get(url + filename)
with open(path, 'wb') as h:
h.write(r.content)
with zipfile.ZipFile(path, "r") as h:
h.extractall(data_dir)
def show_random_samples(batch, rows=5, cols=5, width=None, height=None, shuffle=True):
"""Show rows * cols random samples from a batch (without labels)."""
if width is None: width = 1.5*cols
if height is None: height = 1.5*rows
if rows * cols == 1:
axes = [plt.subplots(rows, cols, figsize=(width, height))[1]]
else:
axes = plt.subplots(rows, cols, figsize=(width, height))[1].flatten()
# by default batch_size=1 in DataLoader
for ax, x in zip(axes, DataLoader(TensorDataset(batch), shuffle=shuffle)):
ax.imshow(x[0].reshape(batch.shape[-2:]), cmap="gray")
ax.axis('off')
def rosenbrock(x):
"""Rosenbrock function."""
return (1-x[0])**2 + 100*(x[1] - x[0]**2)**2
def rosenbrock_contour(iterates=None, **kwargs):
"""Plot contours of the Rosenbrock function."""
n = 250
X, Y = np.meshgrid(np.linspace(-2,2,n),
np.linspace(-1,3,n))
fig = plt.figure(figsize=(14,8))
plt.contour(X, Y, rosenbrock([X,Y]), np.logspace(-0.5, 3.5, 20, base=10), cmap='gray')
if iterates is not None:
if isinstance(iterates, dict):
for key, value in iterates.items():
plt.plot(*(zip(*value['iterates'])),
ls='--', marker='o',
label='lr: {}'.format(key))
else:
plt.plot(*(zip(*iterates)), 'bo--')
plt.xlabel('x')
plt.ylabel('y')
if isinstance(iterates, dict): plt.legend()
if 'lr_history' in kwargs and kwargs['lr_history']:
plt.figure(figsize=(13,8))
plt.plot(kwargs['lr_history'])
plt.xlabel('iter')
plt.ylabel('learning rate')
plt.title('Cosine annealing')
plt.grid(True)
def gd(x0, lr=1e-3, mu=0.0, nesterov=False,
use_torch_opt=False, schedule_lr=False,
N=500, model=rosenbrock, **kwargs):
"""Gradient descent.
Parameters
-----------
x0 : :obj:`numpy.array`
Initial iterate.
lr : :obj:`float`
Learning rate.
mu : :obj:`float` [0, 1)
Momentum, see [1] (1-2).
nesterov : :obj:`bool`
If `True` use Nesterov accelerated gradient,
see [1] (3-4).
use_torch_opt : :obj:`bool`
If `True` use torch.optim.SGD. Note that there are
slight differences in the interpretation of the
`lr` and `mu` parameters (see the documentation of optim.SGD),
hence the results would be different from the manual version.
schedule_lr : :obj:`bool`
Use scheduler for the learning rate
(used only when use_torch_opt=`True`).
N : :obj:`int`
Number of iterations.
model : :obj:`callable`
The model.
References
-----------
[1] http://proceedings.mlr.press/v28/sutskever13.pdf
Returns
--------
:obj:`list(numpy.array)`
The iterates.
"""
if schedule_lr and not use_torch_opt: use_torch_opt = True
x = torch.tensor(x0, requires_grad=True)
lr_history = []
opt = None
if use_torch_opt:
opt = optim.SGD([x], lr=lr, momentum=mu, nesterov=nesterov)
if schedule_lr:
if 'T_max' in kwargs: T_max = kwargs['T_max']
else: T_max = N//5
if 'eta_min' in kwargs: eta_min = kwargs['eta_min']
else: eta_min = lr//3
scheduler = CosineAnnealingLR(opt, T_max, eta_min)
iterates = [x.clone().data.numpy()]
v = torch.zeros(len(x)).double()
for k in range(N):
if schedule_lr:
scheduler.step()
lr_history.append(opt.param_groups[0]['lr'])
if opt is None: # perform step manually
if nesterov: y = model(x + mu * v)
else: y = model(x)
y.backward()
with torch.no_grad():
v = mu * v - lr * x.grad
x += v
x.grad.zero_()
else:
y = model(x)
y.backward()
opt.step()
opt.zero_grad()
iterates.append(x.clone().data.numpy())
return {'iterates': iterates,
'lr_history': lr_history}