-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxpool.py
More file actions
86 lines (63 loc) · 2.4 KB
/
Copy pathMaxpool.py
File metadata and controls
86 lines (63 loc) · 2.4 KB
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
import numpy as np
def max_pool_forward_naive(x, pool_param):
"""A naive implementation of the forward pass for a max-pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
No padding is necessary here, eg you can assume:
- (H - pool_height) % stride == 0
- (W - pool_width) % stride == 0
Returns a tuple of:
- out: Output data, of shape (N, C, H', W') where H' and W' are given by
H' = 1 + (H - pool_height) / stride
W' = 1 + (W - pool_width) / stride
- cache: (x, pool_param)
"""
N,C,H,W = x.shape
HH, WW = pool_param["pool_height"], pool_param["pool_width"]
stride = pool_param["stride"]
h_ = 1+(H-HH)//stride
w_ = 1+(W-WW)//stride
out = np.zeros((N,C,h_,w_))
for n in range(N):
for c in range(C):
for hi in range(h_):
for wi in range(w_):
vertical = stride*hi
v_end = vertical+HH
horizontal = stride*wi
h_end = horizontal+WW
x_slice = x[n,c,vertical:v_end,horizontal:h_end]
out[n,c,hi,wi] = np.max(x_slice)
cache = (x,pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""A naive implementation of the backward pass for a max-pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
dx = None
x, pool_param = cache
N,C,H,W = x.shape
HH, WW = pool_param["pool_height"], pool_param["pool_width"]
stride = pool_param["stride"]
h_, w_ = dout.shape[2], dout.shape[3]
dx = np.zeros(x.shape)
for n in range(N):
for c in range(C):
for hi in range(h_):
for wi in range(w_):
vertical = stride*hi
v_end = vertical+HH
horizontal = stride*wi
h_end = horizontal+WW
x_slice = x[n,c,vertical:v_end,horizontal:h_end]
mask = (x_slice==np.max(x_slice))
dx[n,c,vertical:v_end,horizontal:h_end] += dout[n,c,hi,wi] * mask
return dx