Python / PyTorch Fundamentals Interview Questions
What are activation functions in PyTorch and how do you apply them?
Activation functions introduce non-linearity into neural networks, enabling them to learn complex mappings. PyTorch provides them both as nn.Module classes (usable as layers) and as functional forms in torch.nn.functional.
| Function | Formula | Typical use |
|---|---|---|
| ReLU | max(0, x) | Default for hidden layers (fast, avoids vanishing grad) |
| LeakyReLU | max(αx, x), α≈0.01 | When dying ReLU is a problem |
| Sigmoid | 1/(1+e^−x) → (0,1) | Binary classification output |
| Tanh | (e^x−e^−x)/(e^x+e^−x) → (−1,1) | RNNs, zero-centred alternative to sigmoid |
| Softmax | e^xᵢ/Σe^xⱼ → sums to 1 | Multi-class output (use with NLLLoss) |
| GELU | x·Φ(x) smooth | Transformers (BERT, GPT) |
| SiLU/Swish | x·sigmoid(x) | Modern architectures (EfficientNet) |
import torch import torch.nn as nn import torch.nn.functional as F x = torch.tensor([-2., -1., 0., 1., 2.]) # ââ As nn.Module (use inside nn.Sequential or __init__) relu = nn.ReLU() print(relu(x)) # [0, 0, 0, 1, 2] sigmoid = nn.Sigmoid() print(sigmoid(x)) # [0.12, 0.27, 0.50, 0.73, 0.88] # ââ As functional (use inside forward()) print(F.relu(x)) # same as nn.ReLU()(x) print(F.gelu(x)) # smooth approximation # Softmax: dim must be specified! logits = torch.randn(4, 10) # (batch=4, classes=10) probs = F.softmax(logits, dim=1) # dim=1 (classes) print(probs.sum(dim=1)) # tensor([1., 1., 1., 1.]) # !! Never apply Softmax before CrossEntropyLoss !! # CrossEntropyLoss = LogSoftmax + NLLLoss internally # Applying softmax first â double-softmax = wrong! loss_fn = nn.CrossEntropyLoss() loss = loss_fn(logits, torch.randint(0, 10, (4,))) # pass raw logits!
More Related questions...