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

[책]Reshuffle: Who wins when AI restacks the knowledge economy

[책]Reshuffle: Who wins when AI restacks the knowledge economy

원래는 Amazon에 가서 Personal Knowledge Managment에 관한 책을 사려고 했다. Sketch Your Mind라는 책이었는데, 그 때 이 책 “Reshuffle”을 발견하였다. AI가 어떻게 Knowledge Economy를 흔들 것가? 라는 부제를 훑어보면서 저자가 쓴 다른 책을 보게 되었는데 거기에 내가 좋아했던 책을쓴 저자라는 것을 알게 되었다. 그래서 크게 고민하지 않고 구매를 하고

By Bongho, Lee
[책]올라운드투자, 누군가의 투자일기

[책]올라운드투자, 누군가의 투자일기

“올라운드 투자”라는 제목을 보았을 때는, “올라운드 플레이어”가 생각이 났다. “올라운드”라는 표현을 오랜만에 들어본 까닭이었다. 그럼에도 불구하고 이 책을 고른 것은 저자가 그간 보여준 컨텐츠에 대한 신뢰가 있던 까닭이었다. 컨텐츠를 다양하게 보는 편이지만 깊이가 아주 있지는 않았다. 여기서 깊이라 함은 기존 전문적인 정량적 분석의 내용의 수준을 말하는 것이다.

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

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

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

By Bongho, Lee