Training a Neuron
Recap
In Chapter 3, we built a complete autograd engine: forward pass, topological sort, backward pass. Now we'll use it to train something.
A Single Neuron
The simplest neural network is one neuron. It computes:
where:
- is the input (given)
- is the weight (learned)
- is the bias (learned)
- is the prediction
The tanh is the activation function. Without it, stacking multiple layers would collapse into a single linear transformation. Non-linearity is what makes deep learning deep.
The Loss Function
To train, we need a loss — a single number that tells us how wrong the model is. For a single data point with target :
This is the mean squared error (MSE). When , the loss is zero. Otherwise, it's positive.
Stochastic Gradient Descent (SGD)
Training is a loop:
- Forward: compute and (builds the graph)
- Backward: call
Backward(graph, loss)to fill in gradients - Update: nudge each parameter opposite to its gradient
where is the learning rate. Too high → diverges. Too low → painfully slow.
- Reset: create a fresh graph (or zero out gradients) and repeat
Training a Neuron — Live!
This interactive demo trains a single neuron to learn y = tanh(2*x + 1) for a few data points. Watch the loss decrease as the neuron figures out the right weight and bias:
Experiments to Try
- Change the learning rate: try
lr = 0.1(slower) orlr = 2.0(might diverge!) - Change the epochs: try
epochs = 50for more training - Change initial weights: try
w_val = -1.0— can it still converge? - Add more data points: add
3.0toxsand the corresponding target toys
Common Gotchas
-
Forgetting to reset the graph: If you reuse a graph, old gradients accumulate. We create a fresh
Grapheach epoch to avoid this. -
Missing non-linearity: Without
tanh, stacking multiple linear layers is equivalent to a single linear layer. Non-linearities are what give neural networks their expressive power. -
Exploding/vanishing gradients: Very deep graphs can make gradients too large (exploding) or too small (vanishing).
tanhis particularly prone to vanishing gradients when saturated. This is why modern networks often use ReLU. -
Learning rate sensitivity: SGD is sensitive to the learning rate. Adaptive optimizers like Adam adjust the learning rate per-parameter, but SGD is the foundation they all build on.