使用张量举个例子使用permute
时间: 2023-07-11 07:17:52 浏览: 46
在PyTorch中,我们可以使用permute函数对张量进行维度的重新排列。以下是一个使用permute函数的例子:
```python
import torch
tensor = torch.randn(2, 3, 4)
permuted = tensor.permute(1, 2, 0)
print("Original Tensor: ", tensor)
print("Permuted Tensor: ", permuted)
```
输出结果:
```
Original Tensor: tensor([[[-0.2749, -0.2436, -0.6301, 0.4698],
[ 0.0152, -0.2920, -0.3647, -0.5039],
[-0.5639, 1.1067, 0.4374, 0.2545]],
[[-0.2158, -0.8168, 0.5624, 1.1334],
[-0.8238, 1.0769, -0.3303, -1.0293],
[-0.5513, -0.1478, 0.3212, -0.9629]]])
Permuted Tensor: tensor([[[-0.2749, -0.2158],
[ 0.0152, -0.8238],
[-0.5639, -0.5513]],
[[-0.2436, -0.8168],
[-0.2920, 1.0769],
[ 1.1067, -0.1478]],
[[-0.6301, 0.5624],
[-0.3647, -0.3303],
[ 0.4374, 0.3212]],
[[ 0.4698, 1.1334],
[-0.5039, -1.0293],
[ 0.2545, -0.9629]]])
```
在这个例子中,我们首先创建了一个2x3x4的随机张量。然后,我们使用permute函数将这个张量的维度重新排列为3x4x2。permute函数接受一个整数序列作为参数,这个序列定义了新张量的维度顺序。在这个例子中,我们将原始张量的第1个维度变成了新张量的第2个维度,将原始张量的第2个维度变成了新张量的第3个维度,将原始张量的第3个维度变成了新张量的第1个维度。