Take columns of a 2D matrix and rearrange them into the blocks/windows of a 4D image volume. Notes ----- A NumPy reimagining of MATLAB's ``col2im`` 'sliding' function. Code extended from Andrej Karpathy's ``im2col.py``. Parameters ---------- X_col : :py:class:
(X_col, X_shape, W_shape, pad, stride, dilation=0)
| 544 | |
| 545 | |
| 546 | def col2im(X_col, X_shape, W_shape, pad, stride, dilation=0): |
| 547 | """ |
| 548 | Take columns of a 2D matrix and rearrange them into the blocks/windows of |
| 549 | a 4D image volume. |
| 550 | |
| 551 | Notes |
| 552 | ----- |
| 553 | A NumPy reimagining of MATLAB's ``col2im`` 'sliding' function. |
| 554 | |
| 555 | Code extended from Andrej Karpathy's ``im2col.py``. |
| 556 | |
| 557 | Parameters |
| 558 | ---------- |
| 559 | X_col : :py:class:`ndarray <numpy.ndarray>` of shape `(Q, Z)` |
| 560 | The columnized version of `X` (assumed to include padding) |
| 561 | X_shape : 4-tuple containing `(n_ex, in_rows, in_cols, in_ch)` |
| 562 | The original dimensions of `X` (not including padding) |
| 563 | W_shape: 4-tuple containing `(kernel_rows, kernel_cols, in_ch, out_ch)` |
| 564 | The dimensions of the weights in the present convolutional layer |
| 565 | pad : 4-tuple of `(left, right, up, down)` |
| 566 | Number of zero-padding rows/cols to add to `X` |
| 567 | stride : int |
| 568 | The stride of each convolution kernel |
| 569 | dilation : int |
| 570 | Number of pixels inserted between kernel elements. Default is 0. |
| 571 | |
| 572 | Returns |
| 573 | ------- |
| 574 | img : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_ch)` |
| 575 | The reshaped `X_col` input matrix |
| 576 | """ |
| 577 | if not (isinstance(pad, tuple) and len(pad) == 4): |
| 578 | raise TypeError("pad must be a 4-tuple, but got: {}".format(pad)) |
| 579 | |
| 580 | s, d = stride, dilation |
| 581 | pr1, pr2, pc1, pc2 = pad |
| 582 | fr, fc, n_in, n_out = W_shape |
| 583 | n_ex, in_rows, in_cols, n_in = X_shape |
| 584 | |
| 585 | X_pad = np.zeros((n_ex, n_in, in_rows + pr1 + pr2, in_cols + pc1 + pc2)) |
| 586 | k, i, j = _im2col_indices((n_ex, n_in, in_rows, in_cols), fr, fc, pad, s, d) |
| 587 | |
| 588 | X_col_reshaped = X_col.reshape(n_in * fr * fc, -1, n_ex) |
| 589 | X_col_reshaped = X_col_reshaped.transpose(2, 0, 1) |
| 590 | |
| 591 | np.add.at(X_pad, (slice(None), k, i, j), X_col_reshaped) |
| 592 | |
| 593 | pr2 = None if pr2 == 0 else -pr2 |
| 594 | pc2 = None if pc2 == 0 else -pc2 |
| 595 | return X_pad[:, :, pr1:pr2, pc1:pc2] |
| 596 | |
| 597 | |
| 598 | ####################################################################### |
no test coverage detected