如何调整PyTorch的张量大小?
要调整PyTorch张量的大小,我们使用 .view() 方法。我们可以增加或减少张量的维度,但必须确保在调整大小前后张量中的元素总数相同。
步骤
-
导入所需的库。在所有以下Python示例中,所需的Python库是 torch 。确保您已经安装它。
-
创建一个PyTorch张量并打印它。
-
使用 .view() 调整上面创建的张量的大小,并将值分配给变量。 .view() 不会调整原始张量的大小,它只会提供具有新大小的视图,顾名思义。
-
最后,在调整大小后打印张量。
示例1
# Python program to resize a tensor in PyTorch
# Import the library
import torch
# Create a tensor
T = torch.Tensor([1, 2, 3, 4, 5, 6])
print(T)
# Resize T to 2x3
x = T.view(2,3)
print("Tensor after resize:\n",x)
# Other way to resize T to 2x3
x = T.view(-1,3)
print("Tensor after resize:\n",x)
# Other way resize T to 2x3
x = T.view(2,-1)
print("Tensor after resize:\n",x)
输出
当运行上面的Python 3代码时,它将产生以下输出
tensor([1., 2., 3., 4., 5., 6.])
Tensor after resize:
tensor([[1., 2., 3.],
[4., 5., 6.]])
Tensor after resize:
tensor([[1., 2., 3.],
[4., 5., 6.]])
Tensor after resize:
tensor([[1., 2., 3.],
[4., 5., 6.]])
示例2
# Import the library
import torch
# Create a tensor shape 4x3
T = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print(T)
# Resize T to 3x4
x = T.view(-1,4)
print("Tensor after resize:\n",x)
# Other way to esize T to 3x4
x = T.view(3,-1)
print("Tensor after resize:\n",x)
# Resize T to 2x6
x = T.view(2,-1)
print("Tensor after resize:\n",x)
输出
当运行上面的Python 3代码时,它将产生以下输出
tensor([[1., 2., 3.],
[2., 1., 3.],
[2., 3., 5.],
[5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2.],
[1., 3., 2., 3.],
[5., 5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2.],
[1., 3., 2., 3.],
[5., 5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2., 1., 3.],
[2., 3., 5., 5., 6., 4.]])