- 시작.
저는 원래 ML과 DL 입문을 CV, 그리고 Tensorflow로 했습니다.
그런데 보통 이미 나와 있는 Transformer 모델이나, 아니면 제가 현재 다루어야 할 모델들은 전부 Pytorch로 구현 되어 있는 경우가 많았습니다.
하여 단숨에 다시 Pytorch로 밑바닥부터 차근차근 Tensorflow에서 Pytorch로 컨버젼(개인)하고,
Pytorch도 다른 Python syntax를 다뤘던 부분과 연계하여
class, 문자열 함수와 결합한 형태를 만들면서 연습해보도록 하겠습니다.
Pytorch Basic.
1. 1차원 Numpy, torch.tensor
import numpy as np
import torch
np_1d = np.array([0,1,2,3,4])
torch_1d = torch.tensor([1,2,3,4,5])
# zip 함수와의 결합.
for x,y in zip(np_1d,torch_1d):
print(x,y)
#결과
#0 tensor(1)
#1 tensor(2)
#2 tensor(3)
#3 tensor(4)
#4 tensor(5)
- 1차원 넘파이, torch.tensor에 대한 슬라이싱도 일반 파이썬 리스트처럼 가능합니다.
- 단, torch.tensor의 경우 int, float 등 숫자만 올 수 있다는 점을 유념하세요.
print(np_1d[2])
print(np_1d[-1])
print(torch_1d[1:3])
#
#결과.
#2
#4
#tensor([2, 3])
2. 2차원 Numpy, torch.tensor
np_2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
torch_2d = torch.tensor([[1,2,3],[4,5,6],[7,8,9]])
- 2중 포문을 통한 출력
for i in range(len(np_2d)):
for j in range(len(torch_2d)):
print(np_2d[i][j],torch_2d[i][j],end=' ')
print()
# 결과.
#1 tensor(1) 2 tensor(2) 3 tensor(3)
#4 tensor(4) 5 tensor(5) 6 tensor(6)
#7 tensor(7) 8 tensor(8) 9 tensor(9)
3. Numpy, torch.tensor에 대한 조건문, 반복문, 클래스 만들기
- Numpy np.array에 대해서는 문자열을 집어넣어보기도 하고, 숫자를 집어넣어보기도 합니다.
- 기본적으로 항상 상속을 받도록 정의합니다. 저의 경우 부모 클래스로는 출력 함수만 정의해보고, 나머지 세세한 함수들은 자식 새끼 클래스(?)에 정의하는 편입니다.
- 숫자를 세거나, 사이즈를 구하거나, 차원을 구하는 함수를 구현하거나, 가져다 씁니다.
- **kwargs 키워드를 사용합니다.
- 부모 클래스
class array:
## 생성자
def __init__(self,numpy_array,torch_array):
self.numpy_2d_array = numpy_array
self.torch_2d_array = torch_array
def show_numpy_array(self):
for i in range(len(self.numpy_2d_array)):
for j in range(len(self.numpy_2d_array[0])):
print(self.numpy_2d_array[i][j], end=' ')
print()
def show_torch_array(self):
for i in range(len(self.torch_2d_array)):
for j in range(len(self.torch_2d_array[0])):
print(self.torch_2d_array[i][j],end=' ')
print()
- 자식 클래스
class array_main(array):
## 생성자
def __init__(self,**kwargs):
self.numpy_2d_array = kwargs['numpy_array']
self.torch_2d_array = kwargs['torch_array']
super(array_main,self).__init__(self.numpy_2d_array,self.torch_2d_array)
def numpy_search(self,target):
res = []
for x in range(len(self.numpy_2d_array)):
for y in range(len(self.numpy_2d_array[0])):
if self.numpy_2d_array[x][y].endswith(target):
res.append(self.numpy_2d_array[x][y])
print(res)
def numpy_length(self):
res=[]
for x in self.numpy_2d_array:
res.append(len(x))
print(res)
def torch_size(self):
cnt=0
for x in range(len(self.torch_2d_array)):
for y in range(len(self.torch_2d_array[x])):
cnt+=1
print(cnt)
return cnt
def torch_describe(self):
yy = self.torch_2d_array
res = self.torch_size()
#print(res)
print('shape :',yy.shape,'size :',res,'dim :',yy.dim())
- 인스턴스 선언
xx = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
yy = torch.tensor([[1,2,3],[4,5,6],[6,7,8]])
- 함수 실행
x.show_numpy_array()
x.show_torch_array()
x.torch_describe()
#
# 결과
#a b c
#d e f
#g h i
#tensor(1) tensor(2) tensor(3)
#tensor(4) tensor(5) tensor(6)
#tensor(6) tensor(7) tensor(8)
#9
#shape : torch.Size([3, 3]) size : 9 dim : 2
이상입니다.
한번 여러분들이 알고 있는 함수나 클래스 문법을 활용하여서
쉽게 pytorch에 적응해보는 것을 권유합니다.
'ML & DL > Pytorch(base)' 카테고리의 다른 글
'찐비전공자를 위한' : Pytorch 기초 다루기 - 행렬 연산, 사칙 연산 (0) | 2022.02.24 |
---|