如何在 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)输出结果
当您运行上述Python3代码时,它将产生以下输出
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)输出结果
当您运行上述Python3代码时,它将产生以下输出
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.]])