Neural network foundations · Day 11
Activation functions: give your network its shape
Understand ReLU, sigmoid, tanh and softmax. Follow the original Keras example, compare the curves and choose an output that fits your task.

Contents
Complete preserved original
The complete historical lesson follows in its original order. The separately labeled guide below adds checked calculations and qualifies several claims without replacing this text. Original embedded document titles are retained as small source labels.
Activation Functions in Neural Networks
Activation Functions in Neural Networks: Why They Matter ?
Activation functions are pivotal in neural networks, transforming the input of each neuron to its output signal, thus determining the neuron’s activation level. This process allows neural networks to handle tasks such as image recognition and language processing effectively.
The Role of Different Activation Functions
Neural networks employ distinct activation functions in their inner and outer layers, customized to the specific requirements of the network:
- Inner Layers: Functions like ReLU (Rectified Linear Unit) introduce necessary non-linearity, allowing the network to learn complex patterns in the data. Without these functions, neural networks would not be able to model anything beyond simple linear relationships.
- Outer Layers: Depending on the task, different functions are used. For example, a softmax function is used for multiclass classification to convert the logits to probabilities that sum to one, which are essential for classification tasks.
Practical Application
Understanding the distinction and application of different activation functions is crucial for designing networks that perform efficiently across various tasks.
Neural Network Configuration Example
Building a Neural Network for Image Classification
This example demonstrates setting up a neural network in Python using TensorFlow/Keras, designed to classify images into three categories.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
model = Sequential([
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(64, 64, 3)),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(64, kernel_size=(3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
The code above outlines each step in constructing the network, from input to output, detailing how each layer contributes to the task of image classification. The use of ‘relu’ in hidden layers and ‘softmax’ in the output layer optimizes the model for accuracy and efficiency.
Activation Functions in Neural Networks
| Activation Function | Formula | Used in Layer | Purpose | Linearity |
|---|---|---|---|---|
| Sigmoid | σ(x) = 1 / (1 + e−x) | Output | Maps input to the range (0, 1), useful for binary classification. | Non-linear |
| Softmax | Softmax(xi) = exᵢ / Σj exⱼ | Output | Converts logits to probabilities for multiclass classification. | Non-linear |
| Tanh | tanh(x) = (ex − e−x) / (ex + e−x) | Hidden | Maps values between -1 and 1, zero-centered. | Non-linear |
| ReLU | f(x) = max(0, x) | Hidden | Replaces negative values with 0, allowing for faster convergence. | Non-linear |
| Leaky ReLU | f(x) = max(0.01x, x) | Hidden | Allows a small, non-zero output for negative inputs. | Non-linear |
| PReLU | f(x) = max(αx, x) | Hidden | Parameter α is learnable, improving learning dynamics. | Non-linear |
| ELU | f(x) = x if x > 0 else α(ex − 1) | Hidden | Controls the vanishing gradient problem by outputting values below zero for negative inputs. | Non-linear |
| modSwish | f(x) = x · σ(βx) | Hidden | A modified version of Swish, continuously differentiable and non-monotonic. | Non-linear |
Added explanation · checked 16 November 2026
From a weighted sum to a useful prediction
A neuron first computes a preactivation: multiply each input by a weight, add the results, then add a bias. The activation maps that number to the value passed onward. The weights learn which combinations matter; the activation controls the shape of the response. Hidden activations make the model flexible, while an output activation expresses the task’s constraints.
z = w₁x₁ + w₂x₂ + b
a = f(z)
For x₁ = 2, x₂ = −1, w₁ = 0.5, w₂ = 1 and b = 0.2, the preactivation is 0.2. ReLU produces 0.2; sigmoid produces approximately 0.549834. The same weighted sum therefore has different interpretations depending on the activation. A sigmoid value could represent a modeled binary probability, but this alone does not establish good calibration.
Why stacking linear layers is insufficient
Consider a first layer h = 2x + 1 and a second layer y = 3h − 4. Substitution gives y = 6x − 1. Two affine transformations collapse into one affine transformation, including their biases. More such layers do not create curved decision boundaries by themselves. A nonlinear hidden activation prevents this collapse in general. Nonlinearity is necessary for that added expressive power, but is not a guarantee of generalization.
W₂(W₁x + b₁) + b₂
= (W₂W₁)x + (W₂b₁ + b₂)
ReLU is piecewise linear: each side is linear, but its slope changes at zero. A network can combine many such regions. This is why calling ReLU nonlinear is compatible with drawing it as two straight segments. At zero it has no ordinary derivative; frameworks choose a convention for backpropagation.
Read the activation and derivative plots together
The sigmoid curve approaches zero or one at extreme inputs; tanh approaches minus one or one. Their derivatives become small in these saturated regions. During backpropagation, repeated multiplication by small derivatives can weaken the learning signal. At z = 0, sigmoid’s derivative is 0.25; at z = 6 it is approximately 0.00246651. The plotted values were computed directly, not measured during a training experiment.
σ′(z) = σ(z)(1 − σ(z))
tanh′(z) = 1 − tanh²(z)
ReLU has derivative one on its positive side and zero on its negative side. A unit that stays negative across its training inputs can stop receiving a useful activation gradient. Leaky ReLU preserves a chosen negative-side slope; PReLU learns that slope. Neither makes optimization failure impossible. The plot uses slope 0.1 for visibility; the original table’s 0.01 is retained as a different valid choice.
Choose the output activation and loss together
Start with what one target means. Is it a real-valued number, one class among alternatives, or several independent labels? This determines the output width, target encoding and loss. Hidden-layer choices can then be tested on a validation set while the final test set remains untouched.
| Task | Output | Target and loss |
|---|---|---|
| Unbounded regression | One linear unit per numeric target | Real targets; an appropriate regression loss such as mean squared error |
| Binary classification | One sigmoid unit | Zero/one target; binary cross-entropy |
| Exclusive multiclass classification | One softmax unit per class | Integer class indices with sparse categorical cross-entropy, or one-hot targets with categorical cross-entropy |
| Independent multilabel classification | One sigmoid unit per label | Separate zero/one targets; binary cross-entropy per label |
Softmax couples the outputs: increasing one logit affects all class probabilities. It is appropriate when exactly one of the modeled classes is the target. Independent sigmoid outputs do not have to sum to one and suit labels that can coexist. A regression target with a known range may justify a bounded output, but sigmoid is not a universal regression default.
A stable softmax worked example
For logits [2, 1, 0], subtract the largest logit before exponentiating. The resulting probabilities are approximately [0.665241, 0.244728, 0.090031]. They sum to one. If the true class is the first one, negative log likelihood is approximately 0.407606. Subtracting the same constant from every logit leaves the result unchanged and avoids unnecessarily large exponentials.
m = maxⱼ zⱼ
pᵢ = exp(zᵢ − m) / Σⱼ exp(zⱼ − m)
Loss for true class k = −log(pₖ)
Another valid implementation returns logits directly and uses a loss configured with from_logits=True. Do not accidentally treat probabilities as logits or apply softmax twice. The retained original code uses softmax and the probability-based default of sparse categorical cross-entropy. Its labels must be integer class IDs 0, 1 or 2. Compiling a model defines the training configuration; it does not train it.
Technical notes on the preserved original
The original wording, code and table remain above. These notes qualify historical claims separately so you can compare the explanation with the underlying mathematics.
- Accuracy and convergence: ReLU and softmax are sensible choices for the illustrated task, but they do not establish accuracy, efficiency or faster convergence for a dataset that has not been tested. Use measured validation results to compare models.
- ELU and vanishing gradients: ELU permits negative activations, but its negative-side derivative is α exp(z). For α = 1 and z = −6 it is approximately 0.00247875. It therefore also saturates; it does not eliminate vanishing gradients by construction.
- PReLU formula: The general definition is αx for x < 0 and x for x ≥ 0. The original max(αx, x) expression agrees when 0 ≤ α ≤ 1, but does not describe an unconstrained learned α in general. For α = 2 and x = −1, the piecewise definition gives −2, while max(−2, −1) gives −1.
- “modSwish” naming: The displayed xσ(βx) is the parameterized Swish form. β = 1 gives the SiLU/Swish form used in common libraries. The name in the original table is preserved; it does not establish a distinct new activation. Nonmonotonic behavior depends on the parameter; β = 0 yields x/2.
- Hidden versus output layers: The table describes common placements, not restrictions. Sigmoid and tanh can also be hidden activations. Output choice follows the target and loss.
What the original Keras code actually constructs
With default valid padding and channels-last layout, the 64 × 64 × 3 input becomes 62 × 62 × 32 after the first convolution, then 31 × 31 × 32 after pooling. The second convolution gives 29 × 29 × 64 and pooling gives 14 × 14 × 64. Flattening creates 12,544 features, followed by 128 hidden units and three class outputs.
Counting a bias per convolutional filter and dense unit gives 896, 18,496, 1,605,760 and 387 trainable parameters across the four parameterized layers, totaling 1,625,539. Most are in the first dense layer. This count is a manual architecture calculation checked in Python; it is not a captured TensorFlow summary.
Execution disclosure: The original Python code passes a syntax check. TensorFlow is unavailable in this verification environment, so its model construction, summary and training were not executed. The original does not provide training images, labels, a fit call or a test evaluation. No measured accuracy is claimed. The added NumPy calculations and plotted curves were executed. In current Keras examples an explicit Input layer is commonly used; the original input_shape spelling remains unchanged for preservation.
Practice before moving on
- Compute sigmoid at zero and explain why its derivative there is 0.25.
- Change every logit in [2, 1, 0] by +1000. Explain why stable softmax returns the same probabilities.
- Choose outputs for an image with one animal class, then for a photo that may contain several objects.
- Explain why learning α makes PReLU different from choosing a fixed leaky slope.
- Find which layer dominates the original model’s parameter count and suggest a smaller architecture to test. Treat it as a hypothesis until validated.
Primary references and further study
These references support the added definitions and implementation guidance. Checked 16 November 2026. They do not replace the original explanation or prove an accuracy result.
Questions about activation functions
What does an activation function do?
It maps a neuron’s weighted input plus bias to its output. Nonlinear hidden activations let a network represent more than a composition of affine transformations.
Which activation should I use for three exclusive classes?
A three-unit softmax output can represent the class probabilities. Use sparse categorical cross-entropy with integer labels, or categorical cross-entropy with one-hot labels.
Does ReLU guarantee better accuracy?
No. ReLU is a common hidden-layer choice, but accuracy and convergence depend on data, architecture, initialization and training. Compare validation results.
What is the difference between Leaky ReLU and PReLU?
Leaky ReLU uses a chosen negative-side slope. PReLU learns the negative-side slope as a model parameter.
Does ELU eliminate vanishing gradients?
No. Its negative-side derivative can become very small for strongly negative inputs, so it does not eliminate vanishing gradients.
Was the original TensorFlow model trained for this lesson?
No. Its code was syntax-checked, but TensorFlow was unavailable for execution. The added NumPy calculations and plots were executed; no model accuracy result is claimed.
