PyTorch torch.nn.LeakyReLU 関数
torch.nn.LeakyReLUPyTorchにおけるリーク付きReLU活性化関数です。
負の値に対して小さな正の勾配を許容し、「死滅ニューロン」問題を回避します。
関数定義
torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)
パラメータ
negative_slope: 負の値の傾き、デフォルトは0.01
式
f(x) = x, x > 0 f(x) = negative_slope * x, x <= 0
使用例
例1: 基本的な使い方
実例
import torch
import torch.nn as nn
lrelu = nn.LeakyReLU(negative_slope=0.1)
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])
output = lrelu(x)
print("入力:", x.tolist())
print("出力:", output.tolist())
print("負の値には小さな正の勾配がある")
import torch.nn as nn
lrelu = nn.LeakyReLU(negative_slope=0.1)
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])
output = lrelu(x)
print("入力:", x.tolist())
print("出力:", output.tolist())
print("負の値には小さな正の勾配がある")
例2: GANでの使用
実例
import torch
import torch.nn as nn
# GAN生成器でよく使われるLeakyReLU
generator = nn.Sequential(
nn.Linear(100, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 784),
nn.Tanh()
)
z = torch.randn(4, 100)
output = generator(z)
print("入力:", z.shape, "-> 出力:", output.shape)
import torch.nn as nn
# GAN生成器でよく使われるLeakyReLU
generator = nn.Sequential(
nn.Linear(100, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 784),
nn.Tanh()
)
z = torch.randn(4, 100)
output = generator(z)
print("入力:", z.shape, "-> 出力:", output.shape)
例3: 死滅ニューロンの防止
実例
import torch
import torch.nn as nn
# ReLUとLeakyReLUの比較
relu = nn.ReLU()
lrelu = nn.LeakyReLU()
# 負の値の入力
x = torch.randn(10, 100) - 5
# ReLU出力はすべて0
print("ReLU後の非ゼロ比率:", (relu(x) != 0).float().mean().item())
# LeakyReLUには勾配がある
print("LeakyReLU後の非ゼロ比率:", (lrelu(x) != 0).float().mean().item())
import torch.nn as nn
# ReLUとLeakyReLUの比較
relu = nn.ReLU()
lrelu = nn.LeakyReLU()
# 負の値の入力
x = torch.randn(10, 100) - 5
# ReLU出力はすべて0
print("ReLU後の非ゼロ比率:", (relu(x) != 0).float().mean().item())
# LeakyReLUには勾配がある
print("LeakyReLU後の非ゼロ比率:", (lrelu(x) != 0).float().mean().item())
使用シーン
- GAN: 生成器、判別器
- 死滅ニューロンの防止
- スパースネットワーク
その他の拡張