mindspore.ops.pad

mindspore.ops.pad(input_x, padding, mode='constant', value=None)[source]

Pads the input tensor according to the padding.

Parameters
  • input_x (Tensor) – Tensor of shape \((N, *)\), where \(*\) means, any number of additional dimensions.

  • padding (Union[tuple[int], list[int], Tensor]) –

    Filling position of pad. \(\left\lfloor\frac{\text{len(padding)}}{2}\right\rfloor\) dimensions of input_x will be padded.

    Example: to pad only the last dimension of the input tensor, then padding has the form \((\text{padding_left}, \text{padding_right})\);

    Example: to pad the last 2 dimensions of the input tensor, then use \((\text{padding_left}, \text{padding_right}\), \(\text{padding_top}, \text{padding_bottom})\);

    Example: to pad the last 3 dimensions, use \((\text{padding_left}, \text{padding_right}\), \(\text{padding_top}, \text{padding_bottom}\), \(\text{padding_front}, \text{padding_back})\) and so on.

  • mode (str, optional) –

    Pad filling mode, “constant”, “reflect” or “replicate”. Default: “constant”.

    For “constant” mode, please refer to mindspore.nn.ConstantPad1d as an example to understand this filling pattern and extend the padding pattern to n dimensions.

    For “reflect” mode, please refer to mindspore.nn.ReflectionPad1d as an example and extend the padding pattern to n dimensions.

    For “replicate” mode, please refer to mindspore.nn.ReplicationPad1d as an example and extend the padding pattern to n dimensions.

  • value (Union[int, float, None], optional) – Valid only in “constant” mode. Set the padding value in “constant” mode. If the value is None, 0 is used as the default padding value.

Returns

Tensor, the tensor after padding.

Raises
  • TypeError – If paddings is not an int of tuple or int of list.

  • TypeError – If input_x is not a Tensor.

  • ValueError – If padding.size is not equal to 2 * len(input_x).

  • ValueError – If mode is not “constant” and value not None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> import mindspore.ops as ops
>>> import numpy as np
>>> x = ms.Tensor(np.arange(1 * 2 * 2 * 2).reshape((1, 2, 2, 2)), dtype=ms.float64)
>>> output = ops.pad(x, [1, 0, 0, 1], mode='constant', value=6.0)
>>> print(x)
[[[[6. 0. 1.]
   [6. 2. 3.]
   [6. 6. 6.]]
  [[6. 4. 5.]
   [6. 6. 7.]
   [6. 6. 6.]]]]
>>> output1 = ops.pad(x, (1, 0, 0, 1), mode='reflect')
>>> print(output1)
[[[[1. 0. 1.]
   [3. 2. 3.]
   [1. 0. 1.]]
  [[5. 4. 5.]
   [7. 6. 7.]
   [5. 4. 5.]]]]
>>> output2 = ops.pad(x, (1, 1, 2, 1), mode='replicate')
[[[[0. 0. 1. 1.]
   [0. 0. 1. 1.]
   [0. 0. 1. 1.]
   [2. 2. 3. 3.]
   [2. 2. 3. 3.]]
  [[4. 4. 5. 5.]
   [4. 4. 5. 5.]
   [4. 4. 5. 5.]
   [6. 6. 7. 7.]
   [6. 6. 7. 7.]]]]