PyTorch torch.nn.LeakyReLU function
PyTorch torch.nn Reference Manual
torch.nn.LeakyReLU is the leaky ReLU activation function in PyTorch.
It allows a small positive gradient for negative values, avoiding the "dead neuron" problem.
Function definition
torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)
Parameters
negative_slope: slope for negative values, default 0.01
Formula
f(x) = x, x > 0
f(x) = negative_slope * x, x <= 0
Usage examples
Example 1: Basic usage
Example
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
)
(
"Input:"
,
x.
tolist
(
)
)
(
"Output:"
,
output.
tolist
(
)
)
(
"Negative values have a small positive gradient"
)
Example 2: Using it in a GAN
Example
import
torch
import
torch.
nn
as
nn
GAN generators often use 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
)
(
"Input:"
,
z.
shape
,
"-> Output:"
,
output.
shape
)
Example 3: Preventing dead neurons
Example
import
torch
import
torch.
nn
as
nn
Comparing ReLU and LeakyReLU
relu
=
nn.
ReLU
(
)
lrelu
=
nn.
LeakyReLU
(
)
Negative input
x
=
torch.
randn
(
10
,
100
)
5
ReLU outputs all zeros
(
"Non-zero ratio after ReLU:"
,
(
relu
(
x
)
!=
0
)
.
float
(
)
.
mean
(
)
.
item
(
)
)
LeakyReLU has gradients
(
"Non-zero ratio after LeakyReLU:"
,
(
lrelu
(
x
)
!=
0
)
.
float
(
)
.
mean
(
)
.
item
(
)
)
Use Cases
- GAN: generators, discriminators
- Preventing dead neurons
- Sparse networks