When will you grow up?

1. Pytorch - Tensor 본문

02. Study/Pytorch

1. Pytorch - Tensor

미카이 2020. 2. 24. 00:24

다양한 딥러닝 패키지 중, Pytorch를 빠르게 익히고자 정리를 합니다.

내용은 Pytorch tutorial, youtube를 기반으로 정리하였습니다.

 

Pytorch ?

 - torch(lua)에서 pytorch(python)로 넘어오게 되었으며, python 기반의 과학 컴퓨팅 패키징이다.

 - Numpy를 GPU를 통해 가속화해서 빠른 연산이 가능하다.

 - 개인적으로, tf에 비해 코드가 좀 더 직관적인 면이 있다. 약간 class로 다 만들어서 그런가..? 

 

 

Tensor ?

 - Tensor는 pytorch의 자료 형

 - 단일 데이터 타입으로 된 다차원 행렬이다. (일반적으로 ? 0d scalar, 1d vector, 2d matrix, 3d~nd tensor)

 - Tensor는 간단한 명령어 [.cuda()] 를 추가하면 gpu로 연산이 가능

 - 더 많은 pytorch의 tensor종류는 클릭 

 

 

Tensor Use 

만약 pytorch가 설치가 안되어 있다면 클릭

 

import torch

x = torch.Tensor(3)

print(x) # 초기화 되지 않은 tensor 생성 [torch.FloatTensor of size 3]

 

x2 = torch.Tensor(3,3)

print(x2) # [torch.FloatTensor of size 3x3]

 

x3 = torch.rand(3,3)

print(x3) # rand는 0~1 사이의 uniform distribution random 값으로 선언

 

x4 = torch.randn(3,3)

print(x4) # randn는 평균이 0, 분산이 1인 normal distribution random 값으로 선언

 

 

Numpy -> Tensor 변환 및 Tensor -> Numpy 변환

# .Tensor() / .numpy()

import torch

import numpy as np

a = np.array([1,2,3,4])

b = torch.Tensor(a) # numpy array -> tensor convert

a1 = torch.Tensor(3)

b1 = a1.numpy() # tensor -> numpy array convert

 

 

Tensor 형태 변환 

# .view()

import torch

a = torch.rand(3,3) # (3x3 크기의 2차원 tensor생성)

a = a.view(1,1,3,3)

print(a) # (1x1x3x3) 형태의 4차원 tensor 생성

 

 

Tensor 이어 붙이기

# .cat()

import torch

a = torch.rand(1,1,3,3)

b = torch.randn(1,1,3,3)

c = torch.cat((a,b),0) # tensor, axis

 

 

GPU 계산 (cpu버전말고, gpu버전 깐 사람만 해당)

# .cuda()

import torch

x = torch.rand(3,3)

y = torch.rand(3,3)

# torch.cuda.get_device_name(0) # 자신의 그래픽카드가 나온다.

# print(torch.__version__) # torch 버전확인 

if torch.cuda.is_available():

    x = x.cuda()

    y = y.cuda()

    sum = x + y

 

그 외에 다양한 함수는 https://pytorch.org/docs/stable/torch.html

'02. Study > Pytorch' 카테고리의 다른 글

2. Pytorch - Autograd  (0) 2020.02.24
Comments