티스토리 뷰

MachineLearning

[ML] PyTorch 기본 함수들

SweetDev 2021. 10. 14. 11:27

텐서(tensor)는 배열(array)이나 행렬(matrix)과 매우 유사한 특수한 자료구조입니다. PyTorch에서는 텐서를 사용하여 모델의 입력과 출력뿐만 아니라 모델의 매개변수를 부호화(encode)합니다.

GPU나 다른 연산 가속을 위한 특수한 하드웨어에서 실행할 수 있다는 점을 제외하면, 텐서는 NumPy의 ndarray와 매우 유사합니다. 만약 ndarray에 익숙하다면 Tensor API를 바로 사용할 수 있습니다. 

list -> tensor

data = [[3,5], [10,5]]
x_data = torch.tensor(data)

numpy array -> tensor

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

 

tensor -> numpy array

x_data.numpy()

 

tensor data types

numpy와 동일하다. 

 

GPU에서 텐서 실행하기

tensorflow에서는 1.15 이후의 버전부터는 gpu에 자동으로 tensor들이 할당되지만 pytorch에서는 gpu에 해당 tensor를 올리라고 코드를 작성해주어야 합니다. 

# GPU가 존재하면 텐서를 이동합니다
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
use_cuda = True
device = torch.device("cuda" if use_cuda else "cpu")

이렇게 하고

tensor = tensor.to(device)

해줘도 된다. 

 

 

tensor handling - view

view : reshape과 동일하게 tensor의 shape을 변환

 

하지만 view를 쓸 때 꼭 주의해야 하는 점이 있는데, view는 contiguous하다는 것이다!

import torch
a = torch.zeros(3,2)
b = a.view(2,3)
a.fill_(1)

b는 a와 계속 종속관계를 가지고 있다. 

 

반면, reshpae은 별다른 종속관계를 만들지 않는다. 

import torch
a = torch.zeros(3,2)
b = a.t().reshape(6)
a.fill_(1)

 

 

tensor handling - squeeze, unsqueeze

squeeze : 차원의 개수가 1인 차원을 삭제

unsqueeze : 차원의 개수가 1인 차원을 추가

 

 

행렬 곱은 dot이 아닌 mm

dot은 1xn, nx1 벡터를 곱할때만 사용하고

나머지 행렬 곱은 mm(matmul) 함수를 사용한다. 

 

 

 

 

[출처]

https://y-rok.github.io/pytorch/2020/10/03/pytorch-gpu.html

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함