paddle.nn.Flatten

paddle.nn.Flatten(start_axis=1, stop_axis=- 1)

作用:
它实现将一个连续维度的Tensor展平成一维Tensor。
参数:
start_axis (int,可选) - 展开的起始维度,默认值为1。
stop_axis (int,可选) - 展开的结束维度,默认值为-1。

比如说一个张量:[5, 2, 3, 4],是个四维张量,如果start_axis 按默认值1的话,所对应的就是‘2’所在的维度,stop_axis按默认值-1(复数就是从后向前索引)的话对应的就是‘4’所在的维度。paddle.nn.Flatten(start_axis=1, stop_axis=- 1)就会将这两个维度之间都展平成一维。也就是[5,234]
示例:

import paddle
import numpy as np

inp_np = np.ones([5, 2, 3, 4]).astype('float32')
inp_np = paddle.to_tensor(inp_np)
flatten = paddle.nn.Flatten(start_axis=1, stop_axis=2)
flatten_res = flatten(inp_np)
print(flatten_res )

在这里插入图片描述

源码:

def flatten_(x, start_axis=0, stop_axis=-1, name=None):
    """
    Inplace version of ``flatten`` API, the output Tensor will be inplaced with input ``x``.
    Please refer to :ref:`api_tensor_flatten`.
    """
    if not (isinstance(x, Variable)):
        raise ValueError("The input x should be a Tensor")

    x_dim = len(x.shape)
    if not (isinstance(start_axis, int)) or (
            start_axis > x_dim - 1) or start_axis < -x_dim:
        raise ValueError(
            "The start_axis should be a int, and in range [-rank(x), rank(x))")
    if not (isinstance(stop_axis, int)) or (
            stop_axis > x_dim - 1) or stop_axis < -x_dim:
        raise ValueError(
            "The stop_axis should be a int, and in range [-rank(x), rank(x))")
    if start_axis < 0:
        start_axis = start_axis + x_dim
    if stop_axis < 0:
        stop_axis = stop_axis + x_dim
    if start_axis > stop_axis:
        raise ValueError("The stop_axis should be larger than stat_axis")

    dy_out, _ = _C_ops.flatten_contiguous_range_(x, 'start_axis', start_axis,
                                                 'stop_axis', stop_axis)
    return dy_out