- toc {:toc}
Pipeline Batch training pattern
머신러닝, 딥러닝 학습을 진행하는데 가장 기본이 되는 패턴이다. 머신러닝, 딥러닝에서의 학습은 다음과 같이 분류할 수 있다.
- 데이터 수집
- 데이터 전처리
- 모델 학습
- 모델 평가
- 예측 서버에 모델 구축
- 모델, 서버, 평가 기록
다음과 같이 머신러닝에서의 학습은 여러 과정으로 분할된다. 이 각 프로세스들을 순차적으로 실행하여 학습이 이루어지도록 만드는 패턴이 pipeline batch training pattern이다. 프로세스들이 분할되어 있어, 학습 도중의 경과를 기록하고 재사용이나 부분적인 수정을 간편하게 하거나, 병렬 처리를 통해 성능을 향상시킬 수 있다. 또한, 각각의 프로세스에서 사용되는 라이브러리를 선택해 사용할 수 있고 파이프라인을 만들면서 학습 및 추론에 대한 자동화를 진행할 수 있다.
Pipeline batch training pattern을 사용하는 경우(장점)
- 파이프라인의 자원을 분할해 프로세스마다 라이브러리를 선정하는 경우
- 프로세스를 다른 용도로 함께 사용하려는 경우
- 프로세스마다 데이터의 상태, 진행 로그들을 기록하고 싶은 경우
- 프로세스 실험을 개별적으로 다루고 싶은 경우
단점
- 개별 작업을 진행하면서 독립성을 갖추나 확인해야 할 조건이 늘어나 코드 관리가 복잡해진다.
- 자원 선택에 대해 고려 사항이 늘어난다.
서비스의 전체적인 그림은 아래와 같고, 그 중 학습 파이프라인에서 Pipeline Batch training pattern이 사용되었다.
- 코드 전체적인 코드 구조는 pytorch tutorial을 통해 이해할 수 있다. 데이터셋으로 Fashion-MNIST dataset을 사용했다.
- Fashion-MNIST Dataset을 load해 학습 데이터를 수집한다.
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
위 Fashion-MNIST의 경우와 달리 각 task에 따라 데이터셋을 제작하여 훈련을 진행하는 경우 학습에 사용할할 Custom Dataset을 만든다.
import os
import pandas as pd
from torchvision.io import read_image
class CustomImageDataset(Dataset):
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
self.img_labels = pd.read_csv(annotations_file)
self.img_dir = img_dir
self.transform = transform
self.target_transform = target_transform
def __len__(self):
return len(self.img_labels)
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
image = read_image(img_path)
label = self.img_labels.iloc[idx, 1]
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
- 위 Fashion-MNIST Dataset load 과정에서는 데이터를 불러오면서 transform을 적용해 불러오도록 만들어져 있지만, 일반적으로 학습 데이터를 불러오는 경우 데이터를 불러오고, 학습 데이터를 훈련에 적합하도록 데이터 증강, 정규화 등 전처리를 진행한다.
from torchvision import transforms
train_df, val_df = train_test_split(training_data,
test_size=0.15,
random_state=42,
stratify=imageNet_df['label'])
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
train_ds = Dataset(train_df,
root_dir,
transform=transform)
val_ds = ImageNetDataset(val_df,
root_dir,
transform=transform)
dataset = {'train' : train_ds, 'val' : val_ds}
train_loader = DataLoader(train_ds, batch_size = config['batch_size'], shuffle=True)
val_loader = DataLoader(val_ds, batch_size = config['batch_size'], shuffle=True)
- 학습을 진행할 모델을 만들고 학습과 평가를 진행한다.
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
def train_loop(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
# Set the model to training mode - important for batch normalization and dropout layers
# Unnecessary in this situation but added for best practices
model.train()
for batch, (X, y) in enumerate(dataloader):
# Compute prediction and loss
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), (batch + 1) * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_loop(dataloader, model, loss_fn):
# Set the model to evaluation mode - important for batch normalization and dropout layers
# Unnecessary in this situation but added for best practices
model.eval()
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, correct = 0, 0
# Evaluating the model with torch.no_grad() ensures that no gradients are computed during test mode
# also serves to reduce unnecessary gradient computations and memory usage for tensors with requires_grad=True
with torch.no_grad():
for X, y in dataloader:
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loop(train_dataloader, model, loss_fn, optimizer)
test_loop(test_dataloader, model, loss_fn)
print("Done!")
이후 예측 진행, 모델, 서버, 평가 기록의 경우 해당 환경에 따라 달라지게 된다. Pipeline batch training pattern의 과정은 다음과 같고 각 서비스에 따라 구조가 달라진다.
참고문헌
- pytorch 튜토리얼 : https://pytorch.org/tutorials/