본문 바로가기
AI Here and There

[PyTorch] - Tensor Manipulation

by RiverWon 2024. 4. 11.

pytorch 2일차입니다.

CNN, LSTM stock forecasting 코드 따라치는데 텐서 조작이 너무 어려워서 trensor manipulation 깔작대어 보려구요

 

Tensor Indexing

import torch

x = torch.tensor([[1,2],[3,4]])

print(x)
print(x[0])
print(x[:,0]

#output
#tensor([[1,2],
#		[3,4]])

#tensor([1,2])

#tensor([1,3])

 

view

argument로는 바뀔 shape이 주어짐. tensor값은 동일하지만, shape이 바뀐 새로운 tensor return

x = torch.randn(3,5)

a = x.view(15)
b = x.view(5, -1)

print(x.size())
print(a.size())
print(b.size())

#torch.size([3,5])
#torch.size([15])
#torch.size([5,3]) <- -1로 적어두면 나머지 차원 자동계산

 

item

tensor.item() 은 텐서에 스칼라 값이 존재할 경우 가져옴

해당 텐서에 2개 잉상의 스칼라값 -> item()으로 못가져옴

ValueError : only one element tensors can be converted to Python scalars

torch.randn(1)
print(x)
print(x.item())

#tensor([-0,4899])
#-0,4899999999990

 

 

 

 

 

 

[

 

 

 

 

squeeze, unsqueeze등 추가 예정

 

 

 

 

 

]

 

 

 

 

Torch ↔ Numpy

torch의 tensor ↔  numpy의 array

 

numpy() : torch → numpy

from_numpy() : numpy → torch

 

tensor가 CPU상에 존재하면 Numpy 배열은 메모리공간을 공유함 → tensor가 변하면 배열 값도 변함(반대도 동일)

a = torch.ones(7)
b = a.numpy()
print(a)
print(b)

#output
#tensor([1., 1., 1., 1., 1., 1., 1])
# [1. 1. 1. 1. 1. 1. 1.]

a.add(1)
print(a)
print(b)

#output
#tesor([2., 2., 2., 2., 2., 2., 2])
#[2. 2. 2. 2. 2. 2. 2.]

.numpy()를 이용해 tensor a를 numpy의 array로 변환

여기서 a 바꾸면 b도 바뀜!!

 

import numpy as np

a = np.ones(7)
b = torch.from_numpy(a)
np.add(a, 1, out=a)

print(a)
print(b)

#output
#[2. 2. 2. 2. 2. 2. 2.]
#tensor([2., 2., 2., 2., 2., 2., 2.]), dtype=torch,float64

.from_numpy()를 이용해 array → tensor

마찬가지로 메모리 공유하기 때문에 하나 바뀌면 다른 것도 바뀜

*out=a : 계산 결과를 a에 저장해

 

 

reference : https://cansweep.tistory.com/381