파이토치에서 크로스 엔트로피 손실 사용 시 출력에 소프트맥스를 사용해야 할까요? (Python, PyTorch, MNIST)

2024-07-27

  • 일반적으로 네, 크로스 엔트로피 손실 함수와 함께 소프트맥스 활성화 함수를 사용하는 것이 좋습니다.
  • 하지만, 사용하는 손실 함수에 따라 다릅니다.
    • nn.CrossEntropyLoss 함수는 내부적으로 로그 소프트맥스를 포함하고 있으므로 별도의 소프트맥스 활성화 함수가 필요하지 않습니다.
    • nn.NLLLoss 함수는 로그 소프트맥스를 포함하지 않으므로 직접 소프트맥스 활성화 함수를 사용해야 합니다.
  • MNIST 분류 예시 코드를 통해 각 경우의 구현 방법을 확인할 수 있습니다.

소프트맥스와 크로스 엔트로피 손실

  • 소프트맥스는 다중 클래스 분류 문제에서 예측 확률을 계산하는 활성화 함수입니다.
  • 크로스 엔트로피 손실은 예측 확률 분포와 실제 레이블 간의 차이를 측정하는 손실 함수입니다.

두 함수는 서로 밀접하게 연관되어 있으며, 함께 사용하면 모델의 성능을 향상시키는 데 도움이 됩니다.

파이토치에서의 구현

1 nn.CrossEntropyLoss 사용

import torch
import torch.nn as nn

# MNIST 데이터 로드
train_loader, test_loader = mnist_loaders()

# 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return x

# 모델 생성 및 학습
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

# 모델 평가
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')

2 nn.NLLLoss 사용

import torch
import torch.nn as nn

# MNIST 데이터 로드
train_loader, test_loader = mnist_loaders()

# 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return x

# 모델 생성 및 학습
model = Net()
criterion = nn.NLLLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        outputs = nn.functional.softmax(outputs, dim=1)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()




예제 코드

1 nn.CrossEntropyLoss 사용

import torch
import torch.nn as nn

# MNIST 데이터 로드
train_loader, test_loader = mnist_loaders()

# 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return x

# 모델 생성 및 학습
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

# 모델 평가
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')

2 nn.NLLLoss 사용

import torch
import torch.nn as nn

# MNIST 데이터 로드
train_loader, test_loader = mnist_loaders()

# 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return x

# 모델 생성 및 학습
model = Net()
criterion = nn.NLLLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        outputs = nn.functional.softmax(outputs, dim=1)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

# 모델 평가
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        outputs = model(images)
        outputs = nn.functional.softmax(outputs, dim=1)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')
  • 위 코드는 MNIST 분류 예시이며, 다른 문제에 적용하기 위해서는 수정해야 할 수도 있습니다.
  • nn.CrossEntropyLoss 함수는 log_softmax 연산을 내부적으로 수행하므로, 따로 softmax 연산을 수행할 필요는 없습니다.
  • nn.NLLLoss 함수는 log_softmax 연산을 포함하지 않으므로, softmax 연산을 직접 수행해야 합니다.



소프트맥스 대신 사용할 수 있는 방법

Sigmoid:

  • 이진 분류 문제에서 사용됩니다.
  • 출력 값은 0과 1 사이의 확률을 나타냅니다.
import torch
import torch.nn as nn

# 이진 분류 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 1)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        x = torch.sigmoid(x)
        return x

# 모델 생성 및 학습
model = Net()
criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

# 모델 평가
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        outputs = model(images)
        outputs = (outputs > 0.5).float()
        total += labels.size(0)
        correct += (outputs == labels).sum().item()

    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')

Gumbel Softmax:

  • 샘플링 과정을 통해 다양한 예측 결과를 생성합니다.
import torch
import torch.nn as nn
import torch.distributions as dist

# 확률적 분류 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return gumbel_softmax(x, temperature=1.0)

# 모델 생성 및 학습
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    for images, labels in train_loader:
        outputs = model(images)
        loss = criterion(outputs, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

# 모델 평가
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}%')

Noisy Softmax:

  • 데이터 증강 효과를 제공합니다.
  • 모델의 일반화 성능을 향상시킬 수 있습니다.
import torch
import torch.nn as nn
import torch.distributions as dist

# 데이터 증강 효과를 제공하는 모델 정의
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 10)

    def forward(self, x):
        x = x.view(-1, 784)
        x = self.fc1(x)
        return noisy_softmax(x, temperature=1.0)

# 모델 생성 및 학습
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):

python pytorch mnist



파이썬에서 바이너리 리터럴을 표현하는 방법

1. 0b 접두사 사용:가장 간단한 방법은 0b 접두사를 사용하는 것입니다.2. 0x 접두사 사용:16진수 리터럴을 바이너리 리터럴로 변환하는 데 0x 접두사를 사용할 수 있습니다.3. f-문자열 사용:f-문자열을 사용하여 바이너리 리터럴을 표현할 수 있습니다...


Protocol Buffers를 사용한 Python, XML, 데이터베이스 프로그래밍 경험

1. 빠른 성능:Protocol Buffers는 바이너리 형식으로 데이터를 직렬화하기 때문에 XML이나 JSON보다 훨씬 빠르게 처리됩니다. 이는 네트워크를 통해 데이터를 전송하거나 데이터베이스에 저장해야 하는 경우 특히 중요합니다...


Python에서 운영 체제 식별하기

다음은 Python에서 운영 체제를 식별하는 방법 두 가지입니다.platform 모듈은 Python 표준 라이브러리에 포함되어 있으며 운영 체제 및 하드웨어 플랫폼에 대한 정보를 제공합니다. 다음 코드는 platform 모듈을 사용하여 운영 체제 이름...


Python을 사용한 직접 실행 가능한 플랫폼 간 GUI 앱 만들기

이 가이드에서는 Python을 사용하여 플랫폼 간 GUI 앱을 만들고 직접 실행 가능한 파일로 배포하는 방법을 설명합니다. 다양한 GUI 프레임워크와 배포 도구를 살펴보고 각 도구의 장단점을 비교합니다. 또한 사용자 인터페이스 설계...


파이썬에서 문자열을 사용하여 모듈의 함수 호출

파이썬에서 문자열을 사용하여 모듈의 함수를 호출하는 방법은 두 가지가 있습니다.getattr() 함수 사용: getattr() 함수는 객체와 문자열을 인수로 받아 문자열로 지정된 이름의 속성을 가져옵니다.exec() 함수 사용: exec() 함수는 문자열을 인수로 받아 Python 코드를 실행합니다...



python pytorch mnist

cx_Oracle: 결과 세트 반복 방법

1. fetch() 함수 사용fetch() 함수는 결과 세트에서 한 행씩 반환합니다. 각 반환 값은 튜플 형식이며, 각 열의 값을 나타냅니다.2. fetchall() 함수 사용fetchall() 함수는 결과 세트의 모든 행을 한 번에 리스트 형식으로 반환합니다


Django 클래스 뷰 프로그래밍 개요 (Python, Django, View)

클래스 뷰는 다음과 같은 장점을 제공합니다.코드 재사용성 향상: 공통 로직을 한 번 작성하고 상속을 통해 여러 뷰에서 재사용할 수 있습니다.코드 가독성 향상: 뷰 로직이 명확하게 구분되어 코드를 이해하기 쉽습니다.유지 관리 용이성 향상: 코드 변경이 필요할 경우 한 곳만 변경하면 모든 관련 뷰에 영향을 미칠 수 있습니다


Python과 MySQL 프로그래밍 개요

Python은 다양한 분야에서 활용되는 강력하고 유연한 프로그래밍 언어입니다. MySQL은 가장 인기 있는 오픈 소스 관계형 데이터베이스 관리 시스템(RDBMS) 중 하나입니다. 두 기술을 함께 사용하면 웹 애플리케이션


Python itertools.groupby() 사용법

사용 방법:itertools 모듈 임포트:groupby() 함수 호출:iterable: 그룹화할 대상이 되는 반복 가능한 객체 (리스트, 문자열, 튜플 등)key_func: 각 요소의 키를 결정하는 함수 (선택 사항)


파이썬에서 기존 객체 인스턴스에 메서드 추가하기

파이썬에서 기존 객체 인스턴스에 메서드를 추가하는 방법은 두 가지가 있습니다.setattr() 함수 사용: 객체의 __dict__ 속성에 메서드를 직접 추가합니다.데코레이터 사용: 메서드를 정의하고 데코레이터를 사용하여 인스턴스에 동적으로 바인딩합니다