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!
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
