본문 바로가기
파이토치

[파이토치] 파이토치에서 데이터 로드하기

by mhiiii 2024. 11. 7.
728x90
  • 미니배치
  • 데이터 셔플
  • 병렬 처리

파이토치에서 기본적인 데이터 로드 방법은 Dataset을 정의하고, 이를 DataLoader에 전달하는 것입니다.

 

텐서를 입력받아 Dataset의 형태로 변환해주는 TensorDataset 사용해보기

import torch
import torch.nn as nn
import torch.nn.functional as F

from torch.utils.data import TensorDataset # 텐서데이터셋
from torch.utils.data import DataLoader # 데이터로더

x_train  =  torch.FloatTensor([[73,  80,  75], 
                               [93,  88,  93], 
                               [89,  91,  90], 
                               [96,  98,  100],   
                               [73,  66,  70]])  
y_train  =  torch.FloatTensor([[152],  [185],  [180],  [196],  [142]])

dataset = TensorDataset(x_train, y_train)

dataloader = DataLoader(dataset, batch_size=2, shuffle=True)

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

 

텐서를 정의하여 TensorDataset의 입력으로 사용합니다. 

그리고 이를 dataset으로 저장합니다.

 

파이토치의 데이터셋을 만들었다면 데이터로더를 사용할 수 있습니다.

데이터로더는 dataset과 미니 배치 크기를 필요로하고, 추가적으로 shuffle이라는 인자를 넣을 수 있습니다.

shuffle은 데이터셋을 매 Epoch마다 섞어서 학습시킬 수 있습니다.

validateion이나 test에 필요한 데이터셋에는 굳이 shuffle을 하진 않습니다.

 

nb_epochs = 20
for epoch in range(nb_epochs + 1):
  for batch_idx, samples in enumerate(dataloader):
    # print(batch_idx)
    # print(samples)
    x_train, y_train = samples
    # H(x) 계산
    prediction = model(x_train)

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

    # cost로 H(x) 계산
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()

    print('Epoch {:4d}/{} Batch {}/{} Cost: {:.6f}'.format(
        epoch, nb_epochs, batch_idx+1, len(dataloader),
        cost.item()
        ))

 

 

torch.utils.data.Dataset을 상속받아 직접 커스텀 데이터셋(Custom Dataset)을 만드는 경우

torch.utils.data.Dataset은 파이토치에서 데이터셋을 제공하는 추상 클래스입니다.

class CustomDataset(torch.utils.data.Dataset): 
  def __init__(self):

  def __len__(self):

  def __getitem__(self, idx):

__init__ : 데이터셋의 전처리를 해주는 부분

__len__ : 데이터셋의 길이, 즉 샘플의 총 개수를 적어주는 부분, len(dataset)으로 호출 

__getitem__ : 데이터셋에서 특정 1개의 샘플을 가져오는 함수, dataset[i]로 호출

 

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

# 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)

  # 인덱스를 입력받아 그에 맵핑되는 입출력 데이터를 파이토치의 Tensor 형태로 리턴
  def __getitem__(self, idx): 
    x = torch.FloatTensor(self.x_data[idx])
    y = torch.FloatTensor(self.y_data[idx])
    return x, y

dataset = CustomDataset()
dataloader = DataLoader(dataset, batch_size=2, shuffle=True)

model = torch.nn.Linear(3,1)
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):
    # print(batch_idx)
    # print(samples)
    x_train, y_train = samples
    # H(x) 계산
    prediction = model(x_train)

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

    # cost로 H(x) 계산
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()

    print('Epoch {:4d}/{} Batch {}/{} Cost: {:.6f}'.format(
        epoch, nb_epochs, batch_idx+1, len(dataloader),
        cost.item()
        ))

 

Reference

https://wikidocs.net/55580

728x90