my-homelab-configs/labs/neural-network-from-scratch/network.py

93 lines
4.0 KiB
Python

"""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