Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.LeakyReLU function

PyTorch torch.nn.LeakyReLU function

PyTorch torch.nn Reference Manual 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

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

)

print

(

"Input:"

,

x.

tolist

(

)

)

print

(

"Output:"

,

output.

tolist

(

)

)

print

(

"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

)

print

(

"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

print

(

"Non-zero ratio after ReLU:"

,

(

relu

(

x

)

!=

0

)

.

float

(

)

.

mean

(

)

.

item

(

)

)

LeakyReLU has gradients

print

(

"Non-zero ratio after LeakyReLU:"

,

(

lrelu

(

x

)

!=

0

)

.

float

(

)

.

mean

(

)

.

item

(

)

)


Use Cases


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual