flatten

paddle. flatten ( x: Tensor, start_axis: int = 0, stop_axis: int = -1, name: str | None = None ) Tensor [source]

Flattens a contiguous range of axes in a tensor according to start_axis and stop_axis.

Note

The output Tensor will share data with origin Tensor and doesn’t have a Tensor copy in dygraph mode. If you want to use the Tensor copy version, please use Tensor.clone like flatten_clone_x = x.flatten().clone().

For Example:

Case 1:

  Given
    X.shape = (3, 100, 100, 4)

  and
    start_axis = 1
    end_axis = 2

  We get:
    Out.shape = (3, 100 * 100, 4)

Case 2:

  Given
    X.shape = (3, 100, 100, 4)

  and
    start_axis = 0
    stop_axis = -1

  We get:
    Out.shape = (3 * 100 * 100 * 4)

Note

Alias Support: The parameter name input can be used as an alias for x, the parameter name start_dim can be used as an alias for start_axis , and the parameter name end_dim can be used as an alias for stop_axis. For example, flatten(input=tensor_x, start_dim=0, end_dim=-1) is equivalent to flatten(x=tensor_x, start_axis=0, stop_axis=-1).

Parameters
  • x (Tensor) –

    A tensor of number of dimensions >= axis. A tensor with data type float16, float32,

    float64, int8, int32, int64, uint8.

    System Message: WARNING/2 (/usr/local/lib/python3.10/site-packages/paddle/tensor/manipulation.py:docstring of paddle.tensor.manipulation.flatten, line 38)

    Definition list ends without a blank line; unexpected unindent.

    alias: input.

  • start_axis (int) – the start axis to flatten alias: start_dim.

  • stop_axis (int) – the stop axis to flatten alias: end_dim.

  • name (str|None, optional) – Name for the operation (optional, default is None). For more information, please refer to api_guide_Name.

Returns

Tensor, A tensor with the contents of the input tensor, whose input axes are flattened by indicated start_axis and end_axis, and data type is the same as input x.

Examples

>>> import paddle

>>> image_shape=(2, 3, 4, 4)

>>> x = paddle.arange(end=image_shape[0] * image_shape[1] * image_shape[2] * image_shape[3])
>>> img = paddle.reshape(x, image_shape)

>>> out = paddle.flatten(img, start_axis=1, stop_axis=2)
>>> print(out.shape)
[2, 12, 4]

>>> # out shares data with img in dygraph mode
>>> img[0, 0, 0, 0] = -1
>>> print(out[0, 0, 0])
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
-1)