ReLU의 대안, Leaky ReLU

ReLU의 대안, Leaky ReLU
Photo by Luca Bravo / Unsplash

사실 너무나도 오래된 Activatio Function이지만, 복기 차원에서 정리해보았음

Leaky ReLU is

  • Leaky ReLU(Leaky Rectified Linear Unit)는 ReLU(Rectified Linear Unit)의 변형으로, ReLU의 단점을 보완하기 위해 고안
    $$ \text{Leaky ReLU}(x) = \begin{cases} x & \text{if } x > 0 \ \alpha x & \text{if } x \leq 0 \end{cases} $$
  • 여기서 α는 작은 양수 값으로, 일반적으로 0.01로 설정
    • 입력 값이 음수일 때 작은 기울기를 제공하여 dead ReLU problem 완화

Pros

  • Dead ReLU Problem 완화: Leaky ReLU는 음수 입력에 대해 작은 기울기를 가지므로 뉴런이 활성화되지 않는 문제를 줄여줌.
  • 비선형성 유지: Leaky ReLU는 비선형성을 제공하여 신경망이 복잡한 패턴을 학습할 수 있음
  • 단순한 구현: ReLU와 유사한 형태로 구현이 간단함

Cons

  • 고정된 기울기: α 값이 고정되어 있어 최적의 기울기를 찾는 데 한계가 있을 수 있을 수 있음
  • 과적합 가능성: 작은 기울기가 모든 문제에 적합하지 않을 수 있으며, 일부 경우에는 과적합을 초래할 수 있음
    

Alternatives

  • ReLU: 입력 값이 양수일 때는 그대로 출력하고, 음수일 때는 0을 출력
  • Parametric ReLU (PReLU): α값을 학습 가능한 파라미터로 만들어 최적의 기울기를 찾음
  • Exponential Linear Unit (ELU): 음수 입력에 대해 지수 함수를 적용
  • Scaled Exponential Linear Unit (SELU) 자동으로 수렴을 보장하고 정규화된 출력을 제공하여 깊은 신경망에서 특히 유용

Sample Code

import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split

# 데이터 생성
X, y = make_moons(n_samples=1000, noise=0.2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# PyTorch 텐서로 변환
X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)
y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)

# 모델 정의
class SimpleNN(nn.Module):
    def __init__(self, activation_fn):
        super(SimpleNN, self).__init__()
        self.layer1 = nn.Linear(2, 64)
        self.layer2 = nn.Linear(64, 64)
        self.layer3 = nn.Linear(64, 2)
        self.activation_fn = activation_fn

    def forward(self, x):
        x = self.activation_fn(self.layer1(x))
        x = self.activation_fn(self.layer2(x))
        x = self.layer3(x)
        return x

# 모델 생성 (ReLU와 Leaky ReLU 비교)
relu_model = SimpleNN(nn.ReLU())
leaky_relu_model = SimpleNN(nn.LeakyReLU(0.01))

# 손실 함수와 옵티마이저 정의
criterion = nn.CrossEntropyLoss()
relu_optimizer = optim.Adam(relu_model.parameters(), lr=0.01)
leaky_relu_optimizer = optim.Adam(leaky_relu_model.parameters(), lr=0.01)

# 모델 학습 함수
def train_model(model, optimizer, X_train, y_train, epochs=100):
    model.train()
    losses = []
    for epoch in range(epochs):
        optimizer.zero_grad()
        outputs = model(X_train)
        loss = criterion(outputs, y_train)
        loss.backward()
        optimizer.step()
        losses.append(loss.item())
    return losses

# 모델 평가 함수
def evaluate_model(model, X_test, y_test):
    model.eval()
    with torch.no_grad():
        outputs = model(X_test)
        _, predicted = torch.max(outputs, 1)
        accuracy = (predicted == y_test).float().mean().item()
    return accuracy

# 모델 학습
relu_losses = train_model(relu_model, relu_optimizer, X_train, y_train)
leaky_relu_losses = train_model(leaky_relu_model, leaky_relu_optimizer, X_train, y_train)

# 모델 평가
relu_accuracy = evaluate_model(relu_model, X_test, y_test)
leaky_relu_accuracy = evaluate_model(leaky_relu_model, X_test, y_test)

print(f'ReLU Test Accuracy: {relu_accuracy}')
print(f'Leaky ReLU Test Accuracy: {leaky_relu_accuracy}')

# 학습 곡선 시각화
plt.plot(relu_losses, label='ReLU Loss')
plt.plot(leaky_relu_losses, label='Leaky ReLU Loss')
plt.legend()
plt.title('ReLU vs Leaky ReLU Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()

# 예측 결과 시각화
def plot_decision_boundary(model, X, y, ax):
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = torch.meshgrid(torch.arange(x_min, x_max, 0.01), torch.arange(y_min, y_max, 0.01))
    grid = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1)], dim=1)
    with torch.no_grad():
        pred = model(grid).argmax(dim=1).reshape(xx.shape).numpy()
    ax.contourf(xx, yy, pred, alpha=0.5)
    ax.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k')

fig, ax = plt.subplots(1, 2, figsize=(12, 6))
plot_decision_boundary(relu_model, X_test.numpy(), y_test.numpy(), ax[0])
ax[0].set_title('ReLU Decision Boundary')
plot_decision_boundary(leaky_relu_model, X_test.numpy(), y_test.numpy(), ax[1])
ax[1].set_title('Leaky ReLU Decision Boundary')
plt.show()

Read more

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

장강명 작가의 책은, 유학시절 읽고 처음이었다. 유학시절 "한국이 싫어서"라는 책은 동기부여가 상당히 되는 책이었다. 한국을 떠나 새로운 정채성을 학생으로서 Build up 해나가고 있던 상황에서 이 책은 제목부터 꽤 솔깃하였다. 물론 결말이 기억날 정도로 인상깊은 책은 아니었지만 말이다. 그렇게 시간이 흘러 장강명 작가의 책은 더 이상 읽지 않던

By Bongho, Lee
고객 경험이란 무엇일까?

고객 경험이란 무엇일까?

고객경험이란 무엇일까? 1. 과거 어느 대형 프로젝트에서 있던 일이다. 신사업을 위해서 예측 모델 값을 제공해야 하는 상황이었다. 데이터도 없고,어느정도의 정확도를 제공해야 하는지 답이 없었다. 점추정을 할 것인가? 구간 추정을 할 것인가를 가지고 논의중이었다. Product Manager 줄기차게 고객경험을 내세우며 점추정으로 해야 한다고 주장하였다. 근거는 오롯이 "고객 경험"이었다.

By Bongho, Lee
수요예측, 수정구슬이 아닌 목표를 향한 냉정한 나침반

수요예측, 수정구슬이 아닌 목표를 향한 냉정한 나침반

수요예측의 정의와 비즈니스에서의 중요성 기업의 성장과 운영 효율화를 위해 **수요예측(Demand Forecasting)**은 선택이 아닌 필수 요소로 자리 잡았다. 많은 경영진들이 수요예측을 미래 판매량을 정확히 맞히는 '예언'으로 기대하지만, 이는 수요예측의 본질을 오해하는 것이다. 수요예측의 진짜 의미: 미래를 점치는 수정구슬이 아니라, 우리가 도달해야 할 '목표'를

By Bongho, Lee