1. Tensor 생성
Pytorch란?
- Pytorch는 Facebook AI Research에서 개발한 오픈 소스 머신러닝 라이브러리
- Dynamic Computation Graph를 사용하여 runtime에 연산 그래프를 동적으로 구성
- CUDA를 활용하여 GPU 가속을 간편하게 적용 가능
- Python과 같이 쉽고 사용이 직관적
- Numpy와 유사한 Tensor를 이용
- 다양한 딥러닝 모델 지원(CNN, RNN, Transformer 등)
- Hugging Face의 Transformers와 같은 다른 라이브러리와의 통합
Tensor란?
- Tensor는 다차원 배열(Multi-dimensional array) 구조로, 선형대수학의 벡터 및 행렬을 확장한 개념
- Tensor는 Pytorch에서 데이터를 표현하는 기본 단위
- 효율적인 연산 수행을 위해 Broadcasting 기능을 제공
아래부터는 한 번씩 따라서 직접 코딩해 보시고, 실행 결과를 확인해 보시길 권합니다.
1. Tensor 생성
# integer tensor 생성 1
list_int = [1, 2, 3, 4, 5]
print(torch.tensor(list_int))
print(type(list_int))
# integer tensor 생성 2
tensor_int = torch.tensor([1,2,3,4,5])
print(tensor_int)
print(tensor_int.dtype)
python의 list를 사용하여 tensor를 생성하는 방법 2가지입니다.
int_list = list(range(1, 10))
print(int_list)
tensor_list = torch.arange(1, 10)
print(tensor_int)
python의 range와 비슷하게, torch에서도 정수 tensor를 생성하는 함수를 사용하여 생성 가능합니다.
# float tensor 생성 1
tensor_float = torch.FloatTensor([1.1,2.2,3.3])
print(tensor_float)
print(tensor_float.dtype)
# float tensor 생성 2
tensor_float2 = torch.tensor([1.1,2.2,3.3])
print(tensor_float2)
print(tensor_float2.dtype)
float형의 tensor를 생성하는 2가지 방법이 있습니다.
첫 번째 방법은 tensor type을 Float으로 지정하여 생성하는 방법이고, 두 번째 방법은 tensor로 생성하는데 리스트 안에 요소들이 float 타입인 것을 확인하여 torch에서 자동으로 float 형식으로 지정하는 방법입니다.
tensor_list = torch.linspace(1, 11, 10)
print(tensor_list)
linspace는 linear하게 데이터를 생성하는 방식인데, torch.linspace(1, 11, 10)은 1부터 11까지를 10등분 하는 숫자를 생성하는 함수입니다.
#empty tensor 생성
x = torch.empty(4, 5)
print(x)
print(x.shape)
# zero tensor 생성
x = torch.zeros(4, 5)
print(x)
print(x.shape)
# one tensor 생성
x = torch.ones(4, 5)
print(x)
print(x.shape)
torch.empty는 입력으로 주어진 행렬 size 만큼 초기화하지 않은 tensor를 반환해 주는 함수입니다.
torch.zeros는 입력으로 주어진 행렬 size 만큼 element를 0으로 채운 tensor를 반환해 주는 함수입니다.
torch.ones는 입력으로 주어진 행렬 size 만큼 element를 1로 채운 tensor를 반환해 주는 함수입니다.
# 무작위 초기화 tensor
# Uniform Distribution을 따르는 분포에서 random하게 tensor 생성
x = torch.rand(4, 5)
print(x)
print(x.shape)
# Normal Distribution을 따르는 분포에서 random하게 tensor 생성 N(0, 1)
x = torch.randn(4, 5)
print(x)
print(x.shape)
rand은 주어진 size 만큼 [0,1) 사이의 숫자를 uniform distribution(균등 분포)에서 생성하므로, 각 숫자는 공평하게 random으로 추출되어 생성됩니다.
randn은 주어진 size 만큼 normal distribution(정규 분포)에서 생성하므로, 숫자는 0으로 대게 몰려서 생성되게 됩니다.
# 다른 tensor와 크기가 같은 random tensor 생성
# Normal Distribution을 따르는 분포에서 random하게 tensor 생성
x_previous = torch.randn(4, 5)
print(x_previous)
print(x_previous.shape)
# x_previous tensor가 갖는 shape와 똑같은 형태의 tensor를 랜덤하게 생성
x = torch.rand_like(x_previous)
print(x)
print(x.shape)
rand_like() 함수는 입력으로 주어진 행렬 size 만큼 uniform distribution에서 tensor를 random 하게 생성합니다.
# Multi-dimensional tensor 생성
# 0D tensor
tensor_0 = torch.randn(1)
print(tensor_0.ndim)
print(tensor_0.shape)
# 1D tensor
tensor_1 = torch.randn(3)
print(tensor_1.ndim)
print(tensor_1.shape)
# 2D tensor
tensor_2 = torch.randn(3, 3)
print(tensor_2.ndim)
print(tensor_2.shape)
# 3D tensor
tensor_3 = torch.randn(3, 3, 3)
print(tensor_3.ndim)
print(tensor_3.shape)
# 4D tensor
tensor_4 = torch.randn(3, 3, 3, 3)
print(tensor_4.ndim)
print(tensor_4.shape)
normal distribution을 따르는 tensor를 랜덤하게 생성한 후, ndim 메서드로는 해당 tensor의 차원을 확인하고, shape 메서드로는 해당 tensor의 모양을 확인하는 코드입니다.