Để sắp xếp các phần tử tensor trong PyTorch, ta dùng phương thức torch.sort(). Phương thức này trả về hai tensor. Tensor đầu tiên chứa giá trị đã sắp xếp, tensor thứ hai chứa chỉ mục của các phần tử trong tensor gốc. Có thể tính tensor 2D theo hàng (row-wise) và cột (column-wise).
Các bước
Nhập thư viện torch. Đảm bảo đã cài.
Tạo tensor PyTorch và in ra.
Để sắp xếp, tính torch.sort(input, dim). Gán cho biến v. input là tensor đầu vào, dim là chiều sắp xếp. Sắp xếp theo hàng: dim=1; theo cột: dim=0.
Tensor giá trị sắp xếp truy cập bằng v[0], tensor chỉ mục bằng v[1].
In tensor giá trị sắp xếp và tensor chỉ mục.
Ví dụ 1
Sắp xếp tensor 1D.
import torch
T = torch.Tensor([2.334, 4.433, -4.33, -0.433, 5, 4.443])
print("Original Tensor:\n", T)
v = torch.sort(T)
print("Tensor with sorted value:\n", v[0])
print("Indices of sorted value:\n", v[1])
Kết quả
Original Tensor: tensor([ 2.3340, 4.4330, -4.3300, -0.4330, 5.0000, 4.4430]) Tensor with sorted value: tensor([-4.3300, -0.4330, 2.3340, 4.4330, 4.4430, 5.0000]) Indices of sorted value: tensor([2, 3, 0, 1, 5, 4])
Ví dụ 2
Sắp xếp tensor 2D.
import torch
T = torch.Tensor([[2, 3, -32],
[43, 4, -53],
[4, 37, -4],
[3, -75, 34]])
print("Original Tensor:\n", T)
v = torch.sort(T)
print("Tensor with sorted value:\n", v[0])
print("Indices of sorted value:\n", v[1])
print("Sort tensor Column-wise")
v = torch.sort(T, 0)
print("Tensor with sorted value:\n", v[0])
print("Indices of sorted value:\n", v[1])
print("Sort tensor Row-wise")
v = torch.sort(T, 1)
print("Tensor with sorted value:\n", v[0])
print("Indices of sorted value:\n", v[1])
Kết quả
Original Tensor:
tensor([[ 2., 3., -32.],
[ 43., 4., -53.],
[ 4., 37., -4.],
[ 3., -75., 34.]])
Tensor with sorted value:
tensor([[-32., 2., 3.],
[-53., 4., 43.],
[ -4., 4., 37.],
[-75., 3., 34.]])
Indices of sorted value:
tensor([[2, 0, 1],
[2, 1, 0],
[2, 0, 1],
[1, 0, 2]])
Sort tensor Column-wise
Tensor with sorted value:
tensor([[ 2., -75., -53.],
[ 3., 3., -32.],
[ 4., 4., -4.],
[ 43., 37., 34.]])
Indices of sorted value:
tensor([[0, 3, 1],
[3, 0, 0],
[2, 1, 2],
[1, 2, 3]])
Sort tensor Row-wise
Tensor with sorted value:
tensor([[-32., 2., 3.],
[-53., 4., 43.],
[ -4., 4., 37.],
[-75., 3., 34.]])
Indices of sorted value:
tensor([[2, 0, 1],
[2, 1, 0],
[2, 0, 1],
[1, 0, 2]])