Tensor PyTorch tương tự numpy.ndarray, khác ở chỗ tensor tận dụng GPU để tăng tốc tính toán. Chuyển ndarray → tensor dùng torch.from_numpy(). Chuyển tensor → ndarray dùng phương thức .numpy().
Các bước
Nhập torch và numpy.
Tạo ndarray hoặc tensor.
Chuyển đổi: torch.from_numpy() hoặc .numpy().
In kết quả chuyển đổi.
Ví dụ 1: NumPy ndarray → PyTorch Tensor
import torch
import numpy as np
# Tạo numpy.ndarray
a = np.array([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]])
print("a:\n", a)
print("Kiểu của a:\n", type(a))
# Chuyển sang tensor
t = torch.from_numpy(a)
print("t:\n", t)
print("Kiểu sau chuyển đổi:\n", type(t))
Kết quả
a: [[1 2 3] [2 1 3] [2 3 5] [5 6 4]] Type of a :t: tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]], dtype=torch.int32) Type after conversion:
Ví dụ 2: PyTorch Tensor → NumPy ndarray
import torch
import numpy
# Tạo tensor
t = torch.Tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]])
print("t:\n", t)
print("Kiểu của t:\n", type(t))
# Chuyển sang ndarray
a = t.numpy()
print("a:\n", a)
print("Kiểu sau chuyển đổi:\n", type(a))
Kết quả
t: tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]]) Type of t :a: [[1. 2. 3.] [2. 1. 3.] [2. 3. 5.] [5. 6. 4.]] Type after conversion: