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
This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
Seven inputs a neuron might receive, from −3 to 3.
Try four activation functions.
Python checks name == "step" to decide which way the code goes.
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.
It prints step [0, 0, 0, 0, 1, 1, 1].
Sigmoid.
Python checks name == "step" to decide which way the code goes.
Python checks name == "sigmoid" to decide which way the code goes.
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.
It prints sigmoid [0.05, 0.12, 0.27, 0.5, 0.73, 0.88, 0.95].
tanh.
Python checks name == "step" to decide which way the code goes.
Python checks name == "sigmoid" to decide which way the code goes.
Python checks name == "tanh" to decide which way the code goes.
Like the sigmoid but from −1 to 1, centred on 0.
It prints tanh [-1.0, -0.96, -0.76, 0.0, 0.76, 0.96, 1.0].
ReLU.
Python checks name == "step" to decide which way the code goes.
Python checks name == "sigmoid" to decide which way the code goes.
Python checks name == "tanh" to decide which way the code goes.
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.
It prints relu [0, 0, 0, 0, 1, 2, 3].
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
Leaving out activations between layers, which collapses the network into one linear model
Best practices
Use ReLU (or a close relative) for hidden layers; sigmoid or softmax for probabilities at the output
Key takeaways
An activation function bends a neuron's output.
Without it, stacked layers collapse into one straight line.
Sigmoid and tanh are smooth but flat at the ends; ReLU keeps a steady slope.
ReLU-like functions are the default in hidden layers.
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.