Python

Building Neural Networks from Scratch Using NumPy

When developers start learning deep learning, they usually begin with PyTorch or TensorFlow. These frameworks make it easy to create neural networks, train…

D
DevByteTechnical Author
Published
13 min read0 views
Building Neural Networks from Scratch Using NumPy

When developers start learning deep learning, they usually begin with PyTorch or TensorFlow. These frameworks make it easy to create neural networks, train models, and generate predictions.

But there is something important happening behind those simple APIs.

When you write model.fit() or loss.backward(), the framework performs several mathematical operations, including matrix multiplication, activation functions, gradient calculation, and weight updates.

Understanding these operations makes it much easier to debug models, experiment with architectures, and understand how deep learning actually works.

In this tutorial, we'll build a neural network from scratch using NumPy. We'll use the MNIST handwritten digit dataset, which contains images of handwritten numbers from 0 to 9.

Our objective is to create a model that receives an image and predicts which digit it represents.

We'll implement the important parts ourselves:

  • Forward propagation

  • ReLU activation

  • Softmax activation

  • Cross-entropy loss

  • Backpropagation

  • Gradient descent

  • Model evaluation

  • Saving and loading model parameters

We'll use NumPy for all neural network calculations. Scikit-learn will only help us download the dataset and split it into training and testing data.

1. Understand the Neural Network We Are Building

Before writing code, let's understand the architecture.

MNIST contains grayscale images of handwritten digits, each measuring 28 × 28 pixels.

That means every image contains:

[
28 \times 28 = 784
]

pixel values.

We'll flatten each image into a one-dimensional array containing 784 features.

Our neural network will have three layers:

Input Layer
784 Neurons
     |
     v
Hidden Layer
128 Neurons
ReLU Activation
     |
     v
Output Layer
10 Neurons
Softmax Activation
     |
     v
Predicted Digit
0 to 9

The input layer receives pixel values. The hidden layer learns patterns such as edges, curves, and shapes. The output layer produces a probability for each possible digit.

For example, the output might look like:

Digit 0: 0.01
Digit 1: 0.02
Digit 2: 0.03
Digit 3: 0.04
Digit 4: 0.01
Digit 5: 0.05
Digit 6: 0.02
Digit 7: 0.78
Digit 8: 0.03
Digit 9: 0.01

The model predicts digit 7 because it has the highest probability.

2. Set Up the Python Project

Create a project directory:

mkdir numpy-neural-network
cd numpy-neural-network

Create a virtual environment:

python -m venv venv

Activate it on macOS or Linux:

source venv/bin/activate

On Windows:

venv\Scripts\activate

Install the required libraries:

pip install numpy scikit-learn matplotlib

Our project structure will look like this:

numpy-neural-network/
│
├── main.py
├── model.py
├── requirements.txt
└── model_weights.npz

The neural network implementation will be written using NumPy. We won't use a deep learning framework to perform training or automatic differentiation.

3. Load the MNIST Dataset

We'll use the MNIST dataset containing 70,000 handwritten digit images.

Scikit-learn provides a convenient way to download it through OpenML.

Create main.py:

import numpy as np

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split

print("Downloading MNIST dataset...")

mnist = fetch_openml(
    "mnist_784",
    version=1,
    as_frame=False
)

X = mnist.data.astype(np.float32)

y = mnist.target.astype(np.int64)

print("Dataset shape:", X.shape)
print("Labels shape:", y.shape)

The expected dataset dimensions are:

Dataset shape: (70000, 784)
Labels shape: (70000,)

Each row in X represents one image, and each corresponding value in y represents its actual digit.

For example:

X[0] = [0, 0, 0, 12, 45, ...]
y[0] = 5

The pixel values represent grayscale intensity, while the label tells us which digit the image contains.

4. Normalize the Image Data

The original pixel values range from 0 to 255.

Feeding these large values directly into a neural network can make training less stable.

We'll normalize them to a range between 0 and 1.

X = X / 255.0

The transformation is simple:

[
x_{\text{normalized}} = \frac{x}{255}
]

For example:

Original pixel: 255
Normalized:     1.0

Original pixel: 128
Normalized:     0.502

Original pixel: 0
Normalized:     0.0

Normalization gives the network more manageable input values and helps the optimization process.

5. Split Training and Testing Data

We should not evaluate a neural network using the same images it learned from.

Otherwise, we might measure how well it memorizes training examples instead of how well it recognizes unseen digits.

We'll use 60,000 images for training and 10,000 for testing.

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=10000,
    random_state=42,
    stratify=y
)

print("Training data:", X_train.shape)
print("Testing data:", X_test.shape)

Expected output:

Training data: (60000, 784)
Testing data: (10000, 784)

The stratify=y argument helps preserve the class distribution across both datasets.

The model will learn using X_train and y_train. We'll use the testing dataset only after training to measure its performance.

6. Understand the Mathematics Behind a Neuron

Before implementing the network, let's look at how an individual neuron works.

A neuron receives input values, multiplies them by weights, adds a bias, and applies an activation function.

The mathematical expression is:

[
z = x_1w_1+x_2w_2+\cdots+x_nw_n+b
]

Or in matrix notation:

[
Z = XW+b
]

Here:

  • (X) represents input values.

  • (W) represents weights.

  • (b) represents bias.

  • (Z) represents the result before activation.

The activation function transforms this result.

For our hidden layer, we'll use ReLU.

[
ReLU(x)=\max(0,x)
]

This means negative values become zero, while positive values remain unchanged.

In Python:

def relu(x):
    return np.maximum(0, x)

The derivative of ReLU is:

[
ReLU'(x)=
\begin{cases}
1 & x>0\
0 & x\leq0
\end{cases}
]

We need this derivative later during backpropagation.

def relu_derivative(x):
    return (x > 0).astype(np.float32)

7. Implement the Softmax Activation Function

Our output layer has ten neurons because there are ten possible digits.

We need a function that converts the output values into probabilities.

Softmax does exactly that.

[
Softmax(z_i)=
\frac{e^{z_i}}{\sum_j e^{z_j}}
]

Implement it:

def softmax(x):

    shifted = x - np.max(
        x,
        axis=1,
        keepdims=True
    )

    exp_values = np.exp(shifted)

    return exp_values / np.sum(
        exp_values,
        axis=1,
        keepdims=True
    )

Notice that we subtract the maximum value before calculating exponentials.

This is a numerical stability technique. It prevents unnecessarily large exponential values that could otherwise cause overflow.

For each input image, softmax produces ten probabilities whose sum is approximately 1.

8. Initialize the Neural Network Weights

Our model contains two trainable layers:

784 input features → 128 hidden neurons
128 hidden neurons → 10 output neurons

Each connection has a weight, and each neuron has a bias.

We'll use He initialization for the first layer and a standard deviation suitable for the output layer.

input_size = 784
hidden_size = 128
output_size = 10

np.random.seed(42)

W1 = (
    np.random.randn(input_size, hidden_size)
    * np.sqrt(2.0 / input_size)
)

b1 = np.zeros((1, hidden_size))

W2 = (
    np.random.randn(hidden_size, output_size)
    * np.sqrt(2.0 / hidden_size)
)

b2 = np.zeros((1, output_size))

The weight matrices have these dimensions:

Parameter

Shape

W1

(784, 128)

b1

(1, 128)

W2

(128, 10)

b2

(1, 10)

Why not initialize every weight to zero?

If all neurons in the same layer start with identical weights, they can learn identical patterns. Random initialization helps break this symmetry.

9. Implement Forward Propagation

Forward propagation is the process of passing input data through the neural network to generate predictions.

For our architecture, the operations are:

[
Z_1=XW_1+b_1
]

[
A_1=ReLU(Z_1)
]

[
Z_2=A_1W_2+b_2
]

[
A_2=Softmax(Z_2)
]

Here, (A_2) contains the predicted class probabilities.

Implement the function:

def forward(X):

    Z1 = np.dot(X, W1) + b1

    A1 = relu(Z1)

    Z2 = np.dot(A1, W2) + b2

    A2 = softmax(Z2)

    return Z1, A1, Z2, A2

Let's understand the dimensions.

For a batch of 64 images:

X  = (64, 784)

W1 = (784, 128)

Z1 = (64, 128)

A1 = (64, 128)

W2 = (128, 10)

Z2 = (64, 10)

A2 = (64, 10)

The output contains ten probabilities for each image.

This is the complete forward pass of our neural network.

10. Calculate the Loss Using Cross-Entropy

Generating predictions isn't enough. The model needs to know how wrong its predictions are.

For classification, we'll use categorical cross-entropy.

The formula is:

[
L=-\frac{1}{m}
\sum_{i=1}^{m}\log(p_{i,y_i})
]

Here:

  • (m) is the number of observations in a batch.

  • (p_{i,y_i}) is the predicted probability assigned to the correct class.

For example, suppose the actual digit is 7.

If the model predicts a probability of 0.90 for digit 7, the loss is relatively small.

If it predicts a probability of 0.05 for digit 7, the loss is much larger.

Implement the loss:

def cross_entropy_loss(y_true, y_pred):

    m = y_true.shape[0]

    correct_probabilities = y_pred[
        np.arange(m),
        y_true
    ]

    correct_probabilities = np.clip(
        correct_probabilities,
        1e-12,
        1.0
    )

    loss = -np.mean(
        np.log(correct_probabilities)
    )

    return loss

The np.clip() operation prevents taking the logarithm of zero.

A lower loss generally means the model is assigning higher probabilities to the correct classes.

11. Implement Backpropagation

This is the most important part of building a neural network from scratch.

Forward propagation generates predictions. Backpropagation calculates how the weights and biases contributed to the prediction error.

We use these gradients to update the parameters and improve future predictions.

For softmax combined with cross-entropy, the gradient of the output layer is:

[
dZ_2=\frac{A_2-Y}{m}
]

We don't need to manually calculate the complete derivative of softmax and cross-entropy separately because their combined derivative simplifies to this expression.

The output-layer gradients are:

[
dW_2=A_1^T dZ_2
]

[
db_2=\sum dZ_2
]

Then we propagate the gradients to the hidden layer:

[
dA_1=dZ_2W_2^T
]

[
dZ_1=dA_1\odot ReLU'(Z_1)
]

Finally:

[
dW_1=X^T dZ_1
]

[
db_1=\sum dZ_1
]

Let's implement these calculations.

def backward(
    X,
    y,
    Z1,
    A1,
    A2
):

    m = X.shape[0]

    # Output layer gradient

    dZ2 = A2.copy()

    dZ2[
        np.arange(m),
        y
    ] -= 1

    dZ2 /= m

    dW2 = np.dot(
        A1.T,
        dZ2
    )

    db2 = np.sum(
        dZ2,
        axis=0,
        keepdims=True
    )

    # Hidden layer gradient

    dA1 = np.dot(
        dZ2,
        W2.T
    )

    dZ1 = (
        dA1 *
        relu_derivative(Z1)
    )

    dW1 = np.dot(
        X.T,
        dZ1
    )

    db1 = np.sum(
        dZ1,
        axis=0,
        keepdims=True
    )

    return dW1, db1, dW2, db2

Every gradient has the same shape as the parameter it updates.

For example:

dW1 → (784, 128)
db1 → (1, 128)

dW2 → (128, 10)
db2 → (1, 10)

This is important because a shape mismatch during backpropagation usually indicates an error in the mathematical operations.

12. Update the Model Parameters Using Gradient Descent

Now that we have calculated the gradients, we need to update the weights.

Gradient descent adjusts the parameters in the direction that reduces the loss.

The update rule is:

[
W_{\text{new}}=W_{\text{old}}-\alpha dW
]

Here, (\alpha) is the learning rate.

We'll use a learning rate of 0.1 as a starting point.

learning_rate = 0.1

Implement the update function:

def update_parameters(
    dW1,
    db1,
    dW2,
    db2
):

    global W1, b1, W2, b2

    W1 -= learning_rate * dW1

    b1 -= learning_rate * db1

    W2 -= learning_rate * dW2

    b2 -= learning_rate * db2

The global keyword allows this example to update the weights defined outside the function.

For a larger project, it's better to keep parameters inside a model class instead of relying on global variables.

13. Build the Training Loop

We now have all the essential components:

  • Forward propagation

  • Loss calculation

  • Backpropagation

  • Parameter updates

Let's combine them into a training process.

We'll use mini-batch gradient descent with a batch size of 64.

epochs = 10

batch_size = 64

for epoch in range(epochs):

    permutation = np.random.permutation(
        X_train.shape[0]
    )

    X_shuffled = X_train[permutation]

    y_shuffled = y_train[permutation]

    total_loss = 0

    for start in range(
        0,
        X_train.shape[0],
        batch_size
    ):

        end = start + batch_size

        X_batch = X_shuffled[start:end]

        y_batch = y_shuffled[start:end]

        # Forward propagation

        Z1, A1, Z2, A2 = forward(X_batch)

        # Calculate loss

        loss = cross_entropy_loss(
            y_batch,
            A2
        )

        # Backpropagation

        dW1, db1, dW2, db2 = backward(
            X_batch,
            y_batch,
            Z1,
            A1,
            A2
        )

        # Update parameters

        update_parameters(
            dW1,
            db1,
            dW2,
            db2
        )

        total_loss += loss * len(X_batch)

    average_loss = (
        total_loss / len(X_train)
    )

    print(
        f"Epoch {epoch + 1}/{epochs} "
        f"Loss: {average_loss:.4f}"
    )

During each epoch, the model processes all training observations in batches.

The training data is shuffled before each epoch so the model doesn't always see examples in the same order.

As training progresses, we expect the loss to decrease.

If the loss becomes unstable or increases significantly, check the learning rate, weight initialization, and gradient calculations.

14. Evaluate the Model on Test Data

After training, we need to check how well the model recognizes images it hasn't seen before.

We'll use the test dataset to calculate classification accuracy.

def predict(X):

    _, _, _, probabilities = forward(X)

    return np.argmax(
        probabilities,
        axis=1
    )

The np.argmax() function returns the index of the highest probability.

For example:

Probabilities:

[0.01, 0.02, 0.03, 0.04, 0.01,
 0.05, 0.02, 0.78, 0.03, 0.01]

Prediction: 7

Calculate accuracy:

predictions = predict(X_test)

accuracy = np.mean(
    predictions == y_test
)

print(
    f"Test Accuracy: {accuracy * 100:.2f}%"
)

The result will depend on initialization, training configuration, and the implementation.

For a simple network like this, accuracy in the mid-to-high 90% range is a reasonable experimental target, not a guaranteed result.

If your model performs poorly, investigate the training loss and verify each step before changing the architecture.

15. Test the Model on Individual Images

Let's inspect one image from the test dataset.

import matplotlib.pyplot as plt

index = 10

image = X_test[index].reshape(
    28,
    28
)

actual_digit = y_test[index]

predicted_digit = predict(
    X_test[index:index + 1]
)[0]

plt.imshow(
    image,
    cmap="gray"
)

plt.title(
    f"Actual: {actual_digit}, "
    f"Predicted: {predicted_digit}"
)

plt.axis("off")

plt.show()

This displays the handwritten digit alongside the model's prediction.

You can change the index value to inspect different test images.

This is a useful debugging technique because overall accuracy doesn't tell us which kinds of digits the model struggles to recognize.

For example, handwritten 4s and 9s can sometimes look similar depending on how they are written.

16. Save the Trained Neural Network

We shouldn't need to train the network every time we want to make predictions.

NumPy provides np.savez() for saving multiple arrays in one file.

np.savez(
    "model_weights.npz",
    W1=W1,
    b1=b1,
    W2=W2,
    b2=b2
)

The file stores all four parameter arrays.

To load them later:

data = np.load(
    "model_weights.npz"
)

W1 = data["W1"]

b1 = data["b1"]

W2 = data["W2"]

b2 = data["b2"]

The model can now make predictions using its previously learned parameters without repeating the training process.

In a production implementation, you should also store model configuration details, such as input dimensions and preprocessing rules, alongside the parameters.

17. Important Improvements to Make

Our implementation demonstrates the fundamentals, but there are several improvements worth making before using it in a larger project.

Add a validation dataset

Currently, we train using the training data and evaluate using the test data.

For serious experiments, create three separate datasets:

  • Training data for learning model parameters.

  • Validation data for tuning hyperparameters and monitoring overfitting.

  • Test data for final evaluation.

Avoid repeatedly tuning the model against the test set.

Experiment with learning rates

A learning rate of 0.1 is only a starting point.

Try values such as:

learning_rates = [
    0.001,
    0.01,
    0.1
]

A learning rate that's too high can cause unstable training. A rate that's too low may require many more epochs.

Add regularization

A neural network can overfit when it learns training examples too closely.

Regularization methods such as L2 weight decay and dropout can help control this problem.

Add more hidden layers

You can experiment with deeper architectures, but more layers do not automatically produce better results.

Always compare the results using validation data.

Perform gradient checking

Backpropagation contains several mathematical operations, so a small mistake can affect the entire training process.

Gradient checking compares analytical gradients with numerical approximations.

For a parameter (w), a numerical approximation is:

[
\frac{\partial L}{\partial w}
\approx
\frac{L(w+\epsilon)-L(w-\epsilon)}{2\epsilon}
]

This is especially useful when implementing a neural network without an automatic differentiation framework.

18. What We Actually Learned by Building a Neural Network from Scratch

The most valuable part of this exercise isn't the final accuracy score.

It's understanding what deep learning frameworks perform internally.

When you create a model using PyTorch:

model = nn.Sequential(
    nn.Linear(784, 128),
    nn.ReLU(),
    nn.Linear(128, 10)
)

PyTorch manages the mathematical operations and model parameters.

When you train it:

loss.backward()
optimizer.step()

PyTorch handles gradient calculation and parameter updates.

In our NumPy implementation, we wrote these operations ourselves.

We explicitly calculated matrix multiplication, activation functions, gradients, and weight updates.

That understanding becomes useful when you start experimenting with custom neural networks, loss functions, and training algorithms.

Conclusion

Building neural networks from scratch using NumPy is one of the best ways to understand the fundamentals of deep learning.

We started with handwritten digit images from MNIST and implemented a complete feed-forward neural network without using PyTorch or TensorFlow for training.

We covered forward propagation, ReLU, softmax, cross-entropy loss, backpropagation, gradient descent, and model evaluation.

Although this implementation is not intended to replace production deep learning frameworks, it provides a clear look at how neural networks learn from data.

Once you understand these fundamentals, working with PyTorch and TensorFlow becomes much easier because their high-level APIs are no longer mysterious.

You know what happens behind the scenes, why gradients matter, and how a network gradually improves its predictions.

Official References

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘