flatten

paddle. flatten ( x, start_axis=0, stop_axis=- 1, name=None ) [source]

Flatten op

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

Note that 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, 1000 * 100, 2)

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 dimentions >= axis. A tensor with data type float32, float64, int8, int32, int64.

  • start_axis (int) – the start axis to flatten

  • stop_axis (int) – the stop axis to flatten

  • name (str, Optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

A tensor with the contents of the input tensor, with input

axes flattened by indicated start axis and end axis. A Tensor with data type same as input x.

Return type

Tensor

Raises
  • ValueError – If x is not a Tensor.

  • ValueError – If start_axis or stop_axis is illegal.

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)
# out shape is [2, 12, 4]

# out shares data with img in dygraph mode
img[0, 0, 0, 0] = -1
print(out[0, 0, 0]) # [-1]