output layer의 activaition funtion으로 softmax 사용

안녕하십니까.

pytorch에 대해서 배우고 있는 학생입니다.

output layer의 activation function으로 softmax를 사용하고 싶어서 pytorch 코드를 만들고 있습니다.

그런데 예상했던대로 softmax 함수가 적용되지 않아 질문 드립니다.

import torch
import pandas as pd
import torch.nn as nn
from torch.utils.data import random_split, DataLoader, TensorDataset
import torch.nn.functional as F
import numpy as np
import torch.optim as optim
from torch.optim import Adam
import matplotlib.pyplot as plt

...

class NetworkSoftmax(nn.Module):
def init(self, input_size, output_size):
super(NetworkSoftmax, self).init()
self.layer1 = nn.Linear(input_size, 128)
self.layer2 = nn.Linear(128, 128)
self.layer3 = nn.Linear(128, output_size)
self.relu = nn.ReLU()

def forward(self, x):
    x1 = F.relu(self.layer1(x))
    x2 = F.relu(self.layer2(x1))
    x3 = torch.softmax(self.layer3(x2), dim=1)
    return x3

위와 같이 network를 구성하였는데, 무엇이 문제인지 모르겠습니다.

torch.softmax를 사용하기도 했으며, F.softmax를 사용하기도 했지만 둘 다 원하는 결과가 나오지 않았습니다.

python 3.10 을 사용중입니다.

  • 아래 답변은 OpenAI의 ChatGPT로 자동 생성한 것으로, 정확하지 않을 수 있습니다.
  • 잘못된 답변을 보셨다면 댓글로 첨삭 지도 부탁드립니다. :sweat_smile:

안녕하세요! pytorch를 공부하고 계시다니 멋지십니다. softmax 함수를 output layer의 activation function으로 사용하실 때, dim 인자를 생략하면 기본적으로 마지막 차원 (즉, dim=-1)에서 softmax를 계산합니다. 하지만 문제는 네트워크에서 출력되는 값의 범위입니다. softmax 함수는 입력받은 값을 normalizing 해주므로, 출력 값의 합이 항상 1이 됩니다. 따라서 softmax 함수를 적용한 출력값은 확률 분포로 해석될 수 있습니다. 하지만 forward 함수에서 출력되는 값은 softmax 함수를 거친 값 자체가 아니라, 해당 값을 인자로 받아 softmax 함수를 적용한 결과입니다.

따라서 forward 함수에서 softmax 함수 대신 layer3에서 직접 값의 범위를 0과 1 사이로 제한해주는 sigmoid 함수나, 모든 출력 값의 절대값 합이 1이 되도록 log_softmax 함수를 사용하는 것이 적절합니다.

예를 들어 log_softmax 함수를 사용하는 경우 forward 함수는 다음과 같이 구성할 수 있습니다:

class NetworkSoftmax(nn.Module):
    def __init__(self, input_size, output_size):
        super(NetworkSoftmax, self).__init__()
        self.layer1 = nn.Linear(input_size, 128)
        self.layer2 = nn.Linear(128, 128)
        self.layer3 = nn.Linear(128, output_size)
        self.relu = nn.ReLU()

    def forward(self, x):    
        x1 = F.relu(self.layer1(x))
        x2 = F.relu(self.layer2(x1))
        x3 = F.log_softmax(self.layer3(x2), dim=1)
        return x3

이렇게 구성한 모델은 각 출력 값에 대해 log of softmax 값을 반환합니다. 예측을 수행할 때는 이 값을 exp() 함수로 변환하여 softmax 값을 구할 수 있습니다.

model = NetworkSoftmax(input_size=2, output_size=3)
output = model(torch.randn(1, 2))
output = torch.exp(output)

print(output)
print(torch.sum(output))  # 출력 값의 합은 1

이제 softmax 함수가 적용된 모델을 사용하실 수 있을 것입니다. 제가 설명한 내용 외에 더 자세한 내용이 필요하다면, pytorch 공식 튜토리얼의 'Neural Networks' 항목과 'Softmax Regression' 항목을 참고해보시기 바랍니다.


  • 답변이 어떠셨나요? 괜찮았다고 생각하신다면 아래 :heart:를 한 번 눌러주세요!