Add neural network learning lab
This commit is contained in:
parent
404e0fe385
commit
f8adb4dcdb
|
|
@ -14,6 +14,8 @@ bootstrap/host/inventory/
|
||||||
|
|
||||||
# Ignore generated Graphify repository maps and caches
|
# Ignore generated Graphify repository maps and caches
|
||||||
graphify-out/
|
graphify-out/
|
||||||
|
labs/neural-network-from-scratch/output/
|
||||||
|
.venv-neural-lab/
|
||||||
|
|
||||||
infra/gitea/data/
|
infra/gitea/data/
|
||||||
infra/matrix-server/synapse-data/
|
infra/matrix-server/synapse-data/
|
||||||
|
|
|
||||||
|
|
@ -96,3 +96,8 @@ gateway and host-level tools:
|
||||||
cloud/free providers.
|
cloud/free providers.
|
||||||
|
|
||||||
Run `./jeannie up` and `./jeannie nuke` only from the Debian homelab server.
|
Run `./jeannie up` and `./jeannie nuke` only from the Debian homelab server.
|
||||||
|
|
||||||
|
# Learning labs
|
||||||
|
|
||||||
|
The [neural network from scratch lab](labs/neural-network-from-scratch/README.md)
|
||||||
|
walks through a NumPy classifier, backpropagation, and a training-loss plot.
|
||||||
|
|
|
||||||
|
|
@ -96,3 +96,8 @@ gateway and host-level tools:
|
||||||
cloud/free providers.
|
cloud/free providers.
|
||||||
|
|
||||||
Run `./{{ main_script }} up` and `./{{ main_script }} nuke` only from the Debian homelab server.
|
Run `./{{ main_script }} up` and `./{{ main_script }} nuke` only from the Debian homelab server.
|
||||||
|
|
||||||
|
# Learning labs
|
||||||
|
|
||||||
|
The [neural network from scratch lab](labs/neural-network-from-scratch/README.md)
|
||||||
|
walks through a NumPy classifier, backpropagation, and a training-loss plot.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,67 @@
|
||||||
|
# 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.
|
||||||
|
|
@ -0,0 +1,92 @@
|
||||||
|
"""A small binary classifier implemented with NumPy, for learning and reuse."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
class BinaryClassifier:
|
||||||
|
"""One hidden tanh layer and one sigmoid output; inputs must be 2-D."""
|
||||||
|
|
||||||
|
def __init__(self, input_size, hidden_size=8, seed=42):
|
||||||
|
if input_size < 1 or hidden_size < 1:
|
||||||
|
raise ValueError("input_size and hidden_size must be positive")
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
self.w1 = rng.normal(0, np.sqrt(1 / input_size), (input_size, hidden_size))
|
||||||
|
self.b1 = np.zeros((1, hidden_size))
|
||||||
|
self.w2 = rng.normal(0, np.sqrt(1 / hidden_size), (hidden_size, 1))
|
||||||
|
self.b2 = np.zeros((1, 1))
|
||||||
|
self.mean = np.zeros(input_size)
|
||||||
|
self.scale = np.ones(input_size)
|
||||||
|
|
||||||
|
def _inputs(self, x):
|
||||||
|
x = np.asarray(x, dtype=float)
|
||||||
|
if x.ndim != 2 or x.shape[1] != self.w1.shape[0] or not np.isfinite(x).all():
|
||||||
|
raise ValueError("x must be a finite 2-D array with the expected feature count")
|
||||||
|
return (x - self.mean) / self.scale
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _sigmoid(logits):
|
||||||
|
# Clipping keeps exp from overflowing without changing practical predictions.
|
||||||
|
return 1 / (1 + np.exp(-np.clip(logits, -500, 500)))
|
||||||
|
|
||||||
|
def predict_proba(self, x):
|
||||||
|
hidden = np.tanh(self._inputs(x) @ self.w1 + self.b1)
|
||||||
|
return self._sigmoid(hidden @ self.w2 + self.b2)
|
||||||
|
|
||||||
|
def predict(self, x, threshold=0.5):
|
||||||
|
if not 0 <= threshold <= 1:
|
||||||
|
raise ValueError("threshold must be between 0 and 1")
|
||||||
|
return (self.predict_proba(x) >= threshold).astype(int)
|
||||||
|
|
||||||
|
def fit(self, x, y, *, epochs=1000, learning_rate=0.1):
|
||||||
|
x = np.asarray(x, dtype=float)
|
||||||
|
y = np.asarray(y, dtype=float).reshape(-1, 1)
|
||||||
|
if x.ndim != 2 or x.shape[1] != self.w1.shape[0] or len(x) == 0:
|
||||||
|
raise ValueError("x must be a nonempty 2-D array with the expected feature count")
|
||||||
|
if len(y) != len(x) or not np.isin(y, [0, 1]).all() or not np.isfinite(x).all():
|
||||||
|
raise ValueError("x must be finite and y must contain one binary label per row")
|
||||||
|
if epochs < 1 or not np.isfinite(learning_rate) or learning_rate <= 0:
|
||||||
|
raise ValueError("epochs and learning_rate must be positive")
|
||||||
|
|
||||||
|
# Fit preprocessing on training data only, then retain it for inference.
|
||||||
|
self.mean = x.mean(axis=0)
|
||||||
|
self.scale = x.std(axis=0)
|
||||||
|
self.scale[self.scale == 0] = 1
|
||||||
|
x = self._inputs(x)
|
||||||
|
losses = []
|
||||||
|
for _ in range(epochs):
|
||||||
|
# Forward pass: features -> hidden activations -> output logits.
|
||||||
|
hidden = np.tanh(x @ self.w1 + self.b1)
|
||||||
|
logits = hidden @ self.w2 + self.b2
|
||||||
|
probability = self._sigmoid(logits)
|
||||||
|
# Stable binary cross-entropy directly from logits.
|
||||||
|
losses.append(float(np.mean(np.logaddexp(0, logits) - y * logits)))
|
||||||
|
|
||||||
|
# Backpropagate the mean loss through sigmoid, then tanh.
|
||||||
|
d_logits = (probability - y) / len(x)
|
||||||
|
d_w2 = hidden.T @ d_logits
|
||||||
|
d_b2 = d_logits.sum(axis=0, keepdims=True)
|
||||||
|
d_hidden = (d_logits @ self.w2.T) * (1 - hidden ** 2)
|
||||||
|
d_w1 = x.T @ d_hidden
|
||||||
|
d_b1 = d_hidden.sum(axis=0, keepdims=True)
|
||||||
|
# Batch gradient descent: compute all gradients before updating.
|
||||||
|
self.w1 -= learning_rate * d_w1
|
||||||
|
self.b1 -= learning_rate * d_b1
|
||||||
|
self.w2 -= learning_rate * d_w2
|
||||||
|
self.b2 -= learning_rate * d_b2
|
||||||
|
return losses
|
||||||
|
|
||||||
|
def save(self, path):
|
||||||
|
path = Path(path)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
np.savez(path, w1=self.w1, b1=self.b1, w2=self.w2, b2=self.b2,
|
||||||
|
mean=self.mean, scale=self.scale)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(cls, path):
|
||||||
|
with np.load(path, allow_pickle=False) as data:
|
||||||
|
model = cls(data["w1"].shape[0], data["w1"].shape[1])
|
||||||
|
for name in ("w1", "b1", "w2", "b2", "mean", "scale"):
|
||||||
|
setattr(model, name, data[name].copy())
|
||||||
|
return model
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
numpy>=1.24,<3
|
||||||
|
matplotlib>=3.7,<4
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
"""Train the NumPy network on a reproducible synthetic XOR dataset."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import matplotlib
|
||||||
|
matplotlib.use("Agg")
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from network import BinaryClassifier
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--epochs", type=int, default=2000)
|
||||||
|
parser.add_argument("--learning-rate", type=float, default=0.1)
|
||||||
|
parser.add_argument("--seed", type=int, default=42)
|
||||||
|
parser.add_argument("--output-dir", type=Path, default=Path(__file__).parent / "output")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
rng = np.random.default_rng(args.seed)
|
||||||
|
x = rng.uniform(-1, 1, size=(1000, 2))
|
||||||
|
# XOR is not linearly separable: it needs a nonlinear hidden layer.
|
||||||
|
y = ((x[:, 0] >= 0) != (x[:, 1] >= 0)).astype(int)
|
||||||
|
order = rng.permutation(len(x))
|
||||||
|
train, test = order[:800], order[800:]
|
||||||
|
model = BinaryClassifier(input_size=2, hidden_size=8, seed=args.seed)
|
||||||
|
losses = model.fit(x[train], y[train], epochs=args.epochs, learning_rate=args.learning_rate)
|
||||||
|
train_accuracy = np.mean(model.predict(x[train]).ravel() == y[train])
|
||||||
|
test_accuracy = np.mean(model.predict(x[test]).ravel() == y[test])
|
||||||
|
|
||||||
|
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
model_path = args.output_dir / "model.npz"
|
||||||
|
plot_path = args.output_dir / "training-loss.png"
|
||||||
|
model.save(model_path)
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.plot(range(1, len(losses) + 1), losses)
|
||||||
|
ax.set(title="Binary cross-entropy during training", xlabel="Epoch", ylabel="Training loss")
|
||||||
|
ax.grid(alpha=0.3)
|
||||||
|
fig.tight_layout()
|
||||||
|
fig.savefig(plot_path, dpi=150)
|
||||||
|
plt.close(fig)
|
||||||
|
print(f"Initial loss: {losses[0]:.4f}; final recorded loss: {losses[-1]:.4f}")
|
||||||
|
print(f"Training accuracy: {train_accuracy:.1%}; held-out accuracy: {test_accuracy:.1%}")
|
||||||
|
print(f"Model: {model_path}\nLoss plot: {plot_path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
Reference in New Issue