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

PyTorch torch.nn.ReLU function

PyTorch torch.nn.ReLU function

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


torch.nn.ReLU is one of the most commonly used activation functions in PyTorch. It applies the Rectified Linear Unit operation element-wise to the input tensor.

ReLU is one of the most successful activation functions in deep learning because it is simple to compute, converges quickly, and effectively alleviates the vanishing gradient problem.

Function definition



torch.nn.ReLU(inplace=False)

Parameter Description:

Mathematical principle

nn.ReLU The computation formula is as follows:



f(x) = max(0, x)

That is, for each element in the input, if the value is greater than 0, it is kept unchanged; if the value is less than or equal to 0, the output is 0.

This simple nonlinear transformation enables the network to learn complex patterns while maintaining gradient flow.


Usage examples

Example 1: Basic usage

Create a ReLU activation layer and apply it to the input:

Example

import

torch

import

torch.

nn

as

nn

Create a ReLU activation layer

relu

=

nn.

ReLU

(

)

Create an input tensor containing negative values

input_tensor

=

torch.

tensor

(

[

[

1.0

,

2.0

,

3.0

]

,

[

4.0

,

5.0

,

6.0

]

]

)

Forward propagation

output

=

relu

(

input_tensor

)

print

(

"Input:n"

,

input_tensor

)

print

(

"Output:n"

,

output

)

The output is:



输入:

 tensor([[-1.,  2., -3.],

        [ 4., -5.,  6.]])

输出:

 tensor([[0., 2., 0.],

        [4., 0., 6.]])

As you can see, all negative values are set to 0, while positive values remain unchanged.

Example 2: In-place operation

Using the inplace parameter can save memory:

Example

import

torch

import

torch.

nn

as

nn

Create a ReLU with in-place operation enabled

relu_inplace

=

nn.

ReLU

(

inplace

=

True

)

Create an input tensor

input_tensor

=

torch.

randn

(

2

,

4

)

original_id

=

id

(

input_tensor

)

Modify in place

output

=

relu_inplace

(

input_tensor

)

Check whether the original tensor was modified

print

(

"Was the original tensor modified:"

,

id

(

output

)

==

original_id

)

print

(

"Input/Output:n"

,

input_tensor

)

The output is:



是否修改了原张量: True

Input/Output:

 tensor([[0.0000, 0.0000, 1.2345, 0.0000],

        [0.5432, 0.0000, 0.0000, 2.3456]])

Note: In-place operations can save memory, but may affect gradient computation in some cases. In the early stages of training or when you need to preserve intermediate activation values, it is recommended to use the default inplace=False.

Example 3: Use in a neural network

In convolutional neural networks, ReLU usually follows a convolutional layer:

Example

import

torch

import

torch.

nn

as

nn

Define a simple convolutional neural network

class

SimpleCNN

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

SimpleCNN

,

self

)

.

init

(

)

       

Convolutional layer: 3 input channels, 32 output channels, 3x3 kernel

       

self

.

conv1

=

nn.

Conv2d

(

3

,

32

,

kernel_size

=

3

,

padding

=

1

)

       

ReLU activation

       

self

.

relu1

=

nn.

ReLU

(

)

       

Second convolutional layer

       

self

.

conv2

=

nn.

Conv2d

(

32

,

64

,

kernel_size

=

3

,

padding

=

1

)

       

self

.

relu2

=

nn.

ReLU

(

)

       

Pooling layers

       

self

.

pool

=

nn.

MaxPool2d

(

2

,

2

)

   

def

forward

(

self

,

x

)

:

        x

=

self

.

conv1

(

x

)

        x

=

self

.

relu1

(

x

)

        x

=

self

.

pool

(

x

)

        x

=

self

.

conv2

(

x

)

        x

=

self

.

relu2

(

x

)

        x

=

self

.

pool

(

x

)

       

return

x

Create the model

model

=

SimpleCNN

(

)

Print the model structure

print

(

"Model structure:"

)

print

(

model

)

Test the forward pass

Simulate a 3x32x32 color image

input_image

=

torch.

randn

(

1

,

3

,

32

,

32

)

output

=

model

(

input_image

)

print

(

"nInput shape:"

,

input_image.

shape

)

print

(

"Output shape:"

,

output.

shape

)

The output is:



Model structure:

SimpleCNN(

  (conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

  (relu1): ReLU()

  (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

  (relu2): ReLU()

  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)

)



输入形状: torch.Size([1, 3, 32, 32])

输出形状: torch.Size([1, 64, 8, 8])

Example 4: Using nn.functional.relu

PyTorch also provides a functional interface torch.nn.functional.relu:

Example

import

torch

import

torch.

nn

.

functional

as

F

Use the functional interface

input_tensor

=

torch.

randn

(

1

,

5

,

5

)

Method 1: Use the functional interface

output1

=

F.

relu

(

input_tensor

)

Method 2: Use the inplace version of the function

F.

relu_

(

input_tensor

)

print

(

"Output:n"

,

output1

)

The difference between the two:


Comparison with other activation functions

Activation function Formula Feature Applicable scenarios
nn.ReLU max(0, x) Simple computation, sparse activation General deep learning (default choice)
nn.LeakyReLU x > 0 ? x : 0.01x Small gradient on the negative axis Prevents "dead neurons"
nn.GELU x * Φ(x) Smooth approximation, default for Transformer Transformer, BERT, etc.
nn.Sigmoid 1/(1+e^(-x)) Output 0-1, gradients saturate Output layers, binary classification
nn.Tanh (e^x - e^(-x))/(e^x + e^(-x)) Output -1 to 1, zero-centered RNN, LSTM

Common questions

Q1: Why does ReLU cause the "dead neurons" problem?

When the input is consistently negative, ReLU's output is always 0 and the gradient is also 0, causing these neurons to stop learning.

Solutions:

Q2: Is ReLU suitable for the output layer?

Usually not. Output layers more commonly use Sigmoid(classification) or the identity function (regression), because ReLU's output is unbounded.


Use Cases

nn.ReLU is the most commonly used activation function in deep learning, with main application scenarios including:

Tip: Unless you have special requirements, ReLU is the preferred activation function for hidden layers when designing neural networks.


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