Activation and Loss Functions

Picking activations for hidden and output layers and matching the loss function to the prediction task.

Intermediate · about 3 hours · difficulty 2/5

Learn first: Backpropagation and Autograd

Activations give networks nonlinearity; the output activation and loss must match the task. Mismatches (for example softmax plus MSE for classification) train poorly or not at all.

Hidden activations

  • ReLU: simple, fast, the historical default. Can produce dead units.
  • Leaky ReLU / ELU: small slope for negatives to avoid dead units.
  • GELU / SiLU (Swish): smooth variants used in transformers and modern CNNs.
  • Sigmoid and tanh: saturate and cause vanishing gradients in deep stacks; still used for gates in LSTMs.

Output layer plus loss

  • Regression: linear output + MSE, MAE or Huber loss.
  • Binary classification: one logit + binary cross-entropy (use the with-logits version for numerical stability).
  • Multiclass: logits + softmax cross-entropy. In PyTorch, nn.CrossEntropyLoss expects raw logits, not probabilities.
  • Multi-label: independent sigmoid per label + BCE.
  • Specialized losses: focal loss for imbalance, contrastive and triplet losses for embeddings.

Good enough to move on when, given any prediction target, you can choose the output layer and loss and explain why applying softmax before CrossEntropyLoss is a bug.

Key concepts

  • ReLU and variants
  • GELU and SiLU
  • Sigmoid, tanh and saturation
  • Cross-entropy with logits
  • Regression losses
  • Focal and contrastive losses

Mini project

Train the same small MLP on Fashion-MNIST with sigmoid, tanh, ReLU and GELU activations and plot training loss curves side by side.

Check yourself

Which output activation and loss would you use for tagging an image with any of 20 non-exclusive labels?

Free resources