Pytorch 정리 1
개요
- Pytorch의 공식 문서를 보면서 다양한 기능들을 정리 해보자
tensor
- 배열, 행렬과 유사한 자료구조
-
pytorch는 tensor를 사용하여 모델의 입,출력
-
뿐만 아니라 모델의 매개변수를 부호화(encode) 함.
- Numpy의 ndarray와 매우 유사함
import torch
import numpy as np
tensor 초기화
다음 3가지 방법으로 초기화 할 수 있다.
- 직접 생성
- Numpy 배열로부터 생성
- 다른 tensor로 부터 생성
# 직접 생성
data = [[1,2], [3,4]]
x_data = torch.tensor(data)
print(f"{x_data} \n")
# Numpy 배열로부터 생성
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(f"{x_np} \n")
# 다른 tensor로 부터 생성
x_ones = torch.ones_like(x_data) # x_data의 속성을 유지
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씀
print(f"Random Tensor: \n {x_rand}")
''' output
x_data :
tensor([[1, 2],
[3, 4]])
x_np :
tensor([[1, 2],
[3, 4]])
Ones Tensor :
tensor([[1, 1],
[1, 1]])
Random Tensor :
tensor([[0.1098, 0.2988],
[0.3825, 0.7565]])
'''
또한 무작위(random) 또는 상수(constant) 값을 사용하여 나타낼 수 있다.
shape
은 tensor의 차원(dimension)을 나타내는 튜플로, 아래 함수들에서는 출력 tensor의 차원을 결정
shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor : \n {rand_tensor} \n")
print(f"Ones Tensor : \n {ones_tensor} \n")
print(f"Zeros Tensor : \n {zeros_tensor}")
''' output
Random Tensor :
tensor([[0.9414, 0.2859, 0.9247],
[0.4002, 0.9619, 0.7753]])
Ones Tensor :
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor :
tensor([[0., 0., 0.],
[0., 0., 0.]])
'''
tensor의 속성
- 모양(shape)
- 자료형(datatype)
- 장치(CPU or GPU)
tensor = torch.rand(3, 4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
''' output
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
'''
tensor의 연산
100가지 이상의 tensor 연산은 여기에서 확인할 수 있다.
먼저 각 연산들은 일반적으로 CPU보다 GPU에서 실행하는 것이 빠르다. 따라서 다음 코드를 통해 GPU를 사용하자
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(f"Device tensor is stored on: {tensor.device}")
''' output
Device tensor is stored on: cuda:0
'''
tensor = torch.ones(4, 4)
# 인덱싱
tensor[:,:2] = 0
print(f"Indexing : \n {tensor}\n")
# 결합
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(f"concatenate : \n {t1}\n")
# 곱
print(f"mul : \n {tensor.mul(tensor)}\n")
# 행렬 곱
print(f"mul : \n {tensor.matmul(tensor.T)}\n")
# 평균
print(f"mean : \n {tensor.mean()}\n")
print(f"mean(dim=0) : \n {tensor.mean(dim=0)}\n")
# 최대
print(f"mean : \n {tensor.max()}\n")
print(f"mean : \n {tensor.argmax()}\n")
# 차원 추가 및 제거
print(f"unsqueeze : \n {tensor.unsqueeze(dim=0)}\n") # 추가 ( dim 필수 )
print(f"squeeze : \n {tensor.squeeze()}\n") # 제거
''' output
Indexing :
tensor([[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]])
concatenate :
tensor([[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.],
[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.],
[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.],
[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1., 1.]])
mul :
tensor([[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]])
mul :
tensor([[2., 2., 2., 2.],
[2., 2., 2., 2.],
[2., 2., 2., 2.],
[2., 2., 2., 2.]])
mean :
0.5
mean(dim=0) :
tensor([0., 0., 1., 1.])
mean :
1.0
mean :
2
unsqueeze :
tensor([[[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]]])
squeeze :
tensor([[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]])
'''
https://www.youtube.com/watch?v=H3t4ndSl7nA
https://tutorials.pytorch.kr/beginner/blitz/tensor_tutorial.html
— 추가 —
Leave a comment