[python] 파이썬 PyTorch에서 가중치 감소(weight decay)를 설정하는 방법은?

아래는 파이썬 PyTorch에서 가중치 감소를 설정하는 예시입니다.

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

# 모델 정의
class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, 1)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = MyModel()

# 옵티마이저 설정
optimizer = optim.Adam(model.parameters(), lr=0.01, weight_decay=0.001)

위의 예시에서 weight_decay 매개변수를 0.001로 설정했습니다. 이렇게 설정하면 옵티마이저가 가중치 갱신 시에 L2 정규화 항을 추가로 계산하여 가중치의 크기를 감소시킵니다.

참고로, weight_decay 값은 보통 작은 값을 사용하며, 너무 크게 설정하면 모델의 성능이 저하될 수 있습니다. 적절한 weight_decay 값을 설정하여 모델을 훈련시키세요.