logo

torch.from_numpy()와 torch.tensor()의 차이점 📂머신러닝

torch.from_numpy()와 torch.tensor()의 차이점

설명

넘파이 배열을 토치 텐서로 바꾸는 방법은 torch.from_numpy()torch.tensor()를 사용하는 것이다. 우선 from_numpy()는 넘파이 배열과 메모리를 공유한다. 즉 복사하지 않기 때문에 넘파이 배열을 바꾸면 토치 텐서도 바뀌고, 그 반대도 마찬가지이다.

>>> import torch
>>> import numpy as np

# from_numpy()로 생성한 텐서와 넘파이 배열의 메모리 주소가 같음
>>> a = np.random.randn(6)
>>> hex(a.ctypes.data)
'0x1e1487700b0'
>>> b = torch.from_numpy(a)
>>> hex(b.data_ptr())
'0x1e1487700b0'

# a를 바꾸면 b로 바뀜
>>> a[0:3] = 0
>>> b
tensor([ 0.0000,  0.0000,  0.0000, -0.7667,  1.0462,  1.0083],
       dtype=torch.float64)

반면에 tensor()는 넘파이 배열을 복사하여 새로운 메모리에 할당한다. 넘파이 배열과 토치 텐서 각각의 값을 바꾸어도 서로 영향을 주지 않는다.

# tensor()로 생성한 텐서는 넘파이 배열과 주소가 다름
>>> a = np.random.randn(6)
>>> hex(a.ctypes.data)
'0x1e148770070'
>>> c = torch.tensor(a)
>>> hex(c.data_ptr())
'0x4ad40420480'

# a를 바꿔도 c가 바뀌지 않음
>>> a[0:3] = 0
>>> c
tensor([-0.2374,  1.5200, -0.5507, -2.3992,  1.2971, -0.6234],
       dtype=torch.float64)