深入浅出PaddlePaddle函数——paddle.transpose

该文详细介绍了PaddlePaddle库中的paddle.transpose函数,用于按照指定的perm对多维Tensor进行数据维度重排。函数接受输入Tensorx和排列顺序perm,返回重排后的Tensor。例如,将2DTensor的列转为行等。适用数据类型包括bool、float和int等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类目录:《深入浅出PaddlePaddle函数》总目录
相关文章:
· 深入浅出TensorFlow2函数——tf.transpose
· 深入浅出Pytorch函数——torch.t
· 深入浅出Pytorch函数——torch.transpose
· 深入浅出PaddlePaddle函数——paddle.transpose


根据 perm对输入的多维Tensor进行数据重排。返回多维Tensor的第 i i i维对应输入Tensor perm [ i ] \text{perm}[i] perm[i]维。

语法
paddle.transpose(x, perm, name=None)
参数
  • x:[Tensor] 输入的多维Tensor,可选的数据类型为 boolfloat16float32float64int32int64
  • perm:[list/tuple] perm的长度必须和x的维度相同,并依照perm中数据进行重排。
  • name:[可选, str] 具体用法请参见Name,一般无需设置,默认值为None
返回值

多维Tensor

实例

输入:

x = paddle.to_tensor([[2, 3, 4]])
paddle.transpose(x, perm=[1, 0])

输出:

Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
       [[2],
        [3],
        [4]])
函数实现
def transpose(x, perm, name=None):
    """
    Permute the data dimensions of `input` according to `perm`.
    The `i`-th dimension  of the returned tensor will correspond to the
    perm[i]-th dimension of `input`.
    Args:
        x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32.
        perm (list|tuple): Permute the input according to the data of perm.
        name (str): The name of this layer. It is optional.
    Returns:
        Tensor: A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64.
    For Example:
        .. code-block:: text
         x = [[[ 1  2  3  4] [ 5  6  7  8] [ 9 10 11 12]]
             [[13 14 15 16] [17 18 19 20] [21 22 23 24]]]
         shape(x) =  [2,3,4]
         # Example 1
         perm0 = [1,0,2]
         y_perm0 = [[[ 1  2  3  4] [13 14 15 16]]
                   [[ 5  6  7  8]  [17 18 19 20]]
                   [[ 9 10 11 12]  [21 22 23 24]]]
         shape(y_perm0) = [3,2,4]
         # Example 2
         perm1 = [2,1,0]
         y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]]
                   [[ 2 14] [ 6 18] [10 22]]
                   [[ 3 15]  [ 7 19]  [11 23]]
                   [[ 4 16]  [ 8 20]  [12 24]]]
         shape(y_perm1) = [4,3,2]
    Examples:
        .. code-block:: python
            import paddle
            x = paddle.randn([2, 3, 4])
            x_transposed = paddle.transpose(x, perm=[1, 0, 2])
            print(x_transposed.shape)
            # [3L, 2L, 4L]
    """
    if in_dygraph_mode():
        return _C_ops.transpose(x, perm)
    else:
        if _in_legacy_dygraph():
            out, _ = _legacy_C_ops.transpose2(x, 'axis', perm)
            return out

    check_variable_and_dtype(
        x,
        'x',
        [
            'bool',
            'float16',
            'float32',
            'float64',
            'int32',
            'int64',
            'complex64',
            'complex128',
        ],
        'transpose',
    )
    check_type(perm, 'perm', (list, tuple), 'transpose')
    if isinstance(perm, tuple):
        perm = list(perm)
    if len(perm) != len(x.shape):
        raise ValueError(
            "Input(perm) is the permutation of dimensions of Input(x), "
            "its length should be equal to dimensions of Input(x), "
            "but received dimension of Input(x) is %s, "
            "the length of Input(perm) is %s." % (len(x.shape), len(perm))
        )
    for idx, dim in enumerate(perm):
        if dim >= len(x.shape):
            raise ValueError(
                "Each element in Input(perm) should be less than Input(x)'s dimension, "
                "but %d-th element in Input(perm) is %d which exceeds Input(x)'s "
                "dimension %d." % (idx, perm[idx], len(x.shape))
            )

    helper = LayerHelper('transpose', **locals())
    out = helper.create_variable_for_type_inference(x.dtype)
    x_shape = helper.create_variable_for_type_inference(x.dtype)
    helper.append_op(
        type='transpose2',
        inputs={'X': [x]},
        outputs={'Out': [out], 'XShape': [x_shape]},
        attrs={'axis': perm},
    )
    return out
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值