PyTorch 텐서는 numpy.ndarray와 매우 유사한 자료 구조입니다. 두 자료 구조의 핵심적인 차이점은 텐서가 GPU를 활용해 수치 연산을 가속화할 수 있다는 점입니다. numpy.ndarray를 PyTorch 텐서로 변환할 때는 torch.from_numpy() 함수를 사용하고, 반대로 텐서를 numpy.ndarray로 변환할 때는 .numpy() 메서드를 사용합니다.
변환 절차
필요한 라이브러리를 임포트합니다. 이 예제에서는 torch와 numpy 라이브러리가 필요합니다.
numpy.ndarray 또는 PyTorch 텐서를 생성합니다.
torch.from_numpy() 함수를 사용해 numpy.ndarray를 PyTorch 텐서로 변환하거나, .numpy() 메서드를 사용해 PyTorch 텐서를 numpy.ndarray로 변환합니다.
마지막으로 변환된 텐서 또는 numpy.ndarray를 출력해 결과를 확인합니다.
예제 1: NumPy 배열을 PyTorch 텐서로 변환하기
다음 파이썬 프로그램은 numpy.ndarray를 PyTorch 텐서로 변환하는 과정을 보여줍니다.
# import the libraries
import torch
import numpy as np
# Create a numpy.ndarray "a"
a = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("a:\n", a)
print("Type of a :\n", type(a))
# Convert the numpy.ndarray to tensor
t = torch.from_numpy(a)
print("t:\n", t)
print("Type after conversion:\n", type(t))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
a:
[[1 2 3]
[2 1 3]
[2 3 5]
[5 6 4]]
Type of a :
<class 'numpy.ndarray'>
t:
tensor([[1, 2, 3],
[2, 1, 3],
[2, 3, 5],
[5, 6, 4]], dtype=torch.int32)
Type after conversion:
<class 'torch.Tensor'>
예제 2: PyTorch 텐서를 NumPy 배열로 변환하기
다음 파이썬 프로그램은 PyTorch 텐서를 numpy.ndarray로 변환하는 과정을 보여줍니다.
# import the libraries
import torch
import numpy
# Create a tensor "t"
t = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("t:\n", t)
print("Type of t :\n", type(t))
# Convert the tensor to numpy.ndarray
a = t.numpy()
print("a:\n", a)
print("Type after conversion:\n", type(a))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
t:
tensor([[1., 2., 3.],
[2., 1., 3.],
[2., 3., 5.],
[5., 6., 4.]])
Type of t :
<class 'torch.Tensor'>
a:
[[1. 2. 3.]
[2. 1. 3.]
[2. 3. 5.]
[5. 6. 4.]]
Type after conversion:
<class 'numpy.ndarray'>
참고 사항
torch.from_numpy()로 생성된 텐서는 원본 NumPy 배열과 메모리를 공유합니다. 따라서 한쪽의 값을 변경하면 다른 쪽에도 변경 사항이 반영됩니다. 반면 GPU에서 연산 중인 CUDA 텐서를 CPU의 NumPy 배열로 변환하려면 먼저 .cpu() 메서드를 호출한 뒤 .numpy()를 적용해야 한다는 점도 기억해 두면 좋습니다.