my-homelab-configs/labs/neural-network-from-scratch/README.md

68 lines
3.0 KiB
Markdown

# Neural network from scratch
This lab trains a tiny binary classifier using NumPy for the math and
Matplotlib for a loss plot. It does not use an automatic differentiation or
machine-learning framework. The example uses synthetic XOR data, not homelab
incidents; its predictions are not a health diagnosis.
## Run
On the machine where you want to do the exercise, from the repository root:
```bash
python3 -m venv .venv-neural-lab
source .venv-neural-lab/bin/activate
python -m pip install -r labs/neural-network-from-scratch/requirements.txt
python labs/neural-network-from-scratch/train.py
```
The script prints training and held-out accuracy and writes `model.npz` and
`training-loss.png` to `labs/neural-network-from-scratch/output/` (ignored by
Git). It uses a fixed seed and an 80/20 split. Change the experiment with
`--epochs 500`, `--learning-rate 0.03`, `--seed 7`, or
`--output-dir /path/to/results`. It overwrites files with the same names in
the output directory. View the PNG on a machine with an image viewer.
## What the network learns
Each sample has two numbers. Its label is 1 when the numbers have different
signs, and 0 otherwise. A single linear boundary cannot solve XOR; the hidden
layer uses `tanh` to combine nonlinear features.
1. **Forward pass:** `hidden = tanh(X W1 + b1)` and `logits = hidden W2 + b2`.
The sigmoid of each logit gives the predicted probability of class 1.
2. **Loss:** binary cross-entropy penalizes confident wrong answers. The code
computes it from logits using `logaddexp` for numerical stability.
3. **Backpropagation:** `(probability - label) / sample_count` is the loss
gradient at the output logits. The chain rule carries it through `W2` and
the derivative of `tanh` to calculate all weight and bias gradients.
4. **Gradient descent:** subtract the learning rate times each gradient. The
plotted loss is measured before the update on each epoch, so the last point
is immediately before the final update.
The network standardizes each feature using **training data only** and saves
those statistics with its parameters. The held-out accuracy is a basic check on
new synthetic samples, not proof of generalization to real operations data.
## Reuse the trained model
From this directory, with the same virtual environment active:
```python
from network import BinaryClassifier
model = BinaryClassifier.load("output/model.npz")
print(model.predict_proba([[0.8, -0.5]])) # probability of class 1
print(model.predict([[0.8, -0.5]])) # class at threshold 0.5
```
`fit` also accepts another finite two-dimensional feature matrix and one binary
label per row. The saved NumPy archive is for trusted model files; it includes
weights, biases, and scaling statistics but no feature names, training data,
dataset provenance, or versioned serving contract. Add those before using the
classifier as part of a later application.
Try comparing different learning rates and hidden layer sizes, then compare
training and held-out accuracy. A low training loss by itself does not mean a
model will work on a different kind of data.