pytorch中的transpose方法(函数)

本文详细解析了PyTorch中transpose方法的功能和使用,包括其如何交换张量的两个维度,以及与torch.transpose()函数的等效性。通过实例展示了参数的影响,强调了输出与输入共享内存的特性。

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

pytorch中的transpose方法的作用是交换矩阵的两个维度,transpose(dim0, dim1) → Tensor,其和torch.transpose()函数作用一样。
torch.transpose():

torch.transpose(input, dim0, dim1) → Tensor

Returns a tensor that is a transposed version of input. The given dimensions dim0 and dim1 are swapped.
The resulting out tensor shares it’s underlying storage with the input tensor, so changing the content of one would change the content of the other.
第二条是说输出和输入是共享一块内存的,所以两者同时改变。

Parameters
input (Tensor) – the input tensor.

dim0 (int) – the first dimension to be transposed

dim1 (int) – the second dimension to be transposed

例:

>>> x = torch.randn(2, 3)
>>> x
tensor([[ 1.0028, -0.9893,  0.5809],
        [-0.1669,  0.7299,  0.4942]])
>>> torch.transpose(x, 0, 1)
tensor([[ 1.0028, -0.1669],
        [-0.9893,  0.7299],
        [ 0.5809,  0.4942]])

需要注意的几点:
1、transpose中的两个维度参数的顺序是可以交换位置的,即transpose(x, 0, 1,) 和transpose(x, 1, 0)效果是相同的。如下:

>>> import torch
>>> x = torch.randn(2, 3)
>>> x
tensor([[-0.4343,  0.4643, -1.1345],
        [-0.3667, -1.9913,  1.3485]])
>>> torch.transpose(x, 1, 0)
tensor([[-0.4343, -0.3667],
        [ 0.4643, -1.9913],
        [-1.1345,  1.3485]])
>>> torch.transpose(x, 0, 1)
tensor([[-0.4343, -0.3667],
        [ 0.4643, -1.9913],
        [-1.1345,  1.3485]])

2、transpose.()中只有两个参数,而torch.transpose()函数中有三个参数。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值