PyTorch와 객체 지향 프로그래밍

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

학습 목표

견고한 딥러닝 모델을 학습하는 방법:

  • 옵티마이저로 학습 개선
  • 기울기 소실/폭주 완화
  • 합성곱 신경망(CNN)
  • 순환 신경망(RNN)
  • 다중 입력/출력 모델

 

 

PyTorch 로고

PyTorch로 배우는 Intermediate Deep Learning

필수 지식

이 과목은 다음 주제에 익숙하다고 가정합니다:

PyTorch로 배우는 Intermediate Deep Learning

객체 지향 프로그래밍(OOP)

  • OOP로 다음을 정의합니다:

    • PyTorch Dataset
    • PyTorch 모델
  • OOP에서 객체는 다음을 가집니다:

    • 동작(메서드)
    • 데이터(속성)
PyTorch로 배우는 Intermediate Deep Learning

객체 지향 프로그래밍(OOP)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance
  • __init__BankAccount 객체가 생성될 때 호출됨
  • balanceBankAccount 객체의 속성임
account = BankAccount(100)
print(account.balance)
100
PyTorch로 배우는 Intermediate Deep Learning

객체 지향 프로그래밍(OOP)

  • 메서드: 작업을 수행하는 Python 함수
  • deposit 메서드는 잔액을 증가시킴
class BankAccount:
    def __init__(self, balance):
        self.balance = balance


def deposit(self, amount): self.balance += amount
account = BankAccount(100)
account.deposit(50)
print(account.balance)
150
PyTorch로 배우는 Intermediate Deep Learning

물 음용 가능성 데이터셋

물 음용 가능성 데이터의 일부 처음과 마지막 행을 보여주는 Pandas DataFrame.

PyTorch로 배우는 Intermediate Deep Learning

PyTorch Dataset

from torch.utils.data import Dataset

class WaterDataset(Dataset):

def __init__(self, csv_path): super().__init__() df = pd.read_csv(csv_path) self.data = df.to_numpy()
def __len__(self): return self.data.shape[0]
def __getitem__(self, idx): features = self.data[idx, :-1] label = self.data[idx, -1] return features, label
  • init: 데이터 로드, numpy 배열로 저장
    • super().__init__()WaterDataset이 torch Dataset처럼 동작하도록 함
  • len: 데이터셋 크기 반환
  • getitem:
    • idx 인자 하나를 받음
    • 인덱스 idx의 단일 샘플에 대한 특징과 레이블 반환
PyTorch로 배우는 Intermediate Deep Learning

PyTorch DataLoader

dataset_train = WaterDataset(
    "water_train.csv"
)
from torch.utils.data import DataLoader

dataloader_train = DataLoader(
    dataset_train,
    batch_size=2,
    shuffle=True,
)
features, labels = next(iter(dataloader_train))
print(f"Features: {features},\nLabels: {labels}")
Features: tensor([
  [0.4899, 0.4180, 0.6299, 0.3496, 0.4575,
   0.3615, 0.3259, 0.5011, 0.7545],
  [0.7953, 0.6305, 0.4480, 0.6549, 0.7813,
   0.6566, 0.6340, 0.5493, 0.5789]
]),
Labels: tensor([1., 0.])
PyTorch로 배우는 Intermediate Deep Learning

PyTorch 모델

Sequential 모델 정의:

net = nn.Sequential(
  nn.Linear(9, 16),
  nn.ReLU(),
  nn.Linear(16, 8),
  nn.ReLU(),
  nn.Linear(8, 1),
  nn.Sigmoid(),
)

클래스 기반 모델 정의:

class Net(nn.Module):

def __init__(self): super().__init__() self.fc1 = nn.Linear(9, 16) self.fc2 = nn.Linear(16, 8) self.fc3 = nn.Linear(8, 1)
def forward(self, x): x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = nn.functional.sigmoid(self.fc3(x)) return x net = Net()
PyTorch로 배우는 Intermediate Deep Learning

연습해 봅시다!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...