Convolution operator in NHWC layout. Parameters ---------- a_np : numpy.ndarray 4-D with shape [batch, in_height, in_width, in_channel] w_np : numpy.ndarray 4-D with shape [filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of two
(a_np, w_np, stride, padding)
| 24 | |
| 25 | |
| 26 | def _conv2d_nhwc_python(a_np, w_np, stride, padding): |
| 27 | """Convolution operator in NHWC layout. |
| 28 | |
| 29 | Parameters |
| 30 | ---------- |
| 31 | a_np : numpy.ndarray |
| 32 | 4-D with shape [batch, in_height, in_width, in_channel] |
| 33 | |
| 34 | w_np : numpy.ndarray |
| 35 | 4-D with shape [filter_height, filter_width, in_channel, num_filter] |
| 36 | |
| 37 | stride : int or a list/tuple of two ints |
| 38 | Stride size, or [stride_height, stride_width] |
| 39 | |
| 40 | padding : int or str or a list/tuple of two ints |
| 41 | Padding size, or ['VALID', 'SAME'], or [pad_height, pad_width] |
| 42 | |
| 43 | Returns |
| 44 | ------- |
| 45 | b_np : np.ndarray |
| 46 | 4-D with shape [batch, out_height, out_width, out_channel] |
| 47 | """ |
| 48 | batch, in_height, in_width, in_channel = a_np.shape |
| 49 | kernel_h, kernel_w, _, num_filter = w_np.shape |
| 50 | if isinstance(stride, int): |
| 51 | stride_h = stride_w = stride |
| 52 | else: |
| 53 | stride_h, stride_w = stride |
| 54 | |
| 55 | pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w)) |
| 56 | pad_h = pad_top + pad_bottom |
| 57 | pad_w = pad_left + pad_right |
| 58 | |
| 59 | # compute the output shape |
| 60 | out_channel = num_filter |
| 61 | out_height = (in_height - kernel_h + pad_h) // stride_h + 1 |
| 62 | out_width = (in_width - kernel_w + pad_w) // stride_w + 1 |
| 63 | # change the layout from NHWC to NCHW |
| 64 | at = a_np.transpose((0, 3, 1, 2)) |
| 65 | wt = w_np.transpose((3, 2, 0, 1)) |
| 66 | bt = np.zeros((batch, out_channel, out_height, out_width)) |
| 67 | # computation |
| 68 | for n in range(batch): |
| 69 | for f in range(out_channel): |
| 70 | for c in range(in_channel): |
| 71 | if pad_h > 0 or pad_w > 0: |
| 72 | apad = np.zeros((in_height + pad_h, in_width + pad_w)) |
| 73 | apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = at[n, c] |
| 74 | else: |
| 75 | apad = at[n, c] |
| 76 | out = scipy.signal.convolve2d(apad, np.rot90(np.rot90(wt[f, c])), mode="valid") |
| 77 | bt[n, f] += out[::stride_h, ::stride_w] |
| 78 | return bt.transpose((0, 2, 3, 1)) |
| 79 | |
| 80 | |
| 81 | def conv2d_nhwc_python(a_np, w_np, stride, padding, groups=1): |
no test coverage detected
searching dependent graphs…