Hello Computer Vision

[pytorch] tensor 관련 여러 메소드들 정리 본문

딥러닝/파이토치

[pytorch] tensor 관련 여러 메소드들 정리

지웅쓰 2024. 3. 1. 16:27

텐서 데이터에 적용되는 여러 메소드들이 있는데 이를 한번 정리해보려고 한다.

 

tensor.data

x = torch.tensor([1,2])
print(x)
print(x.data)

y = torch.rand(3,5)
print(y.data)
tensor([1, 2])
tensor([1, 2])
tensor([[0.7150, 0.9495, 0.3474, 0.3829, 0.2828],
        [0.4531, 0.4677, 0.0863, 0.6763, 0.2480],
        [0.6295, 0.0573, 0.5454, 0.4892, 0.5464]])
x, y = next(iter(loader))
print(x.shape)
print(x[1].data)
torch.Size([32, 3, 32, 32])
tensor([[[0.6039, 0.4941, 0.4118,  ..., 0.3569, 0.3412, 0.3098],
         [0.5490, 0.5686, 0.4902,  ..., 0.3765, 0.3020, 0.2784],
         [0.5490, 0.5451, 0.4510,  ..., 0.3098, 0.2667, 0.2627],
         ...,

이렇게 텐서 데이터에 data 메소드들을 적용하면 그대로 텐서가 나오는 것을 확인할 수 있다.

 

tensor.detach

이전 gradient를 다 지우고 새로운 tensor를 만드는 것이다.

https://keepgoingrunner.tistory.com/219

 

torch detach 실험해보기

Pytorch를 사용하다보면은 detach가 쓰이는 코드를 종종만난다. 사실 이 전까지는 gradient에 대해서 별 생각이 없었다. 그런데 요즘 실험 및 논문을 읽으면서 gradient에 대한 이야기가 많이 나와 조금

keepgoingrunner.tistory.com

추가적으로 원본 data와 detach로 만들어진 data는 storage를 공유한다.

x = torch.rand(2,3, requires_grad =True)
y = x.detach()
print(x[1][1].data_ptr())
print(y[1][1].data_ptr())
print(x)
print(y)

 

99403511736272
99403511736272
tensor([[0.4386, 0.6072, 0.5399],
        [0.7399, 0.3638, 0.5041]], requires_grad=True)
tensor([[0.4386, 0.6072, 0.5399],
        [0.7399, 0.3638, 0.5041]])

 

 

tensor.clone

 
x = torch.rand((3, 4), requires_grad = True)
y = x.clone()
print(y)
print(y.requires_grad)
print(x.data_ptr())
print(y.data_ptr())
tensor([[0.7328, 0.8097, 0.1753, 0.0954],
        [0.4242, 0.6517, 0.2417, 0.3720],
        [0.0833, 0.9532, 0.6680, 0.0964]], grad_fn=<CloneBackward0>)
True
99403466361152
99403511012288

input 값에 대해 deepcopy 하는 것을 알 수 있다. 이전에 쓴 글에서 copy deepcopy 차이에서 2차원 리스트의 경우 같은 주소를 참조한다고 했었는데 tensor.clone을 사용하면 새로운 객체를 생성한다.

https://keepgoingrunner.tistory.com/222

 

파이썬 copy, deepcopy 쓰는 이유 및 사용해보기

모델을 훈련 전에 복사할 필요성이 생겼는데 이번 기회에 copy, deepcopy를 비교해보려고 한다. 1. 다른 변수로 할당 우선 코딩 초보인 나에게 해당 변수 값을 다른 변수에 넘겨주면은 되지 않나 생

keepgoingrunner.tistory.com

 

tensor.item

주어진 변수에서 텐서값만 가져온다

a =torch.tensor([1])
print(a.item())
1

 

 

tensor.cpu

현재 변수를 cpu memory로 옮긴다. 만약 cpu에 원래 있었다면 그대로 값 return한다.

a = torch.tensor([1]).to('cuda:0')
print(a.device)
print(a.data_ptr())
a = a.cpu()
print(a.device)
print(a.data_ptr())

c = a.cpu()
print(c.data_ptr())
cuda:0
138350545600512
cpu
99403525111424
99403525111424

 

tensor.numpy

텐서를 넘파이로 변경해준다. 같은 주소를 공유하기 때문에 원본 값이 변하면 같이 변한다.

a = torch.rand(2,3)
b = a.numpy()
print(b)
a.add_(1)
print(b)
[[0.905745   0.32042634 0.44706213]
 [0.5428807  0.03247464 0.7207662 ]]
[[1.905745  1.3204263 1.4470621]
 [1.5428808 1.0324746 1.7207662]]

텐서를 넘파이로 변환 이유는 시각화나 다른 연산적인 부분에서 더 빠르다고한다. 단점으로는 병렬처리가 안된다고 한다. 즉 딥러닝 모델에서 여러대의 gpu를 사용해 텐서를 다루는 것 제외하고는 numpy 배열이 더 사용하고 다루기 쉽다고 보면될 거 같다.

'딥러닝 > 파이토치' 카테고리의 다른 글

CIFAR100-C, CIFAR100 비교  (0) 2024.02.29
[pytorch] 데이터셋 합치기  (0) 2024.02.17
[pytorch] 행렬 계산  (0) 2024.02.17
[pytorch] 기본적인 tensor 조작해보기  (0) 2024.02.06
[pytorch] Nan, inf알아보기  (0) 2024.02.06