Introduction
Build a complete neural network library from scratch using only NumPy — forward pass, backpropagation, optimizers, and CNNs. This comprehensive guide covers everything from design through implementation, testing, and deployment.
Build a complete neural network library from scratch using only NumPy — forward pass, backpropagation, optimizers, and CNNs.
Build a complete neural network library from scratch using only NumPy — forward pass, backpropagation, optimizers, and CNNs. This comprehensive guide covers everything from design through implementation, testing, and deployment.
Layer forward pass: Z = W @ X + b (matrix multiply + bias). Activation functions with derivatives: ReLU(z) = max(0,z), ReLU
10 components required for this project.
| # | Component | Purpose | Qty |
|---|---|---|---|
| 1 | Python 3.10+ | Implementation language | x1 |
| 2 | NumPy | Matrix operations (no PyTorch/TensorFlow) | x1 |
| 3 | Matplotlib | Training loss visualization | x1 |
| 4 | scikit-learn | Datasets and evaluation metrics | x1 |
| 5 | MNIST/CIFAR-10 datasets | Training and testing data | x1 |
| 6 | Jupyter Notebook | Interactive development and visualization | x1 |
| 7 | pytest | Gradient checking with finite differences | x1 |
| 8 | tqdm | Training progress bar | x1 |
| 9 | pickle | Model serialization | x1 |
| 10 | PIL/Pillow | Image preprocessing | x1 |
Follow these 6 steps carefully.
Layer forward pass: Z = W @ X + b (matrix multiply + bias). Activation functions with derivatives: ReLU(z) = max(0,z), ReLU
Binary cross-entropy (binary classification): L = -[y×log(ŷ) + (1-y)×log(1-ŷ)]. Categorical cross-entropy (multi-class): L = -sum(y×log(ŷ)). MSE (regression): L = mean((y-ŷ)²). Implement both the loss value and its gradient with respect to output activation. For numerical stability: add small epsilon (1e-8) inside logarithms to prevent log(0). Verify gradients using finite difference: (L(θ+ε) - L(θ-ε)) / (2ε) ≈ analytical gradient.
SGD: W -= lr × dW. Momentum: velocity_W = β×velocity_W + dW, W -= lr×velocity_W. RMSprop: s_W = ρ×s_W + (1-ρ)×dW², W -= lr×dW/sqrt(s_W+ε). Adam (adaptive moment estimation): m_W = β1×m_W + (1-β1)×dW, v_W = β2×v_W + (1-β2)×dW². Bias correction: m̂_W = m_W/(1-β1^t), v̂_W = v_W/(1-β2^t). W -= lr×m̂_W/(sqrt(v̂_W)+ε). Adam (lr=0.001, β1=0.9, β2=0.999, ε=1e-8) is the recommended default for most tasks.
L2 regularization: add λ/(2m) × sum(W²) to loss. Gradient addition: dW += λ/m × W. Prevents overfitting by penalizing large weights. Dropout: during training, randomly set fraction p of neuron activations to 0 (dropout_mask = np.random.rand(shape) > dropout_rate). Scale remaining activations by 1/(1-p) to maintain expected value. During inference: no dropout (evaluate deterministically). Batch normalization: normalize layer activations to zero mean/unit variance, add learnable scale and shift parameters.
Implement 2D convolution: for each filter, slide across input, compute dot product at each position → feature map. im2col optimization: reshape input patches into columns for matrix multiplication (10–100× speedup over naive loop). Pooling: max or average reduction in spatial dimensions. CNN architecture for MNIST: Conv(32, 3×3)+ReLU, MaxPool(2×2), Conv(64, 3×3)+ReLU, MaxPool, Flatten, Dense(128)+ReLU, Dense(10)+Softmax. Target: > 99% MNIST accuracy.
Implement train_step(X_batch, y_batch): forward pass, compute loss, backward pass, update parameters. Full training loop: split data into mini-batches (batch_size=32), iterate epochs, shuffle data each epoch, compute validation loss and accuracy. Plot training curves (loss and accuracy vs epoch). Save best model based on validation accuracy. Implement confusion matrix for detailed error analysis on test set.
Core code for neural_network.py:
Test Neural Network Library from Scratch by verifying each subsystem individually before full integration.
Verify power voltages, check ground connections, use serial monitor for debug.
An interactive simulator will be available here — simulate circuits and run code in-browser without hardware.