Pad2D¶
Description¶
This module implements the operation of two-dimensional padding.
The padding operation is applied along with convolution layers of neural networks: user-defined constants are added in a certain way (see mode
parameter) during the operation of padding around the perimeter of the data tensor, as a result, a layer of padding elements is formed around the original data.
This can be used, for example, so that the size of the maps would be preserved after the convolution.
There are several ways to set this operation; the following are implemented in the library:
- filling with constant value;
- filling with reflection of the last element.
Initializing¶
def __init__(self, pad, mode="constant", fillValue=None, name=None):
Parameters
parameter | Allowed types | Description | Default |
---|---|---|---|
pad | tuple | Tuple of binary flags showing the sides to which the operation should be applied | - |
mode | str | Fill mode. Possible values: "constant", "reflect" | "constant" |
fillValue | float | Fill value during "constant" mode | None |
name | str | Layer name | None |
Explanations
pad
- tuple has the configuration (top, bottom, left, right)
, where in the place of the side designation, the number of additional elements for the corresponding side is set. For example, (1, 0, 1, 0)
means that you need to add one row at the top and one column to the left.
Examples¶
Necessary imports.
import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Modules import Pad2D
Info
gpuarray
is required to properly place the tensor in the GPU
batchsize, maps, h, w = 1, 1, 5, 5
np.random.seed(1234)
data = gpuarray.to_gpu(np.random.randint(1, 10, (batchsize, maps, h, w)).astype(np.float32))
print(data)
[[[[4. 7. 6. 5. 9.]
[2. 8. 7. 9. 1.]
[6. 1. 7. 3. 1.]
[6. 3. 7. 4. 8.]
[1. 1. 4. 3. 4.]]]]
Let us add 1 additional layer at the top and to the left in the "constant" mode:
padmod = Pad2D(pad=(1, 0, 1, 0))
print(padmod(data))
[[[[0. 0. 0. 0. 0. 0.]
[0. 4. 7. 6. 5. 9.]
[0. 2. 8. 7. 9. 1.]
[0. 6. 1. 7. 3. 1.]
[0. 6. 3. 7. 4. 8.]
[0. 1. 1. 4. 3. 4.]]]]
Let us change the mode to "reflect" and add padding to the right and at the bottom:
padmod = Pad2D(pad=(0, 2, 0, 2), mode="reflect")
print(padmod(data))
[[[[4. 7. 6. 5. 9. 5. 6.]
[2. 8. 7. 9. 1. 9. 7.]
[6. 1. 7. 3. 1. 3. 7.]
[6. 3. 7. 4. 8. 4. 7.]
[1. 1. 4. 3. 4. 3. 4.]
[6. 3. 7. 4. 8. 4. 7.]
[6. 1. 7. 3. 1. 3. 7.]]]]