Bird
Raised Fist0
PyTorchml~5 mins

Activation functions (ReLU, Sigmoid, Softmax) in PyTorch

Choose your learning style10 modes available
Introduction

Activation functions help a neural network learn complex patterns by adding non-linearity. They decide if a neuron should be activated or not.

When building a neural network to classify images.
When predicting probabilities for binary classification.
When you want to pick the most likely class from many options.
When you want to avoid negative outputs in your model.
When you want to squash outputs between 0 and 1.
Syntax
PyTorch
import torch
import torch.nn.functional as F

# ReLU activation
relu_output = F.relu(input_tensor)

# Sigmoid activation
sigmoid_output = torch.sigmoid(input_tensor)

# Softmax activation
softmax_output = F.softmax(input_tensor, dim=1)

ReLU sets negative values to zero and keeps positive values unchanged.

Softmax is used for multi-class outputs and requires specifying the dimension.

Examples
ReLU turns negative values to zero, so output is [0.0, 0.0, 2.0].
PyTorch
import torch
import torch.nn.functional as F

input_tensor = torch.tensor([-1.0, 0.0, 2.0])
relu_output = F.relu(input_tensor)
print(relu_output)
Sigmoid squashes values between 0 and 1, useful for probabilities.
PyTorch
import torch
input_tensor = torch.tensor([-1.0, 0.0, 2.0])
sigmoid_output = torch.sigmoid(input_tensor)
print(sigmoid_output)
Softmax converts scores to probabilities that sum to 1 across classes.
PyTorch
import torch
import torch.nn.functional as F

input_tensor = torch.tensor([[1.0, 2.0, 3.0]])
softmax_output = F.softmax(input_tensor, dim=1)
print(softmax_output)
Sample Model

This program creates a simple neural network with one layer. It applies ReLU, Sigmoid, and Softmax activations to the layer's output. It prints the results for two input samples.

PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(4, 3)  # 4 inputs to 3 outputs

    def forward(self, x):
        x = self.fc1(x)
        relu_out = F.relu(x)
        sigmoid_out = torch.sigmoid(x)
        softmax_out = F.softmax(x, dim=1)
        return relu_out, sigmoid_out, softmax_out

# Create model
model = SimpleNet()

# Sample input: batch of 2 samples, each with 4 features
input_data = torch.tensor([[1.0, 2.0, 3.0, 4.0],
                           [4.0, 3.0, 2.0, 1.0]])

relu_out, sigmoid_out, softmax_out = model(input_data)

print("ReLU output:", relu_out)
print("Sigmoid output:", sigmoid_out)
print("Softmax output:", softmax_out)
OutputSuccess
Important Notes

ReLU is simple and fast, but can cause some neurons to stop learning if they output zero all the time.

Sigmoid is good for binary outputs but can slow learning if values saturate near 0 or 1.

Softmax is best for multi-class classification where outputs represent probabilities.

Summary

Activation functions add non-linearity so neural networks can learn complex patterns.

ReLU sets negative values to zero, Sigmoid squashes values between 0 and 1, Softmax turns scores into probabilities.

Choose activation based on your task: ReLU for hidden layers, Sigmoid for binary output, Softmax for multi-class output.

Practice

(1/5)
1. Which activation function is best suited for the output layer of a binary classification model in PyTorch?
easy
A. Sigmoid
B. ReLU
C. Softmax
D. Tanh

Solution

  1. Step 1: Understand the output requirements for binary classification

    Binary classification outputs a probability between 0 and 1 for one class, so the activation must squash values into this range.
  2. Step 2: Match activation functions to output needs

    Sigmoid outputs values between 0 and 1, making it ideal for binary classification outputs. ReLU outputs zero or positive values without upper bound, Softmax is for multi-class, and Tanh outputs between -1 and 1.
  3. Final Answer:

    Sigmoid -> Option A
  4. Quick Check:

    Binary output needs probability = Sigmoid [OK]
Hint: Binary output? Use Sigmoid for probability between 0 and 1 [OK]
Common Mistakes:
  • Choosing ReLU which doesn't limit output to 0-1
  • Using Softmax for binary instead of multi-class
  • Confusing Tanh with Sigmoid output range
2. Which of the following is the correct way to apply the ReLU activation function to a tensor x in PyTorch?
easy
A. torch.activation.relu(x)
B. torch.nn.functional.relu(x)
C. torch.nn.ReLU(x)
D. torch.relu(x)

Solution

  1. Step 1: Recall PyTorch ReLU usage

    ReLU can be applied using the functional API or as a module. The functional API call is torch.nn.functional.relu(x).
  2. Step 2: Check each option

    torch.relu(x) is incorrect because torch.relu does not exist. torch.activation.relu(x) is invalid syntax. torch.nn.ReLU(x) tries to call the module directly without instantiation. torch.nn.functional.relu(x) correctly uses the functional API.
  3. Final Answer:

    torch.nn.functional.relu(x) -> Option B
  4. Quick Check:

    Use functional API for ReLU = torch.nn.functional.relu(x) [OK]
Hint: Use torch.nn.functional.relu(x) for direct ReLU call [OK]
Common Mistakes:
  • Trying to call torch.relu which doesn't exist
  • Using torch.nn.ReLU without creating an instance
  • Confusing module and functional API usage
3. What is the output of the following PyTorch code?
import torch
import torch.nn.functional as F
x = torch.tensor([-1.0, 0.0, 2.0])
output = F.relu(x)
print(output.tolist())
medium
A. [-1.0, 0.0, 2.0]
B. [0.0, 1.0, 1.0]
C. [0.0, 0.0, 2.0]
D. [-1.0, 0.0, 0.0]

Solution

  1. Step 1: Understand ReLU behavior on input tensor

    ReLU sets negative values to zero and keeps positive values unchanged.
  2. Step 2: Apply ReLU to each element

    -1.0 becomes 0.0, 0.0 stays 0.0, 2.0 stays 2.0. So output is [0.0, 0.0, 2.0].
  3. Final Answer:

    [0.0, 0.0, 2.0] -> Option C
  4. Quick Check:

    ReLU zeroes negatives = [0.0, 0.0, 2.0] [OK]
Hint: ReLU zeroes negatives, keeps positives same [OK]
Common Mistakes:
  • Leaving negative values unchanged
  • Confusing ReLU with Sigmoid output
  • Assuming ReLU changes zeros to ones
4. The following code aims to apply Softmax to a tensor x along dimension 1 but throws an error. What is the error and how to fix it?
import torch
import torch.nn.functional as F
x = torch.tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])
output = F.softmax(x, dim=2)
print(output)
medium
A. Missing activation import; fix by importing torch.nn
B. Softmax requires 1D tensor; fix by flattening x
C. Softmax cannot be applied to float tensors; convert to int
D. Dimension 2 is out of range for tensor of shape (2,3); fix by using dim=1

Solution

  1. Step 1: Check tensor shape and dimension argument

    Tensor x has shape (2, 3), so valid dims are 0 and 1. Using dim=2 is invalid and causes an error.
  2. Step 2: Correct the dimension argument

    To apply Softmax across columns (features), use dim=1. This fixes the error.
  3. Final Answer:

    Dimension 2 is out of range for tensor of shape (2,3); fix by using dim=1 -> Option D
  4. Quick Check:

    Tensor shape (2,3) means max dim=1 [OK]
Hint: Check tensor shape before choosing dim for Softmax [OK]
Common Mistakes:
  • Using invalid dimension index for Softmax
  • Thinking Softmax needs 1D input only
  • Ignoring error message about dimension out of range
5. You have a multi-class classification problem with 4 classes. Which activation function should you use in the output layer and why?

Choose the best option.
hard
A. Softmax, because it outputs probabilities that sum to 1 across all classes
B. Sigmoid, because it outputs probabilities for each class independently
C. Tanh, because it outputs values between -1 and 1 for better gradients
D. ReLU, because it outputs positive values for all classes

Solution

  1. Step 1: Understand multi-class output requirements

    For multi-class classification, the output layer should produce probabilities for each class that sum to 1, representing a valid probability distribution.
  2. Step 2: Match activation functions to multi-class needs

    Softmax converts raw scores into probabilities that sum to 1 across classes. ReLU does not produce probabilities, Sigmoid treats classes independently (not summing to 1), and Tanh outputs values between -1 and 1, not probabilities.
  3. Final Answer:

    Softmax, because it outputs probabilities that sum to 1 across all classes -> Option A
  4. Quick Check:

    Multi-class needs sum-to-1 probabilities = Softmax [OK]
Hint: Multi-class output? Use Softmax for normalized probabilities [OK]
Common Mistakes:
  • Using Sigmoid which treats classes independently
  • Choosing ReLU which is not probabilistic
  • Confusing Tanh output range with probabilities
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard