[Pytorch] torch tensor에서 numpy, numpy에서 torch tensor 변경/전환 방법

torch tensor -> numpy

import torch

torch_value = torch.randn(1,3)
print(torch_value)
# tensor([[0.5519, 0.1323, 0.1297]])

numpy_value = torch_value.numpy()
print(numpy_value)
# [[0.551902, 0.132319, 0.129740]]

 

numpy -> torch tensor

import torch
import numpy as np

numpy_value = np.ones(4)
print(numpy_value)
# [1. 1. 1. 1.]

torch_value = torch.from_numpy(numpy_value)
print(torch_value)
# tensor([1., 1., 1., 1.])