Activation Functions: Bending the Line

Step, sigmoid, tanh and ReLU: four ways a neuron can bend its output. Without a bend, any number of layers adds up to one straight line.

Machine Learning · beginner · 8 min · 24 steps · free

What you'll learn

activations.py

import math

# An activation function bends a neuron's output. Without one, stacked layers collapse into one straight line.
xs = [-3, -2, -1, 0, 1, 2, 3]

for name in ["step", "sigmoid", "tanh", "relu"]:
    if name == "step":
        shape = [1 if x > 0 else 0 for x in xs]
    elif name == "sigmoid":
        shape = [round(1 / (1 + math.exp(-x)), 2) for x in xs]
    elif name == "tanh":
        shape = [round(math.tanh(x), 2) for x in xs]
    else:
        shape = [max(0, x) for x in xs]
    print(name, shape)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. Seven inputs a neuron might receive, from −3 to 3.
  3. Try four activation functions.
  4. Python checks name == "step" to decide which way the code goes.
  5. Step: 1 if the input is above 0, else 0. The perceptron used this. Its jump has no slope, so gradients cannot flow through it.
  6. It prints step [0, 0, 0, 0, 1, 1, 1].
  7. Sigmoid.
  8. Python checks name == "step" to decide which way the code goes.
  9. Python checks name == "sigmoid" to decide which way the code goes.
  10. A smooth S from 0 to 1. Good for probabilities, as in logistic regression. But far from 0 it is almost flat, so gradients get tiny.
  11. It prints sigmoid [0.05, 0.12, 0.27, 0.5, 0.73, 0.88, 0.95].
  12. tanh.
  13. Python checks name == "step" to decide which way the code goes.
  14. Python checks name == "sigmoid" to decide which way the code goes.
  15. Python checks name == "tanh" to decide which way the code goes.
  16. Like the sigmoid but from −1 to 1, centred on 0.
  17. It prints tanh [-1.0, -0.96, -0.76, 0.0, 0.76, 0.96, 1.0].
  18. ReLU.
  19. Python checks name == "step" to decide which way the code goes.
  20. Python checks name == "sigmoid" to decide which way the code goes.
  21. Python checks name == "tanh" to decide which way the code goes.
  22. ReLU: max(0, x). Zero for negatives, a straight line for positives. Simple, fast, and its slope is 1 for positive inputs, so gradients do not shrink.
  23. It prints relu [0, 0, 0, 0, 1, 2, 3].
  24. Four shapes, one purpose: bend the output so layers can build curves. Hidden layers usually use ReLU (or close variants such as GELU in transformers); outputs use sigmoid or softmax when you want chances.

Common mistakes

Best practices

Key takeaways

Check yourself

What is ReLU(−2)?

Answer: 0. ReLU returns max(0, x), so negatives become 0.

A network has 10 layers but no activations. What can it draw?

Answer: Only a straight line (or flat plane). Multiply-and-add layers combine into a single multiply-and-add.

·

More in Deep Learning