Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách thay đổi kích thước (resize) tensor trong PyTorch

Để thay đổi kích thước tensor PyTorch, ta dùng phương thức .view(). Có thể tăng hoặc giảm số chiều, nhưng tổng số phần tử phải giữ nguyên trước và sau khi resize.

Các bước

  • Nhập thư viện torch.

  • Tạo tensor PyTorch và in ra.

  • Resize tensor bằng .view(), gán cho biến mới. .view() không resize tensor gốc, chỉ trả về view mới.

  • In tensor sau resize.

Ví dụ 1: Resize tensor 1D thành 2D

import torch

# Tạo tensor
T = torch.Tensor([1, 2, 3, 4, 5, 6])
print(T)

# Resize thành 2x3
x = T.view(2, 3)
print("Tensor sau resize:\n", x)

# Dùng -1 để tự động tính chiều còn lại
x = T.view(-1, 3)
print("Tensor sau resize:\n", x)

x = T.view(2, -1)
print("Tensor sau resize:\n", x)

Kết quả

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.]])

Ví dụ 2: Resize tensor 4x3 thành các hình dạng khác

import torch

# Tạo tensor 4x3
T = torch.Tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]])
print(T)

# Resize thành 3x4
x = T.view(-1, 4)
print("Tensor sau resize:\n", x)

x = T.view(3, -1)
print("Tensor sau resize:\n", x)

# Resize thành 2x6
x = T.view(2, -1)
print("Tensor sau resize:\n", x)

Kết quả

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.]])