What Stops Neural Networks from Becoming Linear Models
From the publisher’s feed, collected in the ZeroLabs newsroom.
Understanding activation functions, ReLU, GELU, Softmax and the role of non-linearity in deep learningDeep neural networks are built from surprisingly simple mathematical components.One of the most important is the activation function — the mechanism that allows neural networks to escape linearity and model complex patterns.Without activation functions, even extremely deep networks would collapse into simple linear transformations.And interestingly, the evolution of activation functions mirrors the evolution of deep learning itself:Sigmoid dominated early neural networksReLU helped unlock the deep learning revolutionGELU became part of the Transformer era powering modern LLMsUnderstanding activation functions is not just about memorizing formulas. It is about understanding why deep learning works at all and escapes linearity.What Is an Activation Function?At its core, a neural network neuron performs two operations:A weighted linear transformationA non-linear transformationMathematically, a neuron can be represented as:Then the activation function transforms this value:Or more compactly:Where:x , is the inputW , represents learned weightsb , is the biasf , is the activation functionThe linear part alone is not enough to model complex behavior.The activation function is what introduces non-linearity into the network.Why Non-Linearity Changes EverythingThis is one of the most important ideas in deep learning.Suppose we stack multiple layers together, but every layer is purely linear:Even though this looks deep, the entire operation can still be simplified into a single linear transformation:That means:A deep neural network without activation functions is mathematically equivalent to a shallow linear model.This is a massive limitation.Linear models can only create straight decision boundaries.But real-world problems are rarely linear:imageslanguagespeechand so on, all contain highly non-linear relationships.Activation functions allow neural networks to bend and reshape the decision space.A useful way to think about it is:Activation functions give neural networks the ability to model curved and complex relationships instead of just straight lines.This is why non-linearity is fundamental to modern AI.The Evolution of Activation FunctionsInterestingly, the history of activation functions closely follows the evolution of deep learning architectures themselves.Different eras of AI favored different activation functions because they solved different optimization challenges.Sigmoid — The Early Neural Network EraFor many years, the sigmoid function was one of the dominant activation functions in neural networks.Its formula is:The sigmoid curve smoothly compresses any input into a value between 0 and 1.Source: Image by the author.This made it attractive because:outputs resemble probabilitiesit is smooth and differentiableit was loosely inspired by biological neuron activationVisually, the function behaves like an “S-shaped” curve:very negative inputs approach 0very positive inputs approach 1values near 0 remain more sensitiveThis worked reasonably well in shallow neural networks.But as networks became deeper, a major problem appeared.The Vanishing Gradient ProblemTraining neural networks relies on gradients flowing backward through the network during backpropagation.The sigmoid derivative is:The important insight is not the formula itself.The important insight is that the derivative becomes very small when the neuron saturates near 0 or 1.During backpropagation, many small gradients get multiplied together across layers.As a result:gradients shrinkupdates become tinyearly layers learn extremely slowlyThis phenomenon became known as the vanishing gradient problem.As neural networks became deeper, sigmoid increasingly struggled and Deep learning needed something better.ReLU — The Deep Learning RevolutionThen came one of the simplest — yet most influential — activation functions ever introduced: ReLU (Rectified Linear Unit)Its formula is almost absurdly simple:Negative values become zero and positive values pass through unchanged. That’s it.Source: Image by the author.And yet this simple function helped transform deep learning.Why ReLU Changed Deep LearningReLU solved several important optimization problems simultaneously.1. Better Gradient FlowUnlike sigmoid, ReLU does not saturate for positive values.This helps gradients propagate much more effectively through deep networks. So training became faster, more stable and more scalable.2. Computational SimplicityReLU is extremely cheap to compute. It only requires a threshold operation so we don’t have any exponentials or expensive operations.This became important as models and datasets grew larger.3. Sparse ActivationsBecause negative values become zero, many neurons remain inactive for certain inputs.This creates sparse activations, which can sometimes improve efficiency and representation learning.ReLU and the Rise of Modern Deep LearningReLU became especially important during the rise of large convolutional neural networks.Architectures associated with the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) demonstrated that deep networks trained with ReLU could dramatically outperform previous approaches.This period helped trigger the modern deep learning revolution led by researchers such as Geoffrey Hinton and others. For many years, ReLU became the default activation function across deep learning.But eventually, newer architectures introduced new requirements.GELU — The Transformer EraModern Transformer architectures often use a different activation function: GELU (Gaussian Error Linear Unit).Its formula is:Where Φ(x) represents the cumulative Gaussian distribution.Source: Image by the author.At first glance, GELU may look more complicated than ReLU. But conceptually, the idea is elegant.Instead of abruptly removing negative values like ReLU, GELU smoothly weights inputs according to their importance.You can think of GELU as a softer and more probabilistic version of ReLU.Why GELU Works Well in TransformersTransformers process extremely rich contextual embeddings.Small variations in token representations can carry important semantic meaning.Because GELU behaves more smoothly than ReLU:subtle information is preserved betteroptimization becomes smootherrepresentations remain richerThis became particularly useful in architectures such as BERT from Google and GPT-style models from OpenAI.Today, GELU is strongly associated with the Transformer era of deep learning.Visualizing Activation Functions in PythonActivation functions become much easier to understand when we visualize them.The following code compares Sigmoid, ReLU, and GELU.import numpy as npimport matplotlib.pyplot as pltfrom scipy.special import erfx = np.linspace(-5, 5, 500)def sigmoid(x): return 1 / (1 + np.exp(-x))def relu(x): return np.maximum(0, x)def gelu(x): return 0.5 * x * (1 + erf(x / np.sqrt(2)))plt.figure(figsize=(10, 6))plt.plot(x, sigmoid(x), label="Sigmoid")plt.plot(x, relu(x), label="ReLU")plt.plot(x, gelu(x), label="GELU")plt.axhline(0, linestyle="--", linewidth=0.8)plt.axvline(0, linestyle="--", linewidth=0.8)plt.title("Activation Functions")plt.xlabel("Input")plt.ylabel("Output")plt.legend()plt.grid(True)plt.show()Source: Image by the author.Several important behaviors become immediately visible:Sigmoid saturates at extreme valuesReLU creates hard thresholdsGELU behaves more smoothlyThis simple visualization already explains much of the historical evolution of activation functions.Why Non-Linearity Matters in PracticeLet’s now build a simple non-linear classification problem.import numpy as npimport matplotlib.pyplot as pltnp.random.seed(42)n_samples = 500X = np.random.uniform(-1, 1, size=(n_samples, 2))radius = np.sqrt(X[:, 0]**2 + X[:, 1]**2)y = (radius > 0.5).astype(int)plt.figure(figsize=(6, 6))plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.7)plt.title("Non-Linear Classification Problem")plt.xlabel("x1")plt.ylabel("x2")plt.grid(True)plt.show()Source: Image by the author.A linear model would struggle with this dataset because the decision boundary is circular.A straight line cannot separate the classes properly.This is exactly where activation functions become essential.A Small Neural Network ExampleNow let’s train a small neural network using PyTorch.import torchimport torch.nn as nnimport torch.optim as optimX_tensor = torch.tensor(X, dtype=torch.float32)y_tensor = torch.tensor(y, dtype=torch.long)class SmallNeuralNetwork(nn.Module): def __init__(self): super().__init__() self.network = nn.Sequential( nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 2) ) def forward(self, x): return self.network(x)model = SmallNeuralNetwork()criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.01)for epoch in range(500): predictions = model(X_tensor) loss = criterion(predictions, y_tensor) optimizer.zero_grad() loss.backward() optimizer.step() if epoch % 100 == 0: predicted_classes = torch.argmax(predictions, axis=1) accuracy = ( predicted_classes == y_tensor ).float().mean() print( f"Epoch {epoch}, " f"Loss: {loss.item():.4f}, " f"Accuracy: {accuracy.item():.4f}" )The critical component is not only the linear layers:nn.Linear(...)It is the activation functions inserted between them:nn.ReLU()Without activation functions, stacking multiple linear layers would still produce a linear model.With activation functions, the network can progressively reshape the feature space into highly complex decision boundaries.Source: Image by the author.Softmax — More Than Just an Activation FunctionMany explanations treat Softmax as “just another activation function.”But Softmax plays a very different role.Its formula is:Softmax converts raw outputs (called logits) into a probability distribution.The outputs:become positivesum to 1can be interpreted as probabilitiesThis makes Softmax especially useful for multi-class classification.Why Softmax Matters in TransformersSoftmax became even more important with the rise of Transformers.In attention mechanisms, Softmax is used to transform similarity scores into attention weights.The attention equation is:Conceptually:tokens compute similarity scores with one anotherSoftmax normalizes these scoresthe model decides how much attention each token should receiveThis mechanism is fundamental to modern LLMs, Softmax is therefore not merely an activation function. It is a core probabilistic mechanism behind modern attention systems.Practical Engineering TakeawaysDifferent activation functions are useful for different reasons.Binary classification output =>Sigmoid activation functionDeep CNN hidden layers => ReLUTransformers and LLMs => GELUMulti-class output layer => SoftmaxActivation functions directly affect:gradient propagationconvergence speedtraining stabilitycomputational efficiencyrepresentation qualityChoosing an activation function is partly about mathematics — but also about optimization behavior and architecture design.Final ThoughtsActivation functions are some of the simplest mathematical components inside neural networks.But they fundamentally define what a model is capable of learning.The evolution from Sigmoid to ReLU to GELU closely mirrors the evolution of deep learning itself.Without activation functions deep networks would collapse into linear systems, modern computer vision would struggle and Transformers and LLMs would not work the way they do todayIn many ways, activation functions are one of the hidden engines behind modern AI.If this article helped you better understand how neural networks actually learn complex behavior, feel free to connect or share your thoughts.What Stops Neural Networks from Becoming Linear Models was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.