How to use the reshape function in PyTorch?

In PyTorch, there are two ways to change the shape of a tensor using the reshape function.

  1. display()
import torch

# 创建一个大小为(2, 3)的张量
x = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 使用view方法将张量的形状改变为(3, 2)
y = x.view(3, 2)

print(y)

Output: Result / Output / Outcome / Output result

tensor([[1, 2],
        [3, 4],
        [5, 6]])
  1. Reconfigure the shape.
import torch

# 创建一个大小为(2, 3)的张量
x = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 使用reshape方法将张量的形状改变为(3, 2)
y = x.reshape(3, 2)

print(y)

Output: produce or generate

tensor([[1, 2],
        [3, 4],
        [5, 6]])

Both methods can be used to change the shape of a tensor, but the .view() method may sometimes return a view that shares storage, while the .reshape() method always returns a new tensor that does not share storage.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds