forked from oreilly-japan/deep-learning-from-scratch-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions_conv.py
492 lines (403 loc) · 15.8 KB
/
functions_conv.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import numpy as np
from dezero import cuda
from dezero.core import Function, as_variable
from dezero.utils import pair, get_conv_outsize, get_deconv_outsize
from dezero.functions import linear, broadcast_to
# =============================================================================
# [simple version] conv2d_simple / pooling_simple
# =============================================================================
def conv2d_simple(x, W, b=None, stride=1, pad=0):
x, W = as_variable(x), as_variable(W)
Weight = W
N, C, H, W = x.shape
OC, C, KH, KW = Weight.shape
SH, SW = pair(stride)
PH, PW = pair(pad)
OH = get_conv_outsize(H, KH, SH, PH)
OW = get_conv_outsize(W, KW, SW, PW)
col = im2col(x, (KH, KW), stride, pad, to_matrix=True)
Weight = Weight.reshape(OC, -1).transpose()
t = linear(col, Weight, b)
y = t.reshape(N, OH, OW, OC).transpose(0, 3, 1, 2)
return y
def pooling_simple(x, kernel_size, stride=1, pad=0):
x = as_variable(x)
N, C, H, W = x.shape
KH, KW = pair(kernel_size)
PH, PW = pair(pad)
SH, SW = pair(stride)
OH = get_conv_outsize(H, KH, SH, PH)
OW = get_conv_outsize(W, KW, SW, PW)
col = im2col(x, kernel_size, stride, pad, to_matrix=True)
col = col.reshape(-1, KH * KW)
y = col.max(axis=1)
y = y.reshape(N, OH, OW, C).transpose(0, 3, 1, 2)
return y
# =============================================================================
# conv2d / deconv2d
# =============================================================================
class Conv2d(Function):
def __init__(self, stride=1, pad=0):
super().__init__()
self.stride = pair(stride)
self.pad = pair(pad)
def forward(self, x, W, b):
xp = cuda.get_array_module(x)
KH, KW = W.shape[2:]
col = im2col_array(x, (KH, KW), self.stride, self.pad, to_matrix=False)
y = xp.tensordot(col, W, ((1, 2, 3), (1, 2, 3)))
if b is not None:
y += b
y = xp.rollaxis(y, 3, 1)
# y = np.transpose(y, (0, 3, 1, 2))
return y
def backward(self, gy):
x, W, b = self.inputs
# ==== gx ====
gx = deconv2d(gy, W, b=None, stride=self.stride, pad=self.pad,
outsize=(x.shape[2], x.shape[3]))
# ==== gW ====
gW = Conv2DGradW(self)(x, gy)
# ==== gb ====
gb = None
if b.data is not None:
gb = gy.sum(axis=(0, 2, 3))
return gx, gW, gb
def conv2d(x, W, b=None, stride=1, pad=0):
return Conv2d(stride, pad)(x, W, b)
class Deconv2d(Function):
def __init__(self, stride=1, pad=0, outsize=None):
super().__init__()
self.stride = pair(stride)
self.pad = pair(pad)
self.outsize = outsize
def forward(self, x, W, b):
xp = cuda.get_array_module(x)
Weight = W
SH, SW = self.stride
PH, PW = self.pad
C, OC, KH, KW = Weight.shape
N, C, H, W = x.shape
if self.outsize is None:
out_h = get_deconv_outsize(H, KH, SH, PH)
out_w = get_deconv_outsize(W, KW, SW, PW)
else:
out_h, out_w = pair(self.outsize)
img_shape = (N, OC, out_h, out_w)
gcol = xp.tensordot(Weight, x, (0, 1))
gcol = xp.rollaxis(gcol, 3)
y = col2im_array(gcol, img_shape, (KH, KW), self.stride, self.pad,
to_matrix=False)
# b, k, h, w
if b is not None:
self.no_bias = True
y += b.reshape((1, b.size, 1, 1))
return y
def backward(self, gy):
x, W, b = self.inputs
# ==== gx ====
gx = conv2d(gy, W, b=None, stride=self.stride, pad=self.pad)
# ==== gW ====
f = Conv2DGradW(self)
gW = f(gy, x)
# ==== gb ====
gb = None
if b.data is not None:
gb = gy.sum(axis=(0, 2, 3))
return gx, gW, gb
def deconv2d(x, W, b=None, stride=1, pad=0, outsize=None):
return Deconv2d(stride, pad, outsize)(x, W, b)
class Conv2DGradW(Function):
def __init__(self, conv2d):
W = conv2d.inputs[1]
kh, kw = W.shape[2:]
self.kernel_size = (kh, kw)
self.stride = conv2d.stride
self.pad = conv2d.pad
def forward(self, x, gy):
xp = cuda.get_array_module(x)
col = im2col_array(x, self.kernel_size, self.stride, self.pad,
to_matrix=False)
gW = xp.tensordot(gy, col, ((0, 2, 3), (0, 4, 5)))
return gW
def backward(self, gys):
x, gy = self.inputs
gW, = self.outputs
xh, xw = x.shape[2:]
gx = deconv2d(gy, gW, stride=self.stride, pad=self.pad,
outsize=(xh, xw))
ggy = conv2d(x, gW, stride=self.stride, pad=self.pad)
return gx, ggy
# =============================================================================
# pooling(max-pooling) / average_pooling
# =============================================================================
class Pooling(Function):
def __init__(self, kernel_size, stride=1, pad=0):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
def forward(self, x):
col = im2col_array(x, self.kernel_size, self.stride, self.pad,
to_matrix=False)
N, C, KH, KW, OH, OW = col.shape
col = col.reshape(N, C, KH * KW, OH, OW)
self.indexes = col.argmax(axis=2)
y = col.max(axis=2)
return y
def backward(self, gy):
return Pooling2DGrad(self)(gy)
class Pooling2DGrad(Function):
def __init__(self, mpool2d):
self.mpool2d = mpool2d
self.kernel_size = mpool2d.kernel_size
self.stride = mpool2d.stride
self.pad = mpool2d.pad
self.input_shape = mpool2d.inputs[0].shape
self.dtype = mpool2d.inputs[0].dtype
self.indexes = mpool2d.indexes
def forward(self, gy):
xp = cuda.get_array_module(gy)
N, C, OH, OW = gy.shape
N, C, H, W = self.input_shape
KH, KW = pair(self.kernel_size)
gcol = xp.zeros((N * C * OH * OW * KH * KW), dtype=self.dtype)
indexes = (self.indexes.ravel()
+ xp.arange(0, self.indexes.size * KH * KW, KH * KW))
gcol[indexes] = gy.ravel()
gcol = gcol.reshape(N, C, OH, OW, KH, KW)
gcol = xp.swapaxes(gcol, 2, 4)
gcol = xp.swapaxes(gcol, 3, 5)
gx = col2im_array(gcol, (N, C, H, W), self.kernel_size, self.stride,
self.pad, to_matrix=False)
return gx
def backward(self, ggx):
f = Pooling2DWithIndexes(self.mpool2d)
return f(ggx)
class Pooling2DWithIndexes(Function):
def __init__(self, mpool2d):
self.kernel_size = mpool2d.kernel_size
self.stride = mpool2d.stride
self.pad = mpool2d.pad
self.input_shpae = mpool2d.inputs[0].shape
self.dtype = mpool2d.inputs[0].dtype
self.indexes = mpool2d.indexes
def forward(self, x):
col = im2col_array(x, self.kernel_size, self.stride, self.pad,
to_matrix=False)
N, C, KH, KW, OH, OW = col.shape
col = col.reshape(N, C, KH * KW, OH, OW)
col = col.transpose(0, 1, 3, 4, 2).reshape(-1, KH * KW)
indexes = self.indexes.ravel()
col = col[np.arange(len(indexes)), indexes]
return col.reshape(N, C, OH, OW)
def pooling(x, kernel_size, stride=1, pad=0):
return Pooling(kernel_size, stride, pad)(x)
class AveragePooling(Function):
def __init__(self, kernel_size, stride=1, pad=0):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
self.input_shape = None
def forward(self, x):
self.input_shape = x.shape
col = im2col_array(x, self.kernel_size, self.stride, self.pad,
to_matrix=False)
y = col.mean(axis=(2, 3))
return y
def backward(self, gy):
# TODO(Koki): This is simple implementation
N, C, OH, OW = gy.shape
KW, KH = pair(self.kernel_size)
gy /= (KW*KH)
gcol = broadcast_to(gy.reshape(-1), (KH, KW, N*C*OH*OW))
gcol = gcol.reshape(KH, KW, N, C, OH, OW).transpose(2, 3, 0, 1, 4, 5)
gx = col2im(gcol, self.input_shape, self.kernel_size, self.stride,
self.pad, to_matrix=False)
return gx
def average_pooling(x, kernel_size, stride=1, pad=0):
return AveragePooling(kernel_size, stride, pad)(x)
# =============================================================================
# im2col / col2im
# =============================================================================
class Im2col(Function):
def __init__(self, kernel_size, stride, pad, to_matrix):
super().__init__()
self.input_shape = None
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
self.to_matrix = to_matrix
def forward(self, x):
self.input_shape = x.shape
y = im2col_array(x, self.kernel_size, self.stride, self.pad,
self.to_matrix)
return y
def backward(self, gy):
gx = col2im(gy, self.input_shape, self.kernel_size, self.stride,
self.pad, self.to_matrix)
return gx
def im2col(x, kernel_size, stride=1, pad=0, to_matrix=True):
"""Extract patches from an image based on the filter.
Args:
x (`dezero.Variable` or `ndarray`): Input variable of shape
`(N, C, H, W)`
kernel_size (int or (int, int)): Size of kernel.
stride (int or (int, int)): Stride of kernel.
pad (int or (int, int)): Spatial padding width for input arrays.
to_matrix (bool): If True the `col` will be reshaped to 2d array whose
shape is `(N*OH*OW, C*KH*KW)`
Returns:
`dezero.Variable`: Output variable. If the `to_matrix` is False, the
output shape is `(N, C, KH, KW, OH, OW)`, otherwise
`(N*OH*OW, C*KH*KW)`.
Notation:
- `N` is the batch size.
- `C` is the number of the input channels.
- `H` and `W` are the height and width of the input image, respectively.
- `KH` and `KW` are the height and width of the filters, respectively.
- `SH` and `SW` are the strides of the filter.
- `PH` and `PW` are the spatial padding sizes.
- `OH` and `OW` are the the height and width of the output, respectively.
"""
y = Im2col(kernel_size, stride, pad, to_matrix)(x)
return y
class Col2im(Function):
def __init__(self, input_shape, kernel_size, stride, pad, to_matrix):
super().__init__()
self.input_shape = input_shape
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
self.to_matrix = to_matrix
def forward(self, x):
y = col2im_array(x, self.input_shape, self.kernel_size, self.stride,
self.pad, self.to_matrix)
return y
def backward(self, gy):
gx = im2col(gy, self.kernel_size, self.stride, self.pad,
self.to_matrix)
return gx
def col2im(x, input_shape, kernel_size, stride=1, pad=0, to_matrix=True):
return Col2im(input_shape, kernel_size, stride, pad, to_matrix)(x)
# =============================================================================
# numpy im2col
# =============================================================================
def im2col_array(img, kernel_size, stride, pad, to_matrix=True):
N, C, H, W = img.shape
KH, KW = pair(kernel_size)
SH, SW = pair(stride)
PH, PW = pair(pad)
OH = get_conv_outsize(H, KH, SH, PH)
OW = get_conv_outsize(W, KW, SW, PW)
xp = cuda.get_array_module(img)
if xp != np:
col = _im2col_gpu(img, kernel_size, stride, pad)
else:
img = np.pad(img,
((0, 0), (0, 0), (PH, PH + SH - 1), (PW, PW + SW - 1)),
mode='constant', constant_values=(0,))
col = np.ndarray((N, C, KH, KW, OH, OW), dtype=img.dtype)
for j in range(KH):
j_lim = j + SH * OH
for i in range(KW):
i_lim = i + SW * OW
col[:, :, j, i, :, :] = img[:, :, j:j_lim:SH, i:i_lim:SW]
if to_matrix:
col = col.transpose((0, 4, 5, 1, 2, 3)).reshape((N * OH * OW, -1))
return col
def col2im_array(col, img_shape, kernel_size, stride, pad, to_matrix=True):
N, C, H, W = img_shape
KH, KW = pair(kernel_size)
SH, SW = pair(stride)
PH, PW = pair(pad)
OH = get_conv_outsize(H, KH, SH, PH)
OW = get_conv_outsize(W, KW, SW, PW)
if to_matrix:
col = col.reshape(N, OH, OW, C, KH, KW).transpose(0, 3, 4, 5, 1, 2)
xp = cuda.get_array_module(col)
if xp != np:
img = _col2im_gpu(col, SH, SW, PH, PW, H, W)
return img
else:
img = np.zeros((N, C, H + 2 * PH + SH - 1, W + 2 * PW + SW - 1),
dtype=col.dtype)
for j in range(KH):
j_lim = j + SH * OH
for i in range(KW):
i_lim = i + SW * OW
img[:, :, j:j_lim:SH, i:i_lim:SW] += col[:, :, j, i, :, :]
return img[:, :, PH:H + PH, PW:W + PW]
def _im2col_gpu(img, kernel_size, stride, pad):
"""im2col function for GPU.
This code is ported from Chainer:
https://github.com/chainer/chainer/blob/v6.4.0/chainer/utils/conv.py
"""
n, c, h, w = img.shape
kh, kw = pair(kernel_size)
sy, sx = pair(stride)
ph, pw = pair(pad)
out_h = get_conv_outsize(h, kh, sy, ph)
out_w = get_conv_outsize(w, kw, sx, pw)
dy, dx = 1, 1
col = cuda.cupy.empty((n, c, kh, kw, out_h, out_w), dtype=img.dtype)
cuda.cupy.ElementwiseKernel(
'raw T img, int32 h, int32 w, int32 out_h, int32 out_w,'
'int32 kh, int32 kw, int32 sy, int32 sx, int32 ph, int32 pw,'
'int32 dy, int32 dx',
'T col',
'''
int c0 = i / (kh * kw * out_h * out_w);
int ky = i / (kw * out_h * out_w) % kh;
int kx = i / (out_h * out_w) % kw;
int out_y = i / out_w % out_h;
int out_x = i % out_w;
int in_y = ky * dy + out_y * sy - ph;
int in_x = kx * dx + out_x * sx - pw;
if (in_y >= 0 && in_y < h && in_x >= 0 && in_x < w) {
col = img[in_x + w * (in_y + h * c0)];
} else {
col = 0;
}
''',
'im2col')(img.reduced_view(),
h, w, out_h, out_w, kh, kw, sy, sx, ph, pw, dy, dx, col)
return col
def _col2im_gpu(col, sy, sx, ph, pw, h, w):
"""col2im function for GPU.
This code is ported from Chainer:
https://github.com/chainer/chainer/blob/v6.4.0/chainer/utils/conv.py
"""
n, c, kh, kw, out_h, out_w = col.shape
dx, dy = 1, 1
img = cuda.cupy.empty((n, c, h, w), dtype=col.dtype)
cuda.cupy.ElementwiseKernel(
'raw T col, int32 h, int32 w, int32 out_h, int32 out_w,'
'int32 kh, int32 kw, int32 sy, int32 sx, int32 ph, int32 pw,'
'int32 dx, int32 dy',
'T img',
'''
int c0 = i / (h * w);
int y = i / w % h;
int x = i % w;
T val = 0;
for (int ky = 0; ky < kh; ++ky) {
int out_y = (y + ph - ky * dy);
if (0 > out_y || out_y >= out_h * sy) continue;
if (out_y % sy != 0) continue;
out_y /= sy;
for (int kx = 0; kx < kw; ++kx) {
int out_x = (x + pw - kx * dx);
if (0 > out_x || out_x >= out_w * sx) continue;
if (out_x % sx != 0) continue;
out_x /= sx;
int k = out_y + out_h * (kx + kw * (ky + kh * c0));
val = val + col[out_x + out_w * k];
}
}
img = val;
''',
'col2im')(col.reduced_view(),
h, w, out_h, out_w, kh, kw, sy, sx, ph, pw, dx, dy, img)
return img