飞桨学习——paddle.nn.Flatten

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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值