파이토치로 시작하는 딥러닝 기초 (부스트코스) - Lab-04-2 Loading Data

  • 복잡한 머신러닝 모델을 학습하려면 엄청난 양의 데이터가 필요함
    그러나 이를 한 번에 학습시킬 순 없음. 너무 느리기도 하고, 하드웨어적으로도 불가능
    => 일부분의 데이터로만 학습! 미니배치 (전체 데이터를 균일하게 나눠서 학습)

  • Minibatch Gradient Descent의 효과
    1) 업데이트를 좀 더 빠르게 할 수 있음
    2) 그러나 전체 데이터를 쓰지 않아서 잘못된 방향으로 업데이트할 수도 있음

  • 파이토치는 torch.uilts.data.DataLoader 와 torch.utils.data.Dataset 을 사용하여, 미리 준비해둔 데이터셋뿐만 아니라 가지고 있는 데이터를 사용할 수 있도록 함.

  • Dataset은 샘플과 정답(label)을 저장하고, DataLoader는 Dataset을 샘플에 쉽게 접근할 수 있도록 순회 가능한 객체(iterable)로 감쌈.

from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
import torch.nn.functional as F
import torch

# torch.utils.data.Dataset 사용
class CustomDataset(Dataset):
    def __init__(self):
        self.x_data = [[73, 80, 75],
                       [93, 88, 93],
                       [89, 91, 90],
                       [96, 98, 100],
                       [73, 66, 70]]
        self.y_data = [[152], [185], [180], [196], [142]]

    def __len__(self):
        # 이 데이터셋의 총 데이터 수
        return len(self.x_data)

    def __getitem__(self, idx):
        # 어떠한 인덱스 idx를 받았을 때
        # 그에 상응하는 입출력 데이터를 반환함
        x = torch.FloatTensor(self.x_data[idx])
        y = torch.FloatTensor(self.y_data[idx])

        return x, y

dataset = CustomDataset()

# torch.utils.data.DataLoader 사용
dataloader = DataLoader(
    dataset,
    batch_size=2, # 각 미니배치의 크기, 통상적으로 2의 제곱수로 설정
    shuffle=True # Epoch마다 데이터셋을 섞어서, 데이터가 학습되는 순서를 바꿈
)


class MultivariateLinearRegressionModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(3, 1)

    def forward(self, x):
        return self.linear(x)

model = MultivariateLinearRegressionModel()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-5)

nb_epochs = 20
for epoch in range(nb_epochs + 1):
    for batch_idx, samples in enumerate(dataloader): # minibatch 인덱스와 데이터를 받음
        x_train, y_train = samples
        # H(x) 계산
        prediction = model(x_train)

        # cost 계산
        cost = F.mse_loss(prediction, y_train)

        optimizer.zero_grad()
        cost.backward()
        optimizer.step()

        print('Epoch {:4d}/{} hypothesis: {} Cost: {:.6f}'.format(
            # len(dataloader) : 한 epoch당 미니배치의 개수
            epoch, nb_epochs, len(dataloader), cost.item()
        ))
>>>
Epoch    0/20 hypothesis: 3 Cost: 65469.882812
Epoch    0/20 hypothesis: 3 Cost: 20198.619141
Epoch    0/20 hypothesis: 3 Cost: 8328.520508
Epoch    1/20 hypothesis: 3 Cost: 1771.130493
Epoch    1/20 hypothesis: 3 Cost: 510.977753
Epoch    1/20 hypothesis: 3 Cost: 276.539795
Epoch    2/20 hypothesis: 3 Cost: 35.494713
Epoch    2/20 hypothesis: 3 Cost: 19.935017
Epoch    2/20 hypothesis: 3 Cost: 4.103629
Epoch    3/20 hypothesis: 3 Cost: 1.611686
Epoch    3/20 hypothesis: 3 Cost: 0.311820
Epoch    3/20 hypothesis: 3 Cost: 0.595848
Epoch    4/20 hypothesis: 3 Cost: 0.162133
Epoch    4/20 hypothesis: 3 Cost: 0.303527
Epoch    4/20 hypothesis: 3 Cost: 0.310495
Epoch    5/20 hypothesis: 3 Cost: 0.447412
Epoch    5/20 hypothesis: 3 Cost: 0.157541
Epoch    5/20 hypothesis: 3 Cost: 0.232849
Epoch    6/20 hypothesis: 3 Cost: 0.534537
Epoch    6/20 hypothesis: 3 Cost: 0.170841
Epoch    6/20 hypothesis: 3 Cost: 0.148868
Epoch    7/20 hypothesis: 3 Cost: 0.109306
Epoch    7/20 hypothesis: 3 Cost: 0.162745
Epoch    7/20 hypothesis: 3 Cost: 0.612643
Epoch    8/20 hypothesis: 3 Cost: 0.132915
Epoch    8/20 hypothesis: 3 Cost: 0.312399
Epoch    8/20 hypothesis: 3 Cost: 0.295147
Epoch    9/20 hypothesis: 3 Cost: 0.109110
Epoch    9/20 hypothesis: 3 Cost: 0.363284
Epoch    9/20 hypothesis: 3 Cost: 0.153292
Epoch   10/20 hypothesis: 3 Cost: 0.191103
Epoch   10/20 hypothesis: 3 Cost: 0.277986
Epoch   10/20 hypothesis: 3 Cost: 0.423206
Epoch   11/20 hypothesis: 3 Cost: 0.100892
Epoch   11/20 hypothesis: 3 Cost: 0.513258
Epoch   11/20 hypothesis: 3 Cost: 0.114717
Epoch   12/20 hypothesis: 3 Cost: 0.214327
Epoch   12/20 hypothesis: 3 Cost: 0.221839
Epoch   12/20 hypothesis: 3 Cost: 0.405761
Epoch   13/20 hypothesis: 3 Cost: 0.111736
Epoch   13/20 hypothesis: 3 Cost: 0.145362
Epoch   13/20 hypothesis: 3 Cost: 0.576340
Epoch   14/20 hypothesis: 3 Cost: 0.361385
Epoch   14/20 hypothesis: 3 Cost: 0.021315
Epoch   14/20 hypothesis: 3 Cost: 0.407687
Epoch   15/20 hypothesis: 3 Cost: 0.368016
Epoch   15/20 hypothesis: 3 Cost: 0.105536
Epoch   15/20 hypothesis: 3 Cost: 0.257781
Epoch   16/20 hypothesis: 3 Cost: 0.067966
Epoch   16/20 hypothesis: 3 Cost: 0.641744
Epoch   16/20 hypothesis: 3 Cost: 0.034962
Epoch   17/20 hypothesis: 3 Cost: 0.196491
Epoch   17/20 hypothesis: 3 Cost: 0.309715
Epoch   17/20 hypothesis: 3 Cost: 0.034911
Epoch   18/20 hypothesis: 3 Cost: 0.182670
Epoch   18/20 hypothesis: 3 Cost: 0.312757
Epoch   18/20 hypothesis: 3 Cost: 0.089453
Epoch   19/20 hypothesis: 3 Cost: 0.190590
Epoch   19/20 hypothesis: 3 Cost: 0.156555
Epoch   19/20 hypothesis: 3 Cost: 0.506561
Epoch   20/20 hypothesis: 3 Cost: 0.496149
Epoch   20/20 hypothesis: 3 Cost: 0.388282
Epoch   20/20 hypothesis: 3 Cost: 0.009516

0개의 댓글