본문 바로가기
Data Science/Deep Learning

Pytorch 모델 작성 기본 구조 이해하기

by Queen2 2023. 4. 13.
728x90
반응형

파이토치 모델 작성 기본 구조를 간략하게 설명해달라고 했더니

ChatGPT 가 짜준 구조입니다.

 

구조에 대한 기본 설명

nn.Module을 통해 모델의 층을 정의하고 forward pass할 층을 구성하도록 한뒤에,

사용할 데이터를 로드한 뒤,

 

모델/손실함수/옵티마이저를 정해주고 훈련을 시작합니다.

 

이후에 정한 epoch만큼 각 배치의 데이터들을 꺼내서

zero_grad로 옵티마이저의 그레디언트를 초기화 시킨 뒤에 

모델을 통해 나온 결과를 비교해서 정의한 손실함수에 넣습니다.

 

계산된 손실함수를 토대로 역전파를 돌리고

옵티마이저의 파라미터도 업데이트를 진행합니다.

 

예시에는 if 문을 토대로 10개 배치를 기준으로 로그를 남겨습니다.

 


Pytorch 모델 작성 기본구조

import torch
import torch.nn as nn
import torch.optim as optim

# Define your model
class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        # Define your layers here

    def forward(self, x):
        # Define the forward pass of your model here
        return x

# Define your dataset and dataloader
train_dataset = MyDataset(...)
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)

# Initialize your model, loss function, and optimizer
model = MyModel()
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Set the model to training mode
model.train()

# Loop over the training data
for epoch in range(num_epochs):
    for i, batch in enumerate(train_dataloader):
        # Zero the gradients
        optimizer.zero_grad()

        # Get the inputs and labels from the batch
        inputs, labels = batch

        # Forward pass
        outputs = model(inputs)

        # Compute the loss
        loss = loss_fn(outputs, labels)

        # Backward pass
        loss.backward()

        # Update the parameters
        optimizer.step()

        # Print the loss every 10 batches
        if i % 10 == 0:
            print(f"Epoch {epoch}, Batch {i}, Loss {loss.item():.4f}")

 

매번 보면서 어렴풋이 알지만 한번 대략적인 구조를 정리하고 나니까 

머리에 코드가 좀 더 잘 들어오는 것 같네요!

728x90
반응형

댓글