Tuesday, November 24, 2026

BUILDING NEURAL NETWORKS FROM SCRATCH: A GUIDE FOR SOFTWARE ENGINEERS



INTRODUCTION: DEMYSTIFYING THE NEURAL NETWORK

Welcome to this journey into the fascinating world of neural networks. If you have ever wondered how machines learn to recognize faces, translate languages, or beat world champions at complex games, you are about to discover the fundamental building blocks that make all of this possible. This tutorial will guide you through implementing neural networks using nothing but pure Python and basic mathematical operations.

Many software engineers encounter neural networks as mysterious black boxes hidden behind high-level frameworks like TensorFlow or PyTorch. While these frameworks are powerful and essential for production work, they can obscure the elegant simplicity of the underlying mathematics. By building everything from scratch, you will gain an intuitive understanding of how neural networks actually work, what happens during training, and why certain architectural choices matter.

We will start with the simplest possible neural network and gradually build up to more sophisticated architectures. Along the way, you will learn about the mathematical principles that govern learning, the computational tricks that make training efficient, and the practical considerations that separate toy examples from real-world applications.

PART 1: THE FUNDAMENTAL BUILDING BLOCK - THE ARTIFICIAL NEURON

Before we can build a network, we need to understand its most basic component: the artificial neuron. Inspired by biological neurons in the brain, an artificial neuron is a mathematical function that takes multiple inputs, combines them, and produces a single output.

Imagine you are trying to decide whether to go hiking tomorrow. You might consider several factors: the weather forecast, how tired you feel, whether your friends are available, and how much work you have pending. Each factor has a different importance to you. The weather might be very important (high weight), while your tiredness might matter less (low weight). Your brain unconsciously combines these weighted factors to make a decision.

An artificial neuron works similarly. It receives multiple input values, multiplies each by a weight that represents its importance, sums everything together, adds a bias term (which shifts the decision threshold), and finally applies an activation function to produce the output.

The mathematical formula for a single neuron looks like this:

output = activation(w1*x1 + w2*x2 + w3*x3 + ... + wn*xn + bias)

Let us implement this in Python. We will start with the most basic version possible:

import math

def neuron_output(inputs, weights, bias):
    """
    Calculate the output of a single neuron.
    
    Parameters:
        inputs: list of input values
        weights: list of weights (same length as inputs)
        bias: bias term (scalar value)
    
    Returns:
        The activated output of the neuron
    """
    # First, compute the weighted sum of inputs
    weighted_sum = 0.0
    for i in range(len(inputs)):
        weighted_sum += inputs[i] * weights[i]
    
    # Add the bias term
    weighted_sum += bias
    
    # Apply activation function (sigmoid in this case)
    # Sigmoid squashes any value into range (0, 1)
    output = 1.0 / (1.0 + math.exp(-weighted_sum))
    
    return output

This simple function captures the essence of neural computation. The weighted sum represents the neuron's total input signal, and the sigmoid activation function transforms this into a bounded output between zero and one. The sigmoid function is particularly useful because it is smooth and differentiable, properties we will need later for training.

Let us test this neuron with a simple example:

# Example: A neuron that might decide "should I go hiking?"
# Inputs: [weather_quality, energy_level, friends_available]
example_inputs = [0.8, 0.6, 0.9]  # Good weather, moderate energy, friends available
example_weights = [0.7, 0.3, 0.5]  # Weather is most important
example_bias = -0.5  # Slight tendency to say no (negative bias)

decision = neuron_output(example_inputs, example_weights, example_bias)
print(f"Hiking decision strength: {decision:.3f}")
# Output might be around 0.82, suggesting "yes, go hiking"

The activation function deserves special attention because it introduces non-linearity into our network. Without activation functions, stacking multiple layers of neurons would be pointless because any combination of linear operations is still linear. The sigmoid function we used above is just one option. Let us implement several common activation functions:

def sigmoid(x):
    """
    Sigmoid activation function.
    Maps input to range (0, 1).
    Useful for binary classification and probability outputs.
    """
    return 1.0 / (1.0 + math.exp(-x))

def sigmoid_derivative(x):
    """
    Derivative of sigmoid function.
    Needed for backpropagation.
    """
    s = sigmoid(x)
    return s * (1.0 - s)

def tanh(x):
    """
    Hyperbolic tangent activation function.
    Maps input to range (-1, 1).
    Often works better than sigmoid for hidden layers.
    """
    return math.tanh(x)

def tanh_derivative(x):
    """
    Derivative of tanh function.
    """
    t = tanh(x)
    return 1.0 - t * t

def relu(x):
    """
    Rectified Linear Unit (ReLU) activation function.
    Maps negative values to 0, keeps positive values unchanged.
    Most popular activation for modern deep networks.
    """
    return max(0.0, x)

def relu_derivative(x):
    """
    Derivative of ReLU function.
    1 for positive inputs, 0 for negative inputs.
    """
    return 1.0 if x > 0 else 0.0

Each activation function has different properties that make it suitable for different tasks. ReLU has become the default choice for most hidden layers because it avoids the vanishing gradient problem that plagues sigmoid and tanh in deep networks. However, sigmoid remains useful for output layers in binary classification tasks because it naturally produces probability-like values.

PART 2: BUILDING A SIMPLE FEEDFORWARD NEURAL NETWORK

Now that we understand individual neurons, we can connect them into layers to form a complete neural network. A feedforward neural network consists of an input layer, one or more hidden layers, and an output layer. Information flows in one direction: from inputs through hidden layers to outputs.

Let us start by implementing a simple network with one hidden layer. We will build this step by step, beginning with a naive implementation that uses explicit loops. This will help us understand exactly what is happening before we optimize with matrix operations.

class SimpleNeuralNetwork:
    """
    A basic feedforward neural network with one hidden layer.
    This is a naive implementation using loops for clarity.
    """
    
    def __init__(self, input_size, hidden_size, output_size):
        """
        Initialize the network with random weights and biases.
        
        Parameters:
            input_size: number of input features
            hidden_size: number of neurons in hidden layer
            output_size: number of output neurons
        """
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        
        # Initialize weights randomly between -1 and 1
        # We use small random values to break symmetry
        import random
        random.seed(42)  # For reproducibility
        
        # Weights from input to hidden layer
        self.weights_input_hidden = []
        for i in range(hidden_size):
            neuron_weights = []
            for j in range(input_size):
                neuron_weights.append(random.uniform(-1, 1))
            self.weights_input_hidden.append(neuron_weights)
        
        # Biases for hidden layer
        self.bias_hidden = [random.uniform(-1, 1) for _ in range(hidden_size)]
        
        # Weights from hidden to output layer
        self.weights_hidden_output = []
        for i in range(output_size):
            neuron_weights = []
            for j in range(hidden_size):
                neuron_weights.append(random.uniform(-1, 1))
            self.weights_hidden_output.append(neuron_weights)
        
        # Biases for output layer
        self.bias_output = [random.uniform(-1, 1) for _ in range(output_size)]
    
    def forward(self, inputs):
        """
        Perform forward propagation through the network.
        
        Parameters:
            inputs: list of input values
        
        Returns:
            tuple of (hidden_outputs, final_outputs)
        """
        # Compute hidden layer activations
        hidden_outputs = []
        for i in range(self.hidden_size):
            # Compute weighted sum for this hidden neuron
            weighted_sum = 0.0
            for j in range(self.input_size):
                weighted_sum += inputs[j] * self.weights_input_hidden[i][j]
            weighted_sum += self.bias_hidden[i]
            
            # Apply activation function
            hidden_outputs.append(sigmoid(weighted_sum))
        
        # Compute output layer activations
        final_outputs = []
        for i in range(self.output_size):
            # Compute weighted sum for this output neuron
            weighted_sum = 0.0
            for j in range(self.hidden_size):
                weighted_sum += hidden_outputs[j] * self.weights_hidden_output[i][j]
            weighted_sum += self.bias_output[i]
            
            # Apply activation function
            final_outputs.append(sigmoid(weighted_sum))
        
        return hidden_outputs, final_outputs

This implementation clearly shows what happens during forward propagation. Each neuron in the hidden layer computes a weighted sum of all inputs, adds its bias, and applies the sigmoid activation. Then each output neuron does the same using the hidden layer outputs as its inputs.

Let us test this network with a simple example:

# Create a network: 2 inputs, 3 hidden neurons, 1 output
network = SimpleNeuralNetwork(input_size=2, hidden_size=3, output_size=1)

# Test with some input
test_input = [0.5, 0.8]
hidden, output = network.forward(test_input)

print(f"Input: {test_input}")
print(f"Hidden layer outputs: {[f'{h:.3f}' for h in hidden]}")
print(f"Final output: {output[0]:.3f}")

At this point, our network produces random outputs because the weights are initialized randomly. To make the network useful, we need to train it. Training means adjusting the weights and biases so that the network produces desired outputs for given inputs. This is where backpropagation comes in.

PART 3: THE MAGIC OF BACKPROPAGATION

Backpropagation is the algorithm that makes neural networks trainable. The name comes from "backward propagation of errors" because we compute how much each weight contributed to the final error and adjust it accordingly. The mathematics behind backpropagation relies on the chain rule from calculus, which allows us to compute gradients efficiently.

The training process follows these steps:

First, we perform forward propagation to get the network's prediction. Second, we calculate the error by comparing the prediction to the desired output. Third, we compute gradients that tell us how to adjust each weight to reduce the error. Fourth, we update the weights by taking a small step in the direction that reduces error. Fifth, we repeat this process many times with different training examples.

The key insight is that we can compute how much each weight contributed to the error by working backwards through the network. For the output layer, this is straightforward: we can directly see how changing a weight affects the final output. For hidden layers, we use the chain rule to propagate error backwards through the network.

Let us implement backpropagation step by step. We will add a training method to our network class:

class TrainableNeuralNetwork(SimpleNeuralNetwork):
    """
    Extension of SimpleNeuralNetwork with backpropagation training.
    """
    
    def __init__(self, input_size, hidden_size, output_size, learning_rate=0.5):
        """
        Initialize the network with an additional learning rate parameter.
        
        Parameters:
            learning_rate: controls how big the weight updates are
        """
        super().__init__(input_size, hidden_size, output_size)
        self.learning_rate = learning_rate
    
    def train_single_example(self, inputs, targets):
        """
        Train the network on a single example using backpropagation.
        
        Parameters:
            inputs: list of input values
            targets: list of desired output values
        
        Returns:
            The error for this example
        """
        # Step 1: Forward propagation
        # We need to store intermediate values for backpropagation
        
        # Compute hidden layer (store weighted sums before activation)
        hidden_weighted_sums = []
        hidden_outputs = []
        for i in range(self.hidden_size):
            weighted_sum = 0.0
            for j in range(self.input_size):
                weighted_sum += inputs[j] * self.weights_input_hidden[i][j]
            weighted_sum += self.bias_hidden[i]
            hidden_weighted_sums.append(weighted_sum)
            hidden_outputs.append(sigmoid(weighted_sum))
        
        # Compute output layer (store weighted sums before activation)
        output_weighted_sums = []
        final_outputs = []
        for i in range(self.output_size):
            weighted_sum = 0.0
            for j in range(self.hidden_size):
                weighted_sum += hidden_outputs[j] * self.weights_hidden_output[i][j]
            weighted_sum += self.bias_output[i]
            output_weighted_sums.append(weighted_sum)
            final_outputs.append(sigmoid(weighted_sum))
        
        # Step 2: Calculate error
        total_error = 0.0
        for i in range(self.output_size):
            error = targets[i] - final_outputs[i]
            total_error += error * error
        total_error *= 0.5  # Mean squared error
        
        # Step 3: Backpropagation - compute gradients
        
        # Output layer gradients
        output_deltas = []
        for i in range(self.output_size):
            # Error derivative times activation derivative
            error_derivative = -(targets[i] - final_outputs[i])
            activation_derivative = sigmoid_derivative(output_weighted_sums[i])
            delta = error_derivative * activation_derivative
            output_deltas.append(delta)
        
        # Hidden layer gradients
        hidden_deltas = []
        for i in range(self.hidden_size):
            # Sum of weighted deltas from output layer
            error_sum = 0.0
            for j in range(self.output_size):
                error_sum += output_deltas[j] * self.weights_hidden_output[j][i]
            
            # Multiply by activation derivative
            activation_derivative = sigmoid_derivative(hidden_weighted_sums[i])
            delta = error_sum * activation_derivative
            hidden_deltas.append(delta)
        
        # Step 4: Update weights and biases
        
        # Update weights from hidden to output
        for i in range(self.output_size):
            for j in range(self.hidden_size):
                gradient = output_deltas[i] * hidden_outputs[j]
                self.weights_hidden_output[i][j] -= self.learning_rate * gradient
            # Update output bias
            self.bias_output[i] -= self.learning_rate * output_deltas[i]
        
        # Update weights from input to hidden
        for i in range(self.hidden_size):
            for j in range(self.input_size):
                gradient = hidden_deltas[i] * inputs[j]
                self.weights_input_hidden[i][j] -= self.learning_rate * gradient
            # Update hidden bias
            self.bias_hidden[i] -= self.learning_rate * hidden_deltas[i]
        
        return total_error
    
    def train(self, training_data, epochs):
        """
        Train the network on a dataset for multiple epochs.
        
        Parameters:
            training_data: list of (inputs, targets) tuples
            epochs: number of times to iterate through the dataset
        """
        for epoch in range(epochs):
            total_error = 0.0
            for inputs, targets in training_data:
                error = self.train_single_example(inputs, targets)
                total_error += error
            
            # Print progress every 100 epochs
            if (epoch + 1) % 100 == 0:
                avg_error = total_error / len(training_data)
                print(f"Epoch {epoch + 1}, Average Error: {avg_error:.6f}")

This implementation reveals the mathematical beauty of backpropagation. The deltas represent how much each neuron contributed to the error. For output neurons, we can compute this directly from the difference between predicted and target values. For hidden neurons, we propagate the error backwards by computing a weighted sum of deltas from the next layer.

The learning rate is a crucial hyperparameter. If it is too large, the network will overshoot the optimal weights and fail to converge. If it is too small, training will be extremely slow. Finding the right learning rate often requires experimentation.

Let us train our network on a classic problem: learning the XOR function. XOR (exclusive or) is interesting because it is not linearly separable, meaning a single neuron cannot learn it. This is why we need hidden layers.

# XOR training data
# XOR returns 1 if inputs are different, 0 if they are the same
xor_data = [
    ([0.0, 0.0], [0.0]),  # 0 XOR 0 = 0
    ([0.0, 1.0], [1.0]),  # 0 XOR 1 = 1
    ([1.0, 0.0], [1.0]),  # 1 XOR 0 = 1
    ([1.0, 1.0], [0.0])   # 1 XOR 1 = 0
]

# Create and train network
xor_network = TrainableNeuralNetwork(input_size=2, hidden_size=4, output_size=1, learning_rate=0.5)
print("Training XOR network...")
xor_network.train(xor_data, epochs=5000)

# Test the trained network
print("\nTesting trained network:")
for inputs, expected in xor_data:
    _, output = xor_network.forward(inputs)
    print(f"Input: {inputs}, Expected: {expected[0]:.1f}, Got: {output[0]:.3f}")

After training, the network should produce outputs very close to the expected values. This demonstrates that our implementation works correctly. The network has learned to represent the XOR function using its hidden layer neurons, each of which has learned to detect different patterns in the input.

PART 4: VECTORIZATION FOR PERFORMANCE

Our loop-based implementation is clear and educational, but it is extremely slow for larger networks. Modern neural networks often have millions of parameters, and training them with explicit loops would take forever. The solution is vectorization: using matrix operations to compute many values simultaneously.

Python's NumPy library provides efficient matrix operations implemented in optimized C code. By representing our weights as matrices and our activations as vectors, we can replace all those nested loops with simple matrix multiplications.

Let us reimplement our neural network using NumPy:

import numpy as np

class VectorizedNeuralNetwork:
    """
    A vectorized neural network implementation using NumPy.
    Much faster than the loop-based version.
    """
    
    def __init__(self, input_size, hidden_size, output_size, learning_rate=0.5):
        """
        Initialize network with random weights as NumPy arrays.
        """
        self.learning_rate = learning_rate
        
        # Initialize weights with small random values
        # Using Xavier initialization for better convergence
        np.random.seed(42)  # For reproducibility
        self.W1 = np.random.randn(input_size, hidden_size) * np.sqrt(2.0 / input_size)
        self.b1 = np.zeros((1, hidden_size))
        
        self.W2 = np.random.randn(hidden_size, output_size) * np.sqrt(2.0 / hidden_size)
        self.b2 = np.zeros((1, output_size))
    
    def sigmoid(self, x):
        """Vectorized sigmoid function."""
        return 1.0 / (1.0 + np.exp(-np.clip(x, -500, 500)))
    
    def sigmoid_derivative(self, x):
        """Vectorized sigmoid derivative."""
        s = self.sigmoid(x)
        return s * (1.0 - s)
    
    def forward(self, X):
        """
        Forward propagation using matrix operations.
        
        Parameters:
            X: input matrix of shape (batch_size, input_size)
        
        Returns:
            tuple of (hidden_activations, output_activations)
        """
        # Hidden layer computation: Z1 = X @ W1 + b1
        self.Z1 = np.dot(X, self.W1) + self.b1
        self.A1 = self.sigmoid(self.Z1)
        
        # Output layer computation: Z2 = A1 @ W2 + b2
        self.Z2 = np.dot(self.A1, self.W2) + self.b2
        self.A2 = self.sigmoid(self.Z2)
        
        return self.A1, self.A2
    
    def backward(self, X, y):
        """
        Backpropagation using matrix operations.
        
        Parameters:
            X: input matrix of shape (batch_size, input_size)
            y: target matrix of shape (batch_size, output_size)
        """
        m = X.shape[0]  # Number of examples
        
        # Compute output layer gradients
        dZ2 = self.A2 - y  # Derivative of loss w.r.t. Z2
        dW2 = np.dot(self.A1.T, dZ2) / m
        db2 = np.sum(dZ2, axis=0, keepdims=True) / m
        
        # Compute hidden layer gradients
        dA1 = np.dot(dZ2, self.W2.T)
        dZ1 = dA1 * self.sigmoid_derivative(self.Z1)
        dW1 = np.dot(X.T, dZ1) / m
        db1 = np.sum(dZ1, axis=0, keepdims=True) / m
        
        # Update weights and biases
        self.W2 -= self.learning_rate * dW2
        self.b2 -= self.learning_rate * db2
        self.W1 -= self.learning_rate * dW1
        self.b1 -= self.learning_rate * db1
    
    def train(self, X, y, epochs):
        """
        Train the network for multiple epochs.
        
        Parameters:
            X: input matrix of shape (num_examples, input_size)
            y: target matrix of shape (num_examples, output_size)
            epochs: number of training iterations
        """
        for epoch in range(epochs):
            # Forward propagation
            _, predictions = self.forward(X)
            
            # Compute loss (mean squared error)
            loss = np.mean((predictions - y) ** 2)
            
            # Backward propagation
            self.backward(X, y)
            
            # Print progress
            if (epoch + 1) % 100 == 0:
                print(f"Epoch {epoch + 1}, Loss: {loss:.6f}")
    
    def predict(self, X):
        """Make predictions for input data."""
        _, predictions = self.forward(X)
        return predictions

The vectorized version is dramatically more concise and much faster. Instead of nested loops, we use matrix multiplication (the @ operator or np.dot). The mathematics is identical, but NumPy can execute these operations in parallel using optimized low-level code.

Notice how the forward propagation becomes just two lines per layer: compute the weighted sum (Z = X @ W + b) and apply the activation function (A = sigmoid(Z)). The backpropagation is similarly compact, computing gradients as matrix operations.

Let us train this vectorized network on the XOR problem:

# Prepare XOR data as NumPy arrays
X_xor = np.array([[0.0, 0.0],
                  [0.0, 1.0],
                  [1.0, 0.0],
                  [1.0, 1.0]])

y_xor = np.array([[0.0],
                  [1.0],
                  [1.0],
                  [0.0]])

# Create and train vectorized network
vec_network = VectorizedNeuralNetwork(input_size=2, hidden_size=4, output_size=1, learning_rate=1.0)
print("Training vectorized XOR network...")
vec_network.train(X_xor, y_xor, epochs=5000)

# Test predictions
print("\nPredictions:")
predictions = vec_network.predict(X_xor)
for i in range(len(X_xor)):
    print(f"Input: {X_xor[i]}, Expected: {y_xor[i][0]:.1f}, Predicted: {predictions[i][0]:.3f}")

The vectorized version trains much faster and produces the same results. This is the approach used by all modern deep learning frameworks. When you use TensorFlow or PyTorch, they are performing these same matrix operations, just with additional optimizations and GPU acceleration.

PART 5: A MORE REALISTIC EXAMPLE - HANDWRITTEN DIGIT CLASSIFICATION

To demonstrate our neural network on a more practical problem, let us tackle a simplified version of handwritten digit recognition. We will create a small synthetic dataset that mimics the structure of the famous MNIST dataset, where each digit is represented as a grid of pixel values.

For simplicity, we will work with tiny eight by eight pixel images rather than the full twenty-eight by twenty-eight MNIST images. Each pixel will have a value between zero and one representing its intensity.

def create_simple_digit_dataset():
    """
    Create a small synthetic dataset of handwritten digits.
    Each digit is represented as an 8x8 grid (64 pixels).
    """
    # Simple patterns for digits 0, 1, 2
    # 1 represents a dark pixel, 0 represents a light pixel
    
    digit_0_pattern = np.array([
        [0, 1, 1, 1, 1, 1, 1, 0],
        [1, 1, 0, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 0, 0, 0, 0, 1, 1],
        [0, 1, 1, 1, 1, 1, 1, 0]
    ], dtype=float).flatten()
    
    digit_1_pattern = np.array([
        [0, 0, 0, 1, 1, 0, 0, 0],
        [0, 0, 1, 1, 1, 0, 0, 0],
        [0, 1, 1, 1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1]
    ], dtype=float).flatten()
    
    digit_2_pattern = np.array([
        [0, 1, 1, 1, 1, 1, 1, 0],
        [1, 1, 0, 0, 0, 0, 1, 1],
        [0, 0, 0, 0, 0, 0, 1, 1],
        [0, 0, 0, 0, 0, 1, 1, 0],
        [0, 0, 0, 1, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 0, 0, 0],
        [1, 1, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1]
    ], dtype=float).flatten()
    
    # Create training data with some variations
    X_train = []
    y_train = []
    
    # Add multiple noisy versions of each digit
    for _ in range(20):
        # Add noise to digit 0
        noisy_0 = digit_0_pattern + np.random.normal(0, 0.1, 64)
        noisy_0 = np.clip(noisy_0, 0, 1)
        X_train.append(noisy_0)
        y_train.append([1, 0, 0])  # One-hot encoding for digit 0
        
        # Add noise to digit 1
        noisy_1 = digit_1_pattern + np.random.normal(0, 0.1, 64)
        noisy_1 = np.clip(noisy_1, 0, 1)
        X_train.append(noisy_1)
        y_train.append([0, 1, 0])  # One-hot encoding for digit 1
        
        # Add noise to digit 2
        noisy_2 = digit_2_pattern + np.random.normal(0, 0.1, 64)
        noisy_2 = np.clip(noisy_2, 0, 1)
        X_train.append(noisy_2)
        y_train.append([0, 0, 1])  # One-hot encoding for digit 2
    
    return np.array(X_train), np.array(y_train), digit_0_pattern, digit_1_pattern, digit_2_pattern

# Create dataset
X_digits, y_digits, clean_digit_0, clean_digit_1, clean_digit_2 = create_simple_digit_dataset()
print(f"Dataset shape: {X_digits.shape}")
print(f"Labels shape: {y_digits.shape}")

# Create and train a network for digit classification
digit_network = VectorizedNeuralNetwork(
    input_size=64,      # 8x8 = 64 pixels
    hidden_size=32,     # 32 hidden neurons
    output_size=3,      # 3 classes (digits 0, 1, 2)
    learning_rate=0.5
)

print("\nTraining digit classifier...")
digit_network.train(X_digits, y_digits, epochs=1000)

# Test on clean versions of digits
test_digits = np.array([
    clean_digit_0,
    clean_digit_1, 
    clean_digit_2
])

predictions = digit_network.predict(test_digits)
print("\nTest predictions:")
for i, pred in enumerate(predictions):
    predicted_class = np.argmax(pred)
    confidence = pred[predicted_class]
    print(f"Digit {i}: Predicted class {predicted_class} with confidence {confidence:.3f}")

This example demonstrates how neural networks can learn to classify images. The network learns to recognize patterns in the pixel values that distinguish different digits. The hidden layer learns to detect features like edges, curves, and corners that are characteristic of each digit.

One-hot encoding is used for the labels, meaning each class is represented as a vector with a one in the position corresponding to the correct class and zeros elsewhere. This allows us to use the same loss function (mean squared error) for multi-class classification.

PART 6: UNDERSTANDING CONVOLUTIONAL NEURAL NETWORKS

While fully connected networks work well for many tasks, they have limitations when dealing with images. Every pixel is connected to every neuron in the next layer, which creates an enormous number of parameters for large images. More importantly, fully connected networks do not exploit the spatial structure of images. Nearby pixels are usually related, and patterns can appear anywhere in an image.

Convolutional Neural Networks (CNNs) solve these problems by using specialized layers that preserve spatial relationships and share weights across different positions. The key operation is convolution, which slides a small filter (also called a kernel) across the image, computing a weighted sum at each position.

Think of a filter as a pattern detector. For example, a vertical edge detector might have positive weights on the left and negative weights on the right. When this filter slides over a vertical edge in the image, it produces a strong response. Different filters detect different patterns: horizontal edges, diagonal lines, corners, and more complex features in deeper layers.

Let us implement the convolution operation from scratch:

def convolve2d(image, kernel, stride=1, padding=0):
    """
    Perform 2D convolution operation.
    
    Parameters:
        image: 2D numpy array (height, width)
        kernel: 2D numpy array (kernel_height, kernel_width)
        stride: step size for sliding the kernel
        padding: number of zeros to add around the image
    
    Returns:
        Convolved output as 2D numpy array
    """
    # Add padding if specified
    if padding > 0:
        image = np.pad(image, padding, mode='constant', constant_values=0)
    
    image_height, image_width = image.shape
    kernel_height, kernel_width = kernel.shape
    
    # Calculate output dimensions
    output_height = (image_height - kernel_height) // stride + 1
    output_width = (image_width - kernel_width) // stride + 1
    
    # Initialize output
    output = np.zeros((output_height, output_width))
    
    # Perform convolution
    for i in range(output_height):
        for j in range(output_width):
            # Extract the region of the image
            row_start = i * stride
            row_end = row_start + kernel_height
            col_start = j * stride
            col_end = col_start + kernel_width
            
            region = image[row_start:row_end, col_start:col_end]
            
            # Element-wise multiplication and sum
            output[i, j] = np.sum(region * kernel)
    
    return output

This function implements the core convolution operation. The kernel slides across the image, and at each position, we multiply corresponding elements and sum the results. The stride parameter controls how far the kernel moves at each step, and padding adds zeros around the image border to control the output size.

Let us test this with a simple edge detection example:

# Create a simple test image with a vertical edge
test_image = np.array([
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1]
], dtype=float)

# Vertical edge detection kernel
vertical_edge_kernel = np.array([
    [-1, 0, 1],
    [-1, 0, 1],
    [-1, 0, 1]
], dtype=float)

# Horizontal edge detection kernel
horizontal_edge_kernel = np.array([
    [-1, -1, -1],
    [ 0,  0,  0],
    [ 1,  1,  1]
], dtype=float)

# Apply convolution
vertical_edges = convolve2d(test_image, vertical_edge_kernel)
horizontal_edges = convolve2d(test_image, horizontal_edge_kernel)

print("Original image:")
print(test_image)
print("\nVertical edge detection:")
print(vertical_edges)
print("\nHorizontal edge detection:")
print(horizontal_edges)

The vertical edge kernel produces strong responses where there is a vertical edge in the image, while the horizontal edge kernel responds to horizontal edges. This demonstrates how convolution can extract specific features from images.

Now let us implement a complete convolutional layer that can handle multiple input channels and multiple output filters:

class ConvolutionalLayer:
    """
    A convolutional layer with multiple filters.
    """
    
    def __init__(self, num_filters, filter_size, input_channels, stride=1, padding=0):
        """
        Initialize the convolutional layer.
        
        Parameters:
            num_filters: number of filters (output channels)
            filter_size: size of square filters (e.g., 3 for 3x3)
            input_channels: number of input channels
            stride: stride for convolution
            padding: padding to add around input
        """
        self.num_filters = num_filters
        self.filter_size = filter_size
        self.input_channels = input_channels
        self.stride = stride
        self.padding = padding
        
        # Initialize filters with small random values
        # Shape: (num_filters, input_channels, filter_size, filter_size)
        self.filters = np.random.randn(
            num_filters, input_channels, filter_size, filter_size
        ) * 0.1
        
        # Initialize biases (one per filter)
        self.biases = np.zeros(num_filters)
    
    def forward(self, input_data):
        """
        Forward pass through the convolutional layer.
        
        Parameters:
            input_data: 3D array (channels, height, width)
        
        Returns:
            Output feature maps as 3D array (num_filters, out_height, out_width)
        """
        self.input_data = input_data
        channels, height, width = input_data.shape
        
        # Add padding if needed
        if self.padding > 0:
            input_padded = np.pad(
                input_data,
                ((0, 0), (self.padding, self.padding), (self.padding, self.padding)),
                mode='constant'
            )
        else:
            input_padded = input_data
        
        # Calculate output dimensions
        out_height = (height + 2 * self.padding - self.filter_size) // self.stride + 1
        out_width = (width + 2 * self.padding - self.filter_size) // self.stride + 1
        
        # Initialize output
        output = np.zeros((self.num_filters, out_height, out_width))
        
        # Apply each filter
        for f in range(self.num_filters):
            for i in range(out_height):
                for j in range(out_width):
                    # Extract region
                    row_start = i * self.stride
                    row_end = row_start + self.filter_size
                    col_start = j * self.stride
                    col_end = col_start + self.filter_size
                    
                    region = input_padded[:, row_start:row_end, col_start:col_end]
                    
                    # Convolve with filter and add bias
                    output[f, i, j] = np.sum(region * self.filters[f]) + self.biases[f]
        
        return output
    
    def backward(self, output_gradient, learning_rate):
        """
        Backward pass through the convolutional layer.
        
        Parameters:
            output_gradient: gradient from the next layer
            learning_rate: learning rate for weight updates
        
        Returns:
            Gradient to pass to previous layer
        """
        # This is a simplified version for educational purposes
        # Full implementation would include proper gradient computation
        
        # Initialize gradient for input
        input_gradient = np.zeros_like(self.input_data)
        
        # Initialize gradients for filters and biases
        filter_gradients = np.zeros_like(self.filters)
        bias_gradients = np.zeros_like(self.biases)
        
        # Compute gradients (simplified)
        # In practice, this involves rotating filters and performing convolution
        # For now, we'll use a basic approach
        
        channels, height, width = self.input_data.shape
        _, out_height, out_width = output_gradient.shape
        
        # Pad input if necessary
        if self.padding > 0:
            input_padded = np.pad(
                self.input_data,
                ((0, 0), (self.padding, self.padding), (self.padding, self.padding)),
                mode='constant'
            )
        else:
            input_padded = self.input_data
        
        # Compute filter gradients
        for f in range(self.num_filters):
            for i in range(out_height):
                for j in range(out_width):
                    row_start = i * self.stride
                    row_end = row_start + self.filter_size
                    col_start = j * self.stride
                    col_end = col_start + self.filter_size
                    
                    region = input_padded[:, row_start:row_end, col_start:col_end]
                    filter_gradients[f] += output_gradient[f, i, j] * region
            
            bias_gradients[f] = np.sum(output_gradient[f])
        
        # Update filters and biases
        self.filters -= learning_rate * filter_gradients
        self.biases -= learning_rate * bias_gradients
        
        return input_gradient

This convolutional layer can process multi-channel inputs (like RGB images with three channels) and produce multiple output feature maps. Each filter learns to detect a different pattern in the input.

Pooling is another important operation in CNNs. It reduces the spatial dimensions of feature maps, making the network more computationally efficient and providing some translation invariance. The most common type is max pooling, which takes the maximum value in each region:

class MaxPoolingLayer:
    """
    Max pooling layer for downsampling feature maps.
    """
    
    def __init__(self, pool_size=2, stride=2):
        """
        Initialize max pooling layer.
        
        Parameters:
            pool_size: size of pooling window
            stride: stride for pooling operation
        """
        self.pool_size = pool_size
        self.stride = stride
    
    def forward(self, input_data):
        """
        Forward pass through max pooling layer.
        
        Parameters:
            input_data: 3D array (channels, height, width)
        
        Returns:
            Pooled output as 3D array
        """
        self.input_data = input_data
        channels, height, width = input_data.shape
        
        # Calculate output dimensions
        out_height = (height - self.pool_size) // self.stride + 1
        out_width = (width - self.pool_size) // self.stride + 1
        
        # Initialize output
        output = np.zeros((channels, out_height, out_width))
        
        # Store positions of max values for backward pass
        self.max_positions = np.zeros((channels, out_height, out_width, 2), dtype=int)
        
        # Perform max pooling
        for c in range(channels):
            for i in range(out_height):
                for j in range(out_width):
                    row_start = i * self.stride
                    row_end = row_start + self.pool_size
                    col_start = j * self.stride
                    col_end = col_start + self.pool_size
                    
                    region = input_data[c, row_start:row_end, col_start:col_end]
                    output[c, i, j] = np.max(region)
                    
                    # Store position of max value
                    max_pos = np.unravel_index(np.argmax(region), region.shape)
                    self.max_positions[c, i, j] = [
                        row_start + max_pos[0],
                        col_start + max_pos[1]
                    ]
        
        return output
    
    def backward(self, output_gradient):
        """
        Backward pass through max pooling layer.
        
        Parameters:
            output_gradient: gradient from next layer
        
        Returns:
            Gradient to pass to previous layer
        """
        # Initialize input gradient
        input_gradient = np.zeros_like(self.input_data)
        
        channels, out_height, out_width = output_gradient.shape
        
        # Route gradients back to positions where max values came from
        for c in range(channels):
            for i in range(out_height):
                for j in range(out_width):
                    max_row, max_col = self.max_positions[c, i, j]
                    input_gradient[c, max_row, max_col] += output_gradient[c, i, j]
        
        return input_gradient

Max pooling reduces the spatial dimensions by taking the maximum value in each pooling window. During backpropagation, gradients are routed only to the positions where the maximum values came from, since those were the only values that affected the output.

Now let us build a complete CNN for image classification:

class SimpleCNN:
    """
    A simple Convolutional Neural Network for image classification.
    Architecture: Conv -> ReLU -> MaxPool -> Flatten -> FullyConnected -> Softmax
    """
    
    def __init__(self, input_shape, num_filters, filter_size, num_classes):
        """
        Initialize the CNN.
        
        Parameters:
            input_shape: tuple (channels, height, width)
            num_filters: number of convolutional filters
            filter_size: size of convolutional filters
            num_classes: number of output classes
        """
        self.input_shape = input_shape
        channels, height, width = input_shape
        
        # Convolutional layer
        self.conv = ConvolutionalLayer(
            num_filters=num_filters,
            filter_size=filter_size,
            input_channels=channels,
            padding=1
        )
        
        # Max pooling layer
        self.pool = MaxPoolingLayer(pool_size=2, stride=2)
        
        # Calculate size after convolution and pooling
        conv_out_height = height  # Same due to padding=1
        conv_out_width = width
        pool_out_height = conv_out_height // 2
        pool_out_width = conv_out_width // 2
        
        # Flattened size
        flattened_size = num_filters * pool_out_height * pool_out_width
        
        # Fully connected layer
        self.fc_weights = np.random.randn(flattened_size, num_classes) * 0.01
        self.fc_biases = np.zeros((1, num_classes))
    
    def relu(self, x):
        """ReLU activation function."""
        return np.maximum(0, x)
    
    def relu_derivative(self, x):
        """Derivative of ReLU."""
        return (x > 0).astype(float)
    
    def softmax(self, x):
        """Softmax activation for output layer."""
        exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
        return exp_x / np.sum(exp_x, axis=1, keepdims=True)
    
    def forward(self, x):
        """
        Forward pass through the network.
        
        Parameters:
            x: input image (channels, height, width)
        
        Returns:
            Class probabilities
        """
        # Convolutional layer
        self.conv_out = self.conv.forward(x)
        
        # ReLU activation
        self.relu_out = self.relu(self.conv_out)
        
        # Max pooling
        self.pool_out = self.pool.forward(self.relu_out)
        
        # Flatten
        self.flattened = self.pool_out.flatten().reshape(1, -1)
        
        # Fully connected layer
        self.fc_out = np.dot(self.flattened, self.fc_weights) + self.fc_biases
        
        # Softmax
        self.output = self.softmax(self.fc_out)
        
        return self.output
    
    def compute_loss(self, predictions, targets):
        """
        Compute cross-entropy loss.
        
        Parameters:
            predictions: predicted probabilities
            targets: one-hot encoded true labels
        
        Returns:
            Loss value
        """
        # Avoid log(0)
        predictions = np.clip(predictions, 1e-10, 1 - 1e-10)
        return -np.sum(targets * np.log(predictions))
    
    def train_step(self, x, y, learning_rate=0.01):
        """
        Perform one training step.
        
        Parameters:
            x: input image
            y: one-hot encoded label
            learning_rate: learning rate for updates
        
        Returns:
            Loss value
        """
        # Forward pass
        predictions = self.forward(x)
        
        # Compute loss
        loss = self.compute_loss(predictions, y)
        
        # Backward pass (simplified)
        # Gradient of cross-entropy loss with softmax
        output_gradient = predictions - y
        
        # Fully connected layer gradients
        fc_weight_gradient = np.dot(self.flattened.T, output_gradient)
        fc_bias_gradient = output_gradient
        
        # Update fully connected layer
        self.fc_weights -= learning_rate * fc_weight_gradient
        self.fc_biases -= learning_rate * fc_bias_gradient
        
        # Gradient for flattened layer
        flattened_gradient = np.dot(output_gradient, self.fc_weights.T)
        
        # Reshape to pool output shape
        pool_gradient = flattened_gradient.reshape(self.pool_out.shape)
        
        # Backprop through pooling
        relu_gradient = self.pool.backward(pool_gradient)
        
        # Backprop through ReLU
        conv_gradient = relu_gradient * self.relu_derivative(self.conv_out)
        
        # Backprop through convolution
        self.conv.backward(conv_gradient, learning_rate)
        
        return loss

This CNN architecture is similar to early successful models like LeNet. The convolutional layer learns to detect features, the pooling layer reduces dimensionality, and the fully connected layer performs classification based on the learned features.

CNNs are particularly effective for image-related tasks because they exploit the spatial structure of images. The same filter is applied across the entire image, which means the network can detect a pattern regardless of where it appears. This property is called translation invariance and is crucial for tasks like object recognition.

PART 7: RECURRENT NEURAL NETWORKS FOR SEQUENTIAL DATA

While feedforward networks and CNNs work well for fixed-size inputs, many real-world problems involve sequences of varying length: sentences in natural language, time series data, video frames, or DNA sequences. Recurrent Neural Networks (RNNs) are designed to handle sequential data by maintaining a hidden state that captures information about previous inputs.

The key idea behind RNNs is that the network processes one element of the sequence at a time, updating its hidden state at each step. This hidden state acts as a memory, allowing the network to use information from earlier in the sequence when processing later elements.

Let us implement a simple RNN from scratch:

class SimpleRNN:
    """
    A simple Recurrent Neural Network for sequence processing.
    """
    
    def __init__(self, input_size, hidden_size, output_size, learning_rate=0.01):
        """
        Initialize the RNN.
        
        Parameters:
            input_size: dimension of input at each time step
            hidden_size: dimension of hidden state
            output_size: dimension of output
            learning_rate: learning rate for training
        """
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.learning_rate = learning_rate
        
        # Initialize weights
        # Wxh: input to hidden
        self.Wxh = np.random.randn(input_size, hidden_size) * 0.01
        # Whh: hidden to hidden (recurrent connection)
        self.Whh = np.random.randn(hidden_size, hidden_size) * 0.01
        # Why: hidden to output
        self.Why = np.random.randn(hidden_size, output_size) * 0.01
        
        # Initialize biases
        self.bh = np.zeros((1, hidden_size))
        self.by = np.zeros((1, output_size))
    
    def tanh(self, x):
        """Tanh activation function."""
        return np.tanh(x)
    
    def tanh_derivative(self, x):
        """Derivative of tanh."""
        return 1 - np.tanh(x) ** 2
    
    def softmax(self, x):
        """Softmax activation."""
        exp_x = np.exp(x - np.max(x))
        return exp_x / np.sum(exp_x)
    
    def forward(self, inputs):
        """
        Forward pass through the RNN.
        
        Parameters:
            inputs: list of input vectors, one for each time step
        
        Returns:
            tuple of (hidden_states, outputs)
        """
        T = len(inputs)  # Sequence length
        
        # Store hidden states and outputs for each time step
        hidden_states = []
        outputs = []
        
        # Initialize hidden state
        h = np.zeros((1, self.hidden_size))
        
        # Process each time step
        for t in range(T):
            # Get input at current time step
            x = inputs[t].reshape(1, -1)
            
            # Compute new hidden state
            # h_t = tanh(x_t @ Wxh + h_{t-1} @ Whh + bh)
            h = self.tanh(np.dot(x, self.Wxh) + np.dot(h, self.Whh) + self.bh)
            hidden_states.append(h.copy())
            
            # Compute output
            # y_t = h_t @ Why + by
            y = np.dot(h, self.Why) + self.by
            outputs.append(y)
        
        return hidden_states, outputs
    
    def backward(self, inputs, targets, hidden_states, outputs):
        """
        Backward pass through time (BPTT).
        
        Parameters:
            inputs: list of input vectors
            targets: list of target vectors
            hidden_states: list of hidden states from forward pass
            outputs: list of outputs from forward pass
        """
        T = len(inputs)
        
        # Initialize gradients
        dWxh = np.zeros_like(self.Wxh)
        dWhh = np.zeros_like(self.Whh)
        dWhy = np.zeros_like(self.Why)
        dbh = np.zeros_like(self.bh)
        dby = np.zeros_like(self.by)
        
        # Initialize gradient of hidden state
        dh_next = np.zeros((1, self.hidden_size))
        
        # Backpropagate through time
        for t in reversed(range(T)):
            # Get values at current time step
            x = inputs[t].reshape(1, -1)
            h = hidden_states[t]
            y = outputs[t]
            target = targets[t].reshape(1, -1)
            
            # Gradient of output layer
            dy = y - target
            
            # Gradients for output layer weights
            dWhy += np.dot(h.T, dy)
            dby += dy
            
            # Gradient flowing back to hidden state
            dh = np.dot(dy, self.Why.T) + dh_next
            
            # Gradient through tanh (need to compute tanh input)
            # Store the pre-activation during forward pass for accurate gradient
            h_raw = np.arctanh(np.clip(h, -0.9999, 0.9999))  # Approximate inverse
            dh_raw = dh * self.tanh_derivative(h_raw)
            
            # Gradients for hidden layer weights
            dWxh += np.dot(x.T, dh_raw)
            if t > 0:
                dWhh += np.dot(hidden_states[t-1].T, dh_raw)
            dbh += dh_raw
            
            # Gradient for next time step
            dh_next = np.dot(dh_raw, self.Whh.T)
        
        # Clip gradients to prevent exploding gradients
        for gradient in [dWxh, dWhh, dWhy, dbh, dby]:
            np.clip(gradient, -5, 5, out=gradient)
        
        # Update weights
        self.Wxh -= self.learning_rate * dWxh
        self.Whh -= self.learning_rate * dWhh
        self.Why -= self.learning_rate * dWhy
        self.bh -= self.learning_rate * dbh
        self.by -= self.learning_rate * dby
    
    def train_sequence(self, inputs, targets):
        """
        Train on a single sequence.
        
        Parameters:
            inputs: list of input vectors
            targets: list of target vectors
        
        Returns:
            Total loss for the sequence
        """
        # Forward pass
        hidden_states, outputs = self.forward(inputs)
        
        # Compute loss
        loss = 0
        for t in range(len(targets)):
            target = targets[t].reshape(1, -1)
            output = outputs[t]
            loss += np.sum((output - target) ** 2)
        
        # Backward pass
        self.backward(inputs, targets, hidden_states, outputs)
        
        return loss

The RNN processes sequences by maintaining a hidden state that gets updated at each time step. The hidden state at time t depends on both the current input and the previous hidden state, creating a recurrent connection that allows information to flow through time.

The training algorithm for RNNs is called Backpropagation Through Time (BPTT). It works by unrolling the network through time and applying standard backpropagation, but we need to be careful about exploding or vanishing gradients. Gradient clipping helps prevent exploding gradients.

Let us test the RNN on a simple sequence prediction task:

def create_sequence_data():
    """
    Create a simple sequence prediction task.
    Task: Predict the next number in a sequence.
    """
    sequences = []
    
    # Create simple counting sequences
    for start in range(10):
        sequence_input = []
        sequence_target = []
        
        for i in range(5):
            # Input is current number (one-hot encoded)
            current = np.zeros(10)
            current[(start + i) % 10] = 1
            sequence_input.append(current)
            
            # Target is next number (one-hot encoded)
            next_num = (start + i + 1) % 10
            target = np.zeros(10)
            target[next_num] = 1
            sequence_target.append(target)
        
        sequences.append((sequence_input, sequence_target))
    
    return sequences

# Create data
sequence_data = create_sequence_data()

# Create and train RNN
rnn = SimpleRNN(input_size=10, hidden_size=20, output_size=10, learning_rate=0.01)

print("Training RNN on sequence prediction...")
for epoch in range(100):
    total_loss = 0
    for inputs, targets in sequence_data:
        loss = rnn.train_sequence(inputs, targets)
        total_loss += loss
    
    if (epoch + 1) % 20 == 0:
        avg_loss = total_loss / len(sequence_data)
        print(f"Epoch {epoch + 1}, Average Loss: {avg_loss:.4f}")

# Test the trained RNN
print("\nTesting RNN:")
test_input = [np.eye(10)[i] for i in [0, 1, 2, 3, 4]]
_, predictions = rnn.forward(test_input)

print("Input sequence: 0, 1, 2, 3, 4")
print("Predicted next values:")
for i, pred in enumerate(predictions):
    predicted_value = np.argmax(pred)
    print(f"After seeing {i}, predict: {predicted_value}")

RNNs are powerful for many sequential tasks including language modeling, machine translation, speech recognition, and time series forecasting. However, basic RNNs struggle with long-term dependencies due to vanishing gradients. More advanced architectures like LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) address this problem by using gating mechanisms to control information flow.

PART 8: PRACTICAL CONSIDERATIONS AND BEST PRACTICES

Now that we have built neural networks from scratch, let us discuss important practical considerations that separate toy examples from production-ready systems.

Weight initialization is crucial for successful training. Random initialization breaks symmetry so that neurons learn different features, but the scale matters. If weights are too large, activations can saturate and gradients vanish. If weights are too small, signals die out in deep networks. Xavier initialization scales weights based on the number of inputs, which works well for sigmoid and tanh activations. He initialization is similar but designed for ReLU activations.

def xavier_initialization(input_size, output_size):
    """
    Xavier/Glorot initialization for weights.
    Works well with sigmoid and tanh activations.
    """
    limit = np.sqrt(6.0 / (input_size + output_size))
    return np.random.uniform(-limit, limit, (input_size, output_size))

def he_initialization(input_size, output_size):
    """
    He initialization for weights.
    Works well with ReLU activations.
    """
    std = np.sqrt(2.0 / input_size)
    return np.random.randn(input_size, output_size) * std

Learning rate scheduling can significantly improve training. Starting with a larger learning rate allows fast initial progress, then reducing it helps fine-tune the solution. Common strategies include step decay, exponential decay, and cosine annealing.

class LearningRateScheduler:
    """
    Learning rate scheduler with different strategies.
    """
    
    def __init__(self, initial_lr, strategy='step', **kwargs):
        """
        Initialize scheduler.
        
        Parameters:
            initial_lr: starting learning rate
            strategy: 'step', 'exponential', or 'cosine'
            kwargs: strategy-specific parameters
        """
        self.initial_lr = initial_lr
        self.strategy = strategy
        self.params = kwargs
    
    def get_lr(self, epoch):
        """
        Get learning rate for current epoch.
        """
        if self.strategy == 'step':
            # Reduce LR by factor every N epochs
            decay_rate = self.params.get('decay_rate', 0.5)
            decay_epochs = self.params.get('decay_epochs', 100)
            return self.initial_lr * (decay_rate ** (epoch // decay_epochs))
        
        elif self.strategy == 'exponential':
            # Exponential decay
            decay_rate = self.params.get('decay_rate', 0.95)
            return self.initial_lr * (decay_rate ** epoch)
        
        elif self.strategy == 'cosine':
            # Cosine annealing
            total_epochs = self.params.get('total_epochs', 1000)
            min_lr = self.params.get('min_lr', 0.0001)
            return min_lr + 0.5 * (self.initial_lr - min_lr) * (
                1 + np.cos(np.pi * epoch / total_epochs)
            )
        
        return self.initial_lr

Regularization techniques prevent overfitting by constraining the model's complexity. L2 regularization (weight decay) adds a penalty for large weights to the loss function. Dropout randomly sets some activations to zero during training, forcing the network to learn robust features that do not rely on specific neurons.

class RegularizedLayer:
    """
    A fully connected layer with L2 regularization and dropout.
    """
    
    def __init__(self, input_size, output_size, l2_lambda=0.01, dropout_rate=0.5):
        """
        Initialize layer with regularization.
        
        Parameters:
            input_size: number of input features
            output_size: number of output features
            l2_lambda: L2 regularization strength
            dropout_rate: probability of dropping a neuron
        """
        self.weights = he_initialization(input_size, output_size)
        self.biases = np.zeros((1, output_size))
        self.l2_lambda = l2_lambda
        self.dropout_rate = dropout_rate
    
    def forward(self, x, training=True):
        """
        Forward pass with optional dropout.
        
        Parameters:
            x: input data
            training: whether in training mode (applies dropout)
        """
        self.input = x
        self.z = np.dot(x, self.weights) + self.biases
        self.a = np.maximum(0, self.z)  # ReLU activation
        
        if training and self.dropout_rate > 0:
            # Apply dropout
            self.dropout_mask = np.random.binomial(1, 1 - self.dropout_rate, self.a.shape)
            self.a *= self.dropout_mask
            self.a /= (1 - self.dropout_rate)  # Scale to maintain expected value
        
        return self.a
    
    def backward(self, grad_output, learning_rate):
        """
        Backward pass with L2 regularization.
        """
        # Apply dropout mask to gradient
        if hasattr(self, 'dropout_mask'):
            grad_output *= self.dropout_mask
            grad_output /= (1 - self.dropout_rate)
        
        # Gradient through ReLU
        grad_output[self.z <= 0] = 0
        
        # Compute gradients
        grad_weights = np.dot(self.input.T, grad_output)
        grad_biases = np.sum(grad_output, axis=0, keepdims=True)
        
        # Add L2 regularization to weight gradient
        grad_weights += self.l2_lambda * self.weights
        
        # Update parameters
        self.weights -= learning_rate * grad_weights
        self.biases -= learning_rate * grad_biases
        
        # Return gradient for previous layer
        return np.dot(grad_output, self.weights.T)

Batch normalization is another powerful technique that normalizes activations within each mini-batch. This stabilizes training, allows higher learning rates, and acts as a regularizer. The idea is to normalize each feature to have zero mean and unit variance, then learn scale and shift parameters.

class BatchNormalization:
    """
    Batch normalization layer.
    """
    
    def __init__(self, num_features, epsilon=1e-5, momentum=0.9):
        """
        Initialize batch normalization.
        
        Parameters:
            num_features: number of features to normalize
            epsilon: small constant for numerical stability
            momentum: momentum for running statistics
        """
        self.num_features = num_features
        self.epsilon = epsilon
        self.momentum = momentum
        
        # Learnable parameters
        self.gamma = np.ones((1, num_features))  # Scale
        self.beta = np.zeros((1, num_features))  # Shift
        
        # Running statistics for inference
        self.running_mean = np.zeros((1, num_features))
        self.running_var = np.ones((1, num_features))
    
    def forward(self, x, training=True):
        """
        Forward pass through batch normalization.
        
        Parameters:
            x: input data (batch_size, num_features)
            training: whether in training mode
        """
        if training:
            # Compute batch statistics
            batch_mean = np.mean(x, axis=0, keepdims=True)
            batch_var = np.var(x, axis=0, keepdims=True)
            
            # Normalize
            self.x_normalized = (x - batch_mean) / np.sqrt(batch_var + self.epsilon)
            
            # Update running statistics
            self.running_mean = self.momentum * self.running_mean + (1 - self.momentum) * batch_mean
            self.running_var = self.momentum * self.running_var + (1 - self.momentum) * batch_var
            
            # Store for backward pass
            self.batch_mean = batch_mean
            self.batch_var = batch_var
            self.x = x
        else:
            # Use running statistics for inference
            self.x_normalized = (x - self.running_mean) / np.sqrt(self.running_var + self.epsilon)
        
        # Scale and shift
        output = self.gamma * self.x_normalized + self.beta
        return output
    
    def backward(self, grad_output, learning_rate):
        """
        Backward pass through batch normalization.
        """
        batch_size = grad_output.shape[0]
        
        # Gradients for scale and shift
        grad_gamma = np.sum(grad_output * self.x_normalized, axis=0, keepdims=True)
        grad_beta = np.sum(grad_output, axis=0, keepdims=True)
        
        # Update parameters
        self.gamma -= learning_rate * grad_gamma
        self.beta -= learning_rate * grad_beta
        
        # Gradient for normalized input
        grad_x_normalized = grad_output * self.gamma
        
        # Gradient for variance
        grad_var = np.sum(
            grad_x_normalized * (self.x - self.batch_mean) * -0.5 * (self.batch_var + self.epsilon) ** (-1.5),
            axis=0,
            keepdims=True
        )
        
        # Gradient for mean
        grad_mean = np.sum(
            grad_x_normalized * -1 / np.sqrt(self.batch_var + self.epsilon),
            axis=0,
            keepdims=True
        ) + grad_var * np.sum(-2 * (self.x - self.batch_mean), axis=0, keepdims=True) / batch_size
        
        # Gradient for input
        grad_x = (
            grad_x_normalized / np.sqrt(self.batch_var + self.epsilon) +
            grad_var * 2 * (self.x - self.batch_mean) / batch_size +
            grad_mean / batch_size
        )
        
        return grad_x

Mini-batch gradient descent is the standard training approach. Instead of computing gradients on the entire dataset (batch gradient descent) or single examples (stochastic gradient descent), we use small batches. This provides a good balance between computational efficiency and gradient stability.

def create_mini_batches(X, y, batch_size):
    """
    Create mini-batches from dataset.
    
    Parameters:
        X: input data
        y: labels
        batch_size: size of each mini-batch
    
    Returns:
        List of (X_batch, y_batch) tuples
    """
    num_examples = X.shape[0]
    mini_batches = []
    
    # Shuffle data
    indices = np.random.permutation(num_examples)
    X_shuffled = X[indices]
    y_shuffled = y[indices]
    
    # Create mini-batches
    num_complete_batches = num_examples // batch_size
    
    for i in range(num_complete_batches):
        start_idx = i * batch_size
        end_idx = start_idx + batch_size
        X_batch = X_shuffled[start_idx:end_idx]
        y_batch = y_shuffled[start_idx:end_idx]
        mini_batches.append((X_batch, y_batch))
    
    # Handle remaining examples
    if num_examples % batch_size != 0:
        X_batch = X_shuffled[num_complete_batches * batch_size:]
        y_batch = y_shuffled[num_complete_batches * batch_size:]
        mini_batches.append((X_batch, y_batch))
    
    return mini_batches

Advanced optimization algorithms like Adam combine the benefits of momentum and adaptive learning rates. Momentum helps accelerate training by accumulating gradients in consistent directions. Adam maintains per-parameter learning rates that adapt based on gradient history.

class AdamOptimizer:
    """
    Adam optimizer implementation.
    """
    
    def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):
        """
        Initialize Adam optimizer.
        
        Parameters:
            learning_rate: step size
            beta1: exponential decay rate for first moment
            beta2: exponential decay rate for second moment
            epsilon: small constant for numerical stability
        """
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.t = 0  # Time step
        self.m = {}  # First moment estimates
        self.v = {}  # Second moment estimates
    
    def update(self, param_name, param, grad):
        """
        Update parameter using Adam.
        
        Parameters:
            param_name: unique identifier for parameter
            param: parameter array to update
            grad: gradient array
        
        Returns:
            Updated parameter
        """
        # Initialize moments if first time
        if param_name not in self.m:
            self.m[param_name] = np.zeros_like(param)
            self.v[param_name] = np.zeros_like(param)
        
        self.t += 1
        
        # Update biased first moment estimate
        self.m[param_name] = self.beta1 * self.m[param_name] + (1 - self.beta1) * grad
        
        # Update biased second moment estimate
        self.v[param_name] = self.beta2 * self.v[param_name] + (1 - self.beta2) * (grad ** 2)
        
        # Compute bias-corrected first moment estimate
        m_hat = self.m[param_name] / (1 - self.beta1 ** self.t)
        
        # Compute bias-corrected second moment estimate
        v_hat = self.v[param_name] / (1 - self.beta2 ** self.t)
        
        # Update parameter
        param -= self.learning_rate * m_hat / (np.sqrt(v_hat) + self.epsilon)
        
        return param

CONCLUSION: FROM SCRATCH TO PRODUCTION

We have journeyed from the simplest artificial neuron to sophisticated architectures like CNNs and RNNs, building everything from scratch using pure Python and NumPy. This hands-on approach reveals the elegant mathematics underlying neural networks and demystifies the learning process.

The key insights we have explored include the following. Neural networks are compositions of simple operations: weighted sums, non-linear activations, and gradient-based optimization. Backpropagation efficiently computes gradients by applying the chain rule backwards through the network. Vectorization using matrix operations makes training practical for large networks. Different architectures exploit different data structures: fully connected layers for general patterns, convolutional layers for spatial data, and recurrent layers for sequences. Regularization and optimization techniques are essential for training deep networks successfully.

While our implementations are educational, production systems use optimized frameworks like PyTorch and TensorFlow that provide automatic differentiation, GPU acceleration, and extensive libraries of pre-built components. However, understanding the fundamentals we have covered will make you a better practitioner, enabling you to debug problems, design custom architectures, and understand research papers.

The field of deep learning continues to evolve rapidly. Modern architectures like Transformers have revolutionized natural language processing by replacing recurrence with attention mechanisms. Techniques like transfer learning allow us to leverage pre-trained models for new tasks with limited data. Generative models can create realistic images, text, and even code.

As you continue your journey in neural networks, remember that the core principles remain constant: we are fitting flexible functions to data using gradient descent. The art lies in choosing the right architecture, regularization, and optimization strategy for your specific problem. Start simple, understand your data, monitor training carefully, and iterate based on results.

You now have the foundation to implement neural networks from scratch and the understanding to use modern frameworks effectively. The next step is to apply these techniques to real problems, experiment with different architectures, and continue learning from the vibrant deep learning community. Good luck with your neural network adventures!

Monday, November 23, 2026

HOW A MACHINE LEARNS WITHOUT CHANGING ITS MIND - The Full Spectrum of Learning in Mercury Agent 1.4.0




0. A PROMISE, AND THE ONE IDEA THAT MAKES IT INTERESTING


Most people imagine a neural network slowly shifting its weights when they hear that an agent "learns." Mercury Agent does something far more unusual, and once you see it, the whole design clicks into place: Mercury learns intensely and continuously, yet it never changes a single weight of the language model it talks to. Not one. The model stays frozen, anonymous, and replaceable. Everything Mercury remembers, distills, tunes, and improves lives outside the model—in plain tables, Markdown files, and configuration keys that a human can read, audit, correct, and roll back.


This is the red thread of the entire article, so it's worth stating plainly before anything else. Mercury's learning is non-parametric: it does not adjust the parameters of an LLM. Instead, it changes two things that sit around the LLM. It changes the context the model sees at the start of a run, and it changes the configuration that decides which model runs and how. Because both of those are data rather than opaque weights, every lesson Mercury draws is inspectable, every improvement is reversible, and every automatic change can be placed behind a policy and an approval. That single architectural decision turns a clever assistant into a colleague an administrator can actually trust with real credentials. Keep it in mind as we walk through the spectrum; each mechanism we meet is another way of editing context or editing configuration—never of editing the brain.



1. AN INTRODUCTION TO MERCURY AGENT 1.4.0


Mercury Agent (for open source code see Mercury GitHub repository) is a self-hosted, extensible agentic AI platform written in TypeScript and running on Node 22 or newer. "Agentic" is the operative word. A chatbot answers; an agent reasons in a loop, calls tools, remembers what it has done, reflects on the outcome, and acts again until a task is genuinely finished. "Self-hosted" means the whole thing runs on your own machine or server as a single Node process backed by a single SQLite database file; there is no hosted service in the middle, no data leaving your control by default, and your API keys stay in your own environment. "Extensible" means almost every moving part—from tools and reasoning patterns to language-model providers and messaging adapters—is a drop-in you can add without editing the core.


The detail that surprises newcomers, and the detail that matters most for this article, is that Mercury ships with no language model of its own. Before it can say a single useful word, you must point it at a real LLM—whether that's a cloud endpoint such as OpenAI, Anthropic, or an OpenAI-compatible gateway, or a local runtime such as Ollama or LM Studio. This is deliberate. You choose the brain, you own the bill, and you can run fully offline against a local model if you wish. It also means the brain is interchangeable at any moment, which is exactly why none of Mercury's learning is allowed to depend on a particular model's internals. The learning must survive you swapping the model out tomorrow, and so it is built from portable data rather than from fine-tuned weights.


Structurally, Mercury is a monorepo of seven packages arranged in a strict one-way dependency chain. The command-line interface and the HTTP server depend on a runtime package, which depends on the tools, the Model Context Protocol layer and the gateway, all of which depend on a single core package. The core depends only on a schema-validation library, a YAML parser, and the Node built-in modules, and it is where the interesting machinery lives: configuration, the database, authentication, the language-model abstraction and router, the optional decision engine, the agent loop and its reasoning patterns, memory, skills, workflows, the scheduler, security, and the subject of this article—the learning subsystems. The command-line tool, the web server, the gateway and the scheduler are all thin front-ends over the same runtime, which is why a slash command behaves identically whether you type it in the terminal, in the browser panel, or in a Telegram thread.


Version 1.4.0 is the release in which Mercury's learning story becomes a complete spectrum rather than a single feature. Earlier releases gave it post-run reflection and the first cross-run learning. The 1.2.0 release added skills that Mercury distills from its own successful runs and a deterministic replay that lets you travel back through any run. The 1.3.0 release added evaluation-driven self-improvement, where observed behavior becomes a scored regression suite that can drive a governed auto-tuner, together with sharable agent bundles that let one Mercury hand its learned state to another. The 1.4.0 release completes the picture by promoting memory itself into a governed, auditable long-term knowledge layer and by adding multi-agent teams that coordinate through a shared blackboard. Taken together, these form a layered learning architecture that spans timescales from milliseconds to months, and the rest of this article is a guided walk through every layer of it.


Before we descend into the layers, a simple mental picture of where learning sits in a single run will orient everything that follows. A run flows roughly like this, read from left to right:


    user turn

        |

        v

    build context  <----( curated memory, semantic recall, skills index,

        |                  experience hint, proven-skill plan hint, knowledge )

        v

    pick model     <----( router + economics + auto-tuned routing )

        |

        v

    reason + call tools  (the agent loop)

        |

        v

    answer

        |

        v

    reflect + learn ----> ( lessons, user model, new skills, route stats,

                            failure playbooks, distilled skills )


Notice that learning appears twice. On the way in, past learning is consulted to shape the context and the model choice. On the way out, the finished run is mined for new learning. The loop closes on itself, and every arrow in it is an edit to context or configuration—never to the model's weights. That is the whole system in miniature.



2. A TAXONOMY WORTH HOLDING IN YOUR HEAD


It helps architects enormously to classify Mercury's learning before cataloging it, because the catalog is long, and the classification makes it memorable. Three axes do the job.


The first axis is timescale. Some learning happens inside a single run and is discarded when the run ends, such as the compression of the working context. Some happens at the boundary of a run—the moment it finishes—such as reflection and skill distillation. And some accumulates across many runs and persists indefinitely, such as the routing statistics, the failure playbooks, and the long-term memory. Thinking in timescales tells you where the cost lives and how quickly a change becomes visible.


The second axis is the substrate of the lesson, which is really the question: "If Mercury learned something, what file or table changed?" Sometimes the substrate is natural-language memory that is injected back into a prompt, such as a curated fact or a memory lesson. Sometimes it is a procedure—a reusable skill that encodes a sequence of tool calls. Sometimes it is a statistic—a counter that nudges a future decision such as which model to route a task to. And sometimes it is a configuration patch—an actual change to a tuning key. Each substrate has a different blast radius and a different review story.


The third axis is autonomy—the degree to which the lesson is applied without a human in the loop. Some learning is passive and always on, quietly recording evidence. Some proposes a change and waits for approval. And some—only when an administrator has explicitly opted in—applies a change automatically within strict guardrails. The default posture across the platform is conservative: the powerful, autonomous forms of learning are off until you turn them on, and when they are on, they refuse to touch anything a governance policy protects. We will see this posture repeated so often that it becomes a kind of refrain.


With those three axes in hand, the spectrum is easy to navigate. We will walk it from the shortest timescale to the longest, pausing at each station to explain the motivation, the mechanism, the way the lesson is leveraged on the next run, and the controls an administrator has over it.



3. WITHIN THE RUN: WORKING MEMORY AND THE ART OF FORGETTING WELL


The shortest-lived form of learning is the management of the agent's own working memory during a single conversation, and although it is the most ephemeral, it is also the one every user feels first. A language model can only attend to a bounded window of text. As a conversation grows, the transcript eventually threatens to overflow that window, and a naive agent either crashes into the limit or silently drops the oldest messages and loses the thread. Mercury instead learns—within the run—which parts of its own history still matter and which can be compressed into a summary.


The component responsible is the context compressor. On every iteration of the agent loop, it estimates the token footprint of the running message list and compares it against a configured fraction of the active model's context window. The fraction is the compression threshold, and its default is seventy-five percent, which means compaction begins well before the window is actually full so that there is always headroom for the model's reply. When the threshold is crossed, the system prompt is kept verbatim, the most recent handful of messages are kept verbatim, and everything in between is handed to the model to be rewritten as one compact summary message that takes their place. A subtle but important rule governs the cut: a tool call and its result are never separated, so the kept tail is rewound to begin at a clean user message rather than in the middle of a tool exchange. The number of recent messages preserved untouched is itself configurable.


The behavior is driven by a small, legible section of configuration. The values below are the defaults and exist to show the shape of the knobs rather than to be copied blindly:


    agent:

      compression:

        threshold: 0.75   # start compacting at 75% of the model's context window

        keepLast: 6       # keep the six most recent messages verbatim, always


A user who wants to force the behavior rather than wait for the threshold can do so from inside any chat with a single slash command, which is useful just before pasting a large document when you want to clear room deliberately:


    /compress


Why call this learning at all, rather than mere housekeeping? Because the summary the model writes is a genuine act of distillation under a constraint: it must decide what from the last fifty exchanges is still load-bearing for the task and discard the rest without losing the plot. The result is a smaller, denser representation of the same knowledge, produced on the fly, and it directly shapes the quality of every subsequent turn in that conversation. It is learning on the scale of seconds, and it is thrown away when the run ends, which is precisely why it belongs at the near end of our timescale axis.



4. AT THE BOUNDARY OF THE RUN: REFLECTION, LESSONS AND A SELF THAT WRITES ITS OWN SKILLS


The moment a run finishes is the richest learning opportunity Mercury has, because the whole trajectory—every model call, tool call, decision, and guardrail verdict—is now complete and available as evidence. Reflection is the subsystem that mines that completed trajectory, and it is the one users ask about most, usually under two names that turn out to be the same system seen from different angles: "reflections" and "memory lessons."


The motivation is the oldest one in pedagogy. An actor that never reviews its own work repeats its own mistakes forever. Mercury therefore runs a post-task review after a run completes. The review is performed by the decision engine, which may be the optional typed decision model when it is configured, or your ordinary LLM, or—when neither is available—a safe built-in heuristic, so that reflection degrades gracefully rather than demanding extra infrastructure. The review produces up to three distinct artefacts, and understanding the difference between them dissolves most of the confusion around the feature.


The first artefact is a score—an answer-quality judgement of how well the run served its goal, gated by a confidence threshold that defaults to one half. The second artefact is a set of lessons, the "memory lessons" people ask about: short, durable, natural-language takeaways distilled from what went right or wrong, which are stored and then surfaced in later runs so that the same mistake is not made twice. The third artefact is an update to the user model—a refinement of the traits Mercury has inferred about the specific person it is working for. Each of the three can be switched on or off independently, and the whole subsystem has a single master switch:


    reflection:

      enabled: true      # run the post-task review at all

      lessons: true      # store durable memory lessons for future runs

      userModel: true    # refine the inferred, per-user trait profile


A user influences this loop directly and cheaply. After any run, a single rating feeds straight into reflection as an explicit signal of success or failure, and the lessons and scores can later be browsed through the reflections panel in the web interface or read over the HTTP API:


    /feedback good

    /feedback bad


The most striking part of reflection is what happens when a run was not only successful but substantial. When a run reached its goal and used at least a configured minimum number of tool calls, with the default minimum being four, and automatic skill creation is enabled, reflection can turn the successful sequence of actions into a brand-new skill. Mercury, in other words, writes its own procedural memory. It observes that it just solved a class of problem through a particular dance of tools, generalizes that dance, and files it away so that next time the same class of problem can be solved by replaying a known-good procedure rather than by reasoning from scratch. It can also refine an existing skill with fresh success statistics rather than duplicating it. This is the point at which the second axis of our taxonomy—the substrate of the lesson—shifts from natural-language memory to executable procedure, and it is the hinge between this section and the next.



5. THE AGENT THAT DISTILLS ITS OWN PLAYBOOK: SELF-DISTILLING SKILLS


Reflection can create a skill as a side effect of review, but Mercury 1.4.0 also contains a dedicated, more rigorous engine whose entire job is to distill reusable, parameterized skills from winning runs. It lives in its own module and is worth treating separately, because it embodies the governance refrain more clearly than almost anything else in the platform.


A skill in Mercury is a procedure written in the open agentskills.io format: a Markdown file with a little frontmatter naming the skill and describing when it applies, followed by the body of the procedure. Progressive disclosure keeps these cheap. Only the index—the name and the one-line description—sits in the system prompt, so an agent can carry hundreds of skills without bloating its context; the full body is loaded on demand only when a skill is actually invoked. The distiller's contribution is to manufacture such skills automatically from experience.


The mechanism is careful. The distiller subscribes to the event bus and wakes on two signals: a run that ended in success, and a run that received an explicit positive rating. When it wakes, it reads that run's sequence of tool calls and generalizes the concrete argument values into named parameters, so that a run which happened to summarize one particular PDF becomes a skill for summarizing any PDF. The product is a candidate skill carrying a trigger phrase, a parameter list, an ordered set of steps, and a record of which runs it was distilled from. Crucially, the whole engine is off at its master switch by default; until an administrator enables it, nothing is distilled, matched, or recorded at all.


    skills:

      distill:

        enabled: false         # master switch; nothing happens until true

        autoApprove: false     # candidates stay "pending" until a human approves

        minToolCalls: 4        # a winning run needs at least this many tool calls

        dedupMinSimilarity: 0.8  # near-identical triggers update, not duplicate

        matchMinSimilarity: 0.6  # how close a new task must be to reuse a skill

        retireBelowSuccessRate: 0.5  # demote a skill that stops working

        minRunsBeforeRetire: 5   # but only after enough evidence

        maxSkills: 200           # cap retention; oldest retired pruned first


Several of these keys tell a story about evidence and humility rather than about mechanics, and it is worth reading them as a policy. Because a candidate lands with a pending status and is inert until approved, a newly distilled skill cannot influence any run until a human has blessed it—unless the administrator has deliberately switched on automatic approval. Because a trigger that is very similar to an existing skill updates that skill and bumps its version rather than inserting a near-duplicate, the library stays clean as experience accumulates. And because every use of an approved skill updates counters for uses, successes, failures, and cost, a skill that looked good when it was born but that quietly stops working in the field will see its observed success rate fall, and once it has enough runs behind it and drops below the retirement threshold, it is auto-retired. The agent is thus not only writing its own playbook but also pruning the plays that no longer win.


The payoff arrives on the next matching task. When a new request comes in, Mercury looks for an approved distilled skill whose trigger is similar enough to the request, and if it finds one, it injects the proven path into the system prompt as a strong plan hint, effectively telling itself: "You have solved this exact kind of thing before, and here is the procedure that worked." The agent then executes a known-good sequence instead of rediscovering it, which is faster, cheaper, and more reliable. This is procedural memory functioning exactly as it does in a skilled human: the first time is deliberate and slow, and every time afterwards is fluent.



6. ACROSS MANY RUNS: THE LEARNING SERVICE


We now cross from the boundary of a single run to the accumulation of evidence across the whole history of runs, which is where Mercury's cross-run learning service lives. It is driven entirely by the real runs table and the event bus, with no external state and no separate training job, and like the distiller, it is off at its master switch by default so that nothing is recorded, injected, or adjusted until an administrator opts in. It performs three independent kinds of learning, each separately toggleable, and together they form the backbone of Mercury getting better at its job over time.


    learning:

      enabled: true          # master switch (default false)

      hints:

        enabled: true

        maxExamples: 3       # example values shown to convey the shape

        minSimilarity: 0.3

        lookback: 200

      routing:

        minSamples: 20       # need this many observations before trusting a model

        minSuccessRate: 0.8  # and this observed success rate before preferring it

      playbooks:

        enabled: true

        minOccurrences: 3

        minSimilarity: 0.4


The first kind is experience hints. When a new task arrives, the service searches the history for the most similar past run that actually succeeded, using a cheap token-overlap similarity so that the lookup costs almost nothing, and from the best matches it distills a short natural-language hint that is injected into the run's starting context. Conceptually, the agent does this to itself at the top of a run:


    // Look for the closest past SUCCESSFUL run and, if one exists, fold its

    // lesson into the system prompt before the model ever sees the task.

    const hint = learning.hintFor(task, userId);

    if (hint) {

      systemPrompt += "\n\nLearned from past runs:\n" + hint;

    }


The honesty of this design is in the "if." When no sufficiently similar successful run exists, there is simply no hint, and the agent proceeds unaided rather than being handed an irrelevant and possibly misleading example. Learning here is strictly additive and strictly earned.


The second kind is auto-tuned routing, and it is the clearest example in the platform of learning expressed as a statistic that steers a decision. Every finished run updates a small table keyed by a pair: the difficulty bucket that the task was judged to fall into, and the model that handled it. For each pair, the table tracks how many runs there were, how many succeeded, and how much they cost in money and tokens. The router, which ordinarily chooses a model from rules, capabilities, and a cost-quality-latency score, exposes an optional seam through which this accumulated evidence can override its first choice. Conceptually, the seam is this tiny interface:


    // A RouteLearner lets observed outcomes override the router's first pick,

    // but only once enough evidence has accumulated to justify it.

    interface RouteLearner {

      // Return the model with the best observed success rate for this

      // difficulty bucket, or null to leave the router's own choice intact.

      suggest(bucket: string, candidates: string[]): string | null;

    }


The guardrails are everything. The learner returns a suggestion only once a bucket has cleared a minimum number of samples and a minimum observed success rate, with ties broken in favor of the cheaper model; until then, it returns nothing and the router keeps its own economics-driven choice. When the learner does override, the resulting routing decision is flagged as adjusted by learning, so the change is never silent and always traceable. Over weeks of operation, this quietly moves routine work onto whichever model has proven cheapest-yet-reliable for that class of task, and reserves the expensive models for the buckets that genuinely need them—all without anyone hand-tuning a routing table.


The third kind is failure playbooks, which is institutional memory for things that go wrong. When a run fails, its error is normalized into a stable signature by stripping out the volatile parts—the identifiers, numbers, quoted paths, and hex strings—so that a thousand superficially different failures collapse into a handful of recurring shapes. When a later, similar task eventually succeeds, what worked is recorded as the remediation for that signature. Thereafter, when a task matches a known failure signature or a run trips over a known error, Mercury can surface the remediation that resolved it last time. The failure, in other words, is only suffered properly once; afterwards, it becomes advice.


Every part of this is readable from outside, which matters as much as the learning itself. An administrator can inspect the accumulated statistics, ask what hint a given task would receive, and review the playbooks—all from the command line or the HTTP API—and a dedicated panel in the web interface renders the status, the routing table, and the playbooks for a human to audit:


    mercury learn stats

    mercury learn hints "summarise a quarterly PDF and email the team"

    mercury learn playbooks


One design principle deserves emphasis because it recurs throughout the platform: learning must never break a run. Every piece of recording is wrapped so that a failure in the learning machinery is swallowed rather than allowed to derail the actual work. The agent's job comes first; getting better at it is a strictly secondary activity that is never permitted to get in the way.



7. THE LONG MEMORY: SIX KINDS, NOW GOVERNED


If the learning service is how Mercury improves its behavior, memory is how it retains knowledge, and Mercury does not have "a memory" in the singular; it has six, each with a different job and all scoped per user. The working memory we met in section three is the first and shortest. The second is episodic memory—the full searchable history of past sessions stored with a full-text index so that any earlier conversation can be found and summarized. The third is semantic memory—a store of discrete facts that can be remembered, recalled by meaning, and forgotten on request, backed by both full-text search and a vector index. The fourth is curated memory—two small hand-editable Markdown files per user. The fifth is procedural memory—the skills we have already discussed. And the sixth is the user model together with a shared blackboard that multi-agent runs coordinate through.


The two curated files repay a closer look because they are the most human part of the whole system. One file holds facts the agent should always know, such as your timezone, your stack, and your standing preferences; the other holds what Mercury has inferred about you over time. Both are deliberately small, bounded by character limits of roughly a couple of thousand characters and a bit over a thousand characters respectively, and the smallness is the point: curated memory is injected into every prompt, so it must stay high-signal, and the bound forces a constant, healthy triage of what truly deserves to be always-on. You can edit these files by hand, through a slash command, or through the web panel, which means a human can correct the agent's self-updated understanding directly—a property that pure weight-based learning can never offer.


Semantic facts behave in the way a user intuitively expects of memory, and the natural-language interface hides the machinery:


    remember that our staging database host is db-stage.internal

    what is our staging database host?

    forget the staging database detail


The embeddings that give recall its sense of meaning are themselves pluggable. The default provider is a deterministic hash-based embedding that needs no API key and no network, which keeps a fresh install working entirely offline, while an administrator who wants true semantic similarity can switch to a real embeddings provider. This is the same philosophy as the replaceable brain: a sensible, zero-configuration default that works today, and a clean upgrade path when you want more.


The headline memory advance in 1.4.0 is that this whole subsystem is lifted into a governed, auditable knowledge layer, while every existing call keeps working unchanged because governance is soft or off by default. Three capabilities arrive together. The first is governance proper: before a fact is written or read, it can be routed through policy, scanned for personally identifiable information such as email addresses, card numbers, national identifiers, IP addresses, and phone numbers, and then either redacted or blocked according to configuration, with every decision—whether allow, deny, or redact—recorded to an audit ledger and to the global audit bus. Conceptually, the write path looks like this, and the comment is the whole point of it:


    // Governance runs BEFORE a fact is persisted. Detect PII, then redact or

    // block per policy, and only the clean text is ever written to storage.

    const { redacted, matches } = scanPii(rawFact);

    if (matches.length > 0 && policy === "block") {

      throw new Error("fact rejected: contains PII");

    }

    store.remember(redacted, { namespace });   // only the clean text persists


The second capability is structure and hygiene. Facts now carry a namespace dimension on top of their per-user scope, so knowledge can be partitioned by project or domain, and a retention policy can prune by age or by a maximum number of items per namespace so that memory does not grow without bound. The third capability is retrieval-augmented knowledge. Whole documents can be ingested by splitting them into overlapping chunks, embedding each chunk, and storing it with its source, after which a hybrid of full-text and vector search recalls the most relevant chunks together with their provenance, so that an answer grounded in your documents can cite where it came from. The ingestion half of that is as simple as this in spirit:


    // Ingestion: split a document into overlapping chunks and store each one

    // with its source, so later recall can prove where an answer came from.

    for (const chunk of chunkText(document, { size: 800, overlap: 100 })) {

      await knowledge.add(chunk, { source: path, embed: embeddings });

    }


When knowledge is enabled, it quietly grounds the context-building step of every run, which closes a loop that the earlier sections opened: the same context that is shaped by experience hints and proven-skill plan hints is now also shaped by grounded, cited knowledge drawn from your own corpus. All of it is reachable from the command line and the HTTP interface, and a memory-and-knowledge panel renders it for inspection, with the audit log being a first-class, queryable object rather than a hidden side effect:


    mercury memory remember "we deploy on Tuesdays, never on Fridays"

    mercury memory ns                       # list the namespaces in use

    mercury memory knowledge add ./runbooks/tls-rotation.md

    mercury memory knowledge search "how do we rotate TLS certificates?"

    mercury memory audit                    # read the governance decision ledger


The governance story is the clearest proof of the article's thesis. Because every remembered fact is text in a table rather than a weight in a network, it can be scanned, redacted, namespaced, expired, audited, and deleted. None of those verbs has any meaning for a fine-tuned weight. Mercury's choice to learn into data rather than into parameters is exactly what makes a compliant, forgettable, explainable memory possible at all.



8. CLOSING THE LOOP WITH EVIDENCE: EVALUATION-DRIVEN SELF-IMPROVEMENT


Everything so far improves Mercury's inputs, its context, and its model choice. The evaluation subsystem goes one step further and lets Mercury improve its own configuration, under tight governance, on the strength of measured evidence. It is the most autonomous form of learning in the platform and therefore the most carefully fenced. The scoring harness itself is on by default because measuring is harmless, but the auto-tuner that can act on those measurements is off by default because acting is not.


The loop begins by turning real behavior into a test. Any real run, or any run a user rated positively, can be promoted into a labeled evaluation case that captures the input along with the tools the run used, the substrings its output contained, and the cost it incurred, and cases are grouped into suites. These are not synthetic benchmarks; they are the agent's own good days, frozen so that tomorrow's changes can be checked against them.


Scoring is deterministic and pure. Running a suite executes every case through an ephemeral, non-reflecting agent run and scores each one against clear criteria: a case passes when the run did not error, used all the tools the reference run used, produced all the expected substrings, and stayed within the cost ceiling, while a similarity measure compares the new output to the reference. The per-case results are then combined into a single number between zero and one that blends the pass rate, the cost per task, the intervention rate, and the output similarity according to configurable weights, and that number is persisted over time so that quality becomes a trend you can watch rather than a feeling you argue about.


    evals:

      enabled: true            # the scoring harness runs by default

      costCeiling: 0.02        # per-task cost ceiling, in your currency unit

      autotune:

        enabled: false         # governed auto-tuning is OFF by default

        autoApply: false       # even when enabled, propose rather than apply

        minImprovement: 0.05   # accept a change only if it beats the suite by >=5%


The auto-tuner is where learning becomes a configuration patch, and the gate it must pass through is strict in three independent ways. A proposal might change model routing, a reasoning pattern, a temperature, the promotion or retirement of a skill, or a prompt, and before any of that can take effect, it is measured against the suite. The first gate is governance: any proposal that would touch a protected area of configuration—the security settings, the governance settings, the approvals, or the policies—is rejected outright, so the tuner can never widen its own powers. The second gate is cost: a proposal whose cost per task would exceed the ceiling is rejected regardless of how much it improves quality. The third gate is merit: a proposal is accepted only if it improves the aggregate score by at least the configured minimum margin. Even after passing all three, a proposal is applied automatically only when both the auto-tuning switch and the auto-apply switch are on; otherwise, it is simply returned for a human to review.


The final safeguard is that every applied change is versioned and reversible. When a tune is applied, the previous values are captured and written into a versioned record, and a single operation restores those captured values and marks the record reverted, idempotently. An administrator who arrives on Monday to find that the agent tuned itself over the weekend can read exactly what changed, see the evidence that justified it, and undo it completely with one command if they disagree. This is self-improvement that an auditor can live with, and it is only possible because the thing being improved is legible configuration rather than an inscrutable weight update.



9. CARRYING LEARNING ELSEWHERE: AGENT BUNDLES


A lesson that cannot leave the machine it was learned on is of limited value to an organization. Because all of Mercury's learning is data, it can be packaged, and the agent-bundles subsystem does exactly that. A bundle is a signed, portable package of an agent's configuration and learned assets—its skills, its tuned settings, and the rest of the state that makes one Mercury behave like a seasoned specialist—which can be exported, downloaded, carried to another installation, and installed there. One team can train a research assistant or a support triage agent through weeks of real use and reflection, and then hand that accumulated competence to another team as a single artefact rather than as a wiki page of instructions to be re-implemented by hand. This portability is a direct dividend of the non-parametric design: you cannot easily extract and transplant "the part of a fine-tuned model that got good at your runbooks," but you can absolutely zip up a folder of skills, facts, and configuration and sign it.



10. A DIFFERENT SHAPE OF KNOWLEDGE: THE LLM WIKI


One further learning activity rounds out the spectrum and deserves honest framing. Mercury contains an ingestion-time knowledge base inspired by the "LLM wiki" pattern, in which raw sources are stored immutably, the model synthesizes and continually updates a set of cross-linked pages from them, and an index ties the whole thing together, with support for detecting contradictions and for linting recently changed pages. It is a complement to the retrieval-augmented knowledge of section seven: where that layer chunks and retrieves documents close to their original form, the wiki actively rewrites many sources into a coherent, navigable body of synthesized knowledge. Honesty requires noting what the project itself notes: that the synthesis, query, and contradiction-detection quality of the wiki has been exercised against a test-local fake rather than validated against a real language model, so an architect should treat it as a promising mechanism to evaluate rather than as a proven, battle-tested path. The platform's own status documentation is the authority on exactly which subsystems have and have not been validated end to end, and it is the right place to check before depending on any single capability in production.



11. HOW THE LAYERS COOPERATE: ONE TASK, SEEN THROUGH THE LEARNING LENS


To see the spectrum working as a single organism rather than as ten separate features, follow one realistic task through it. An administrator asks Mercury, for the fifth time this quarter, to pull a vendor's PDF invoice, extract the totals, reconcile them against a ledger, and email a summary to finance.


As the run begins, several forms of past learning converge on the context before the model emits a token. Curated memory reminds the agent of the finance distribution list and the house rule never to send external email without approval. The learning service finds the four earlier successful invoice runs and folds a short hint drawn from them into the prompt. The distiller recognizes the request as matching an approved, proven skill and injects the known-good procedure as a strong plan hint. If grounded knowledge is enabled, the relevant lines of the reconciliation runbook are retrieved with their provenance. Meanwhile, the router, consulting the routing statistics for this difficulty bucket, quietly selects the model that has handled invoice reconciliation most reliably and most cheaply over the preceding months. None of this required a human this morning; all of it was learned on earlier mornings and is being spent now.


The run then executes, and because so much proven context was front-loaded, it tends to proceed fluently rather than exploratorily. When it finishes, the second half of the loop engages. Reflection scores the outcome and, if the user rates it well, may refine the invoice skill with fresh success statistics. The learning service updates the routing table for this bucket and, if anything went wrong and was later resolved, records a remediation in the failure playbooks. If evaluation is configured, this very run can be promoted into a case so that future changes to the agent are measured against the standard this run just set. The organism has consumed its past learning and produced new learning, and the model at the centre of it all is exactly as it was before: unchanged, replaceable, and none the wiser, while the data around it grew measurably smarter.



12. WHAT THIS MEANS FOR YOU, BY ROLE


For a developer, the practical consequence is that you extend Mercury's intelligence mostly by shaping data and honouring seams rather than by training anything. You can author skills in a documented Markdown format, let the distiller propose more, and reach every learning signal through a clean facade and a REST surface, which makes the learning observable from your own tooling and testable without a GPU in sight. The interfaces that matter—the route-learner seam, the memory facade, the evaluation store—are small and typed, and the whole system is designed so that a failure in any learning path is swallowed rather than allowed to break the run you actually care about.


For an administrator, the governance refrain is the headline. The powerful, autonomous forms of learning—cross-run learning, skill distillation, and auto-tuning—are off until you deliberately enable them, and even when enabled, they refuse to touch protected configuration, respect cost ceilings, require a margin of proven improvement before acting, and record everything they do in a ledger you can read and a history you can revert. Memory can scan for and redact sensitive data, partition knowledge into namespaces, expire it on a schedule, and prove every decision after the fact. You are never asked to trust a black box; you are given a set of switches, a cost meter, an audit log, and an undo button.


For an architect, the lesson is the thesis we began with, now earned rather than merely asserted. By refusing to encode learning in model weights and insisting instead that every lesson