Skip to content
E
Educatum

Why is non linear activation function needed?

Curated by Educatum AI teamLast updated:
Neural Networks and Deep LearningNN
Direct Answer

Non-linear activation functions are essential because composing any number of purely linear layers algebraically collapses into a single affine transformation, giving a deep linear network no more expressive power than linear regression. Introducing non-linear, non-polynomial activations such as ReLU, GELU, sigmoid, or tanh breaks this collapse, enabling hierarchical feature composition and curved decision boundaries. By the Universal Approximation Theorem, even a single hidden layer with enough non-polynomial units can approximate any continuous function on a compact domain.

Study Card: Non-linear Activation Functions in Neural Networks

Direct Answer

Non-linear activation functions give neural networks the ability to learn complex, non-linear mappings. Without a non-linear activation (ϕ(z)=z\phi(z) = z), stacking multiple layers achieves no extra representational power at all because linear transformations are closed under composition. For a two-layer network without activations:

y=W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)=Weffx+beff\mathbf{y} = W_2(W_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (W_2 W_1)\mathbf{x} + (W_2 \mathbf{b}_1 + \mathbf{b}_2) = W_{\text{eff}} \mathbf{x} + \mathbf{b}_{\text{eff}}

Regardless of whether the network has 2 layers or 100 layers, it remains equivalent to a single linear/affine model (capable only of hyperplanes). Adding non-linear, non-polynomial activations (such as ReLU, GELU, SiLU, sigmoid, or tanh⁡\tanh) between layers allows the network to warp feature space hierarchically and approximate arbitrary continuous functions on compact domains.

Key Terms

  • Linear Collapse: Algebraic reduction of stacked linear/affine layers WL⋯W1W_L \cdots W_1 into a single effective matrix WeffW_{\text{eff}}.
  • Non-linearity: Any function violating f(ax+by)=af(x)+bf(y)f(a\mathbf{x} + b\mathbf{y}) = af(\mathbf{x}) + bf(\mathbf{y}), breaking linear closure across layers.
  • Universal Approximation Theorem (UAT): Proves that a feedforward network with one sufficiently wide hidden layer and a non-polynomial continuous activation can approximate any continuous function on a compact subset of Rn\mathbb{R}^n arbitrarily closely (though depth makes many functions exponentially more parameter-efficient).
  • Piecewise Linear Activations (ReLU / Leaky ReLU): Locally linear in regions while globally non-linear across kinks, avoiding exponential saturation while remaining expressive.

Example

Consider classifying points forming two concentric circles in 2D (inner circle = class 00, outer ring = class 11). Any stack of linear layers can only draw a straight line, achieving near-random accuracy. A two-layer network with ReLU activations combines multiple half-space creases into a convex polygon enclosing the inner circle, cleanly separating the classes.

Code Implementation

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf


def build_model(use_non_linear=True):
    activation = "relu" if use_non_linear else None
    return tf.keras.Sequential([
        tf.keras.layers.Input(shape=(1,)),
        tf.keras.layers.Dense(32, activation=activation),
        tf.keras.layers.Dense(32, activation=activation),
        tf.keras.layers.Dense(1),
    ])


# Nonlinear cubic target
x = np.linspace(-5, 5, 120).astype(np.float32).reshape(-1, 1)
y = 0.1 * x ** 3 - 0.5 * x ** 2 + 0.1 * x

linear_model = build_model(use_non_linear=False)
linear_model.compile(optimizer="adam", loss="mse")
linear_model.fit(x, y, epochs=400, verbose=0)

non_linear_model = build_model(use_non_linear=True)
non_linear_model.compile(optimizer="adam", loss="mse")
non_linear_model.fit(x, y, epochs=400, verbose=0)

linear_pred = linear_model.predict(x, verbose=0)
non_linear_pred = non_linear_model.predict(x, verbose=0)

print(f"Linear multi-layer MSE:     {np.mean((y - linear_pred) ** 2):.4f}")
print(f"Non-linear ReLU model MSE:  {np.mean((y - non_linear_pred) ** 2):.4f}")

plt.figure(figsize=(9, 5))
plt.scatter(x, y, s=18, label="True Cubic Data")
plt.plot(x, linear_pred, color="red", lw=2, label="Without Non-linearity (collapses to line)")
plt.plot(x, non_linear_pred, color="green", lw=2, label="With ReLU Non-linearity")
plt.title("Effect of Non-linear Activation Functions")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True)
plt.show()
  • Modern Activations: ReLU, Leaky ReLU, GELU (standard in Transformers/LLMs), SiLU / Swish (and SwiGLU gated variants), sigmoid, and tanh⁡\tanh, each trading off smoothness, zero-centering, and gradient behavior.
  • Universal Approximation vs. Depth: UAT guarantees width can approximate continuous functions, while empirical and theoretical work shows depth yields exponentially more compact representations for compositional structure.
  • Vanishing / Exploding Gradients: Saturating non-linearities (sigmoid, tanh⁡\tanh) shrink gradients in the tails, whereas ReLU/GELU preserve healthier gradient flow.
  • XOR Problem: Classic minimal demonstration that a single linear threshold cannot separate XOR, whereas adding a non-linear hidden layer solves it trivially.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.