본문 바로가기

STUDY/인공지능

까먹지 않기 위한 파이토치 공부 내용 정리

728x90

* vector, Matrix, Tensor

  • 1D : vector라고 부름
  • 2D : Matrix라고 부름
  • 3D : Tensor라고 부름

 

* pytorch Tensor shape convention

  • 2D Tensor (Typical Simple Setting)
  • $|t|=(batchsize, dim)$

  • 3D Tensor (Typical Compputer Vision)
  • $|t| = (batch size, width, height)$

  • 3D Tensor (Typical Natural Language Processing)
  • $|t| = (batch size, length, dim)$

 

* Import

import numpy as np
import torch

 

* NumPy 

'''Ex. 1D Array with NumPy'''

t = np.array([0., 1., 2., 3., 4., 5., 6.])
print(t)
# [0. 1. 2. 3. 4. 5. 6.]

print('Rank of t: ', t.ndim)
print('shape of t: ', t.shape)
# Rank of t: 1
# Shape of t: (7,)

print('t[0] t[1] t[-1] =', t[0], t[1], t[-1]) # Element
print('t[2:5] t[4:-1] =', t[0], t[1], t[-1]) # Slicing
print('t[:2] t[3:] =', t[0], t[1], t[-1]) # Slicing
# t[0] t[1] t[-1] = 0.0 1.0 6.0
# t[2:5] t[4:-1] = [ 2. 3. 4. ] [ 4. 5. ]
# t[:2] t[3:] = [ 0. 1. ] [ 3. 4. 5. 6.]



'''Ex. 2D Array with NumPy'''

t = np.array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]])
print(t)
# [[ 0. 1. 2.]
#  [ 3. 4. 5.]
#  [ 6. 7. 8.]]

print('Rank of t: ', t.ndim)
print('shape of t: ', t.shape)
# Rank of t: 2
# Shape of t: (3, 3)

 

 

* PyTorch

'''1D Array with PyTorch'''

t = torch.FloatTensor([0., 1., 2., 3., 4., 5., 6.])
print(t)
# tensor([0., 1., 2., 3., 4., 5., 6.])

print(t.dim()) # rank
print(t.shape) # shape
print(t.size()) # shape
print(t[0], t[1], t[-1]) # Element
print(t[2:5], t[4:-1]) # Slicing
print(t[:2], t[3:]) #Slicing
# 1
# torch.Size([7])
# torch.Size([7])
# tensor(0.)  tensor(1.)  tensor(6.)
# tensor([2., 3., 4.])  tensor([4., 5.])
# tensor([0., 1.])  tensor([3., 4., 5., 6.])

'''2D Array with PyTorch'''

t = torch.FloatTensor([[0., 1., 2.], 
	[3., 4., 5.], 
                      [6., 7., 8.]])
print(t)
# tensor([[0., 1., 2.], 
# 		 [3., 4., 5.], 
#        [6., 7., 8.]])

print(t.dim()) # rank
print(t.size()) # shape
# 2
# torch.Size([4, 3])

print(t[:, 1]) 
print(t[ , 1].size()) 
print(t[:, :-1])
# tensor([1., 4., 7.])
# torch.Size([4])
# tensor([[0., 1.],
#       [3., 4.],
#        [6., 7.]])

이 글은 공부 내용을 정리한 글로, 자세한 내용을 공부하고 싶으신 분들은 '부스트코스-파이토치로 시작하는 딥러닝 기초'를 보시기 바랍니다.

728x90