flatten

paddle. flatten ( x, start_axis=0, stop_axis=- 1, name=None ) [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)
Parameters
  • x (Tensor) – A tensor of number of dimensions >= axis. A tensor with data type float16, float32, float64, int8, int32, int64, uint8.

  • start_axis (int) – the start axis to flatten

  • stop_axis (int) – the stop axis to flatten

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to 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)