build neural network from scratch numpy

Build Neural Network from Scratch with Numpy

By Daniel Lee
AD

Embarking on a journey to build a neural network from scratch can be an enriching and enlightening experience for any aspiring data scientist or machine learning enthusiast. While libraries like TensorFlow and PyTorch have made the process more seamless, delving into the fundamentals with plain NumPy offers an unparalleled understanding of the underlying mechanisms.

Building a neural network from scratch requires a robust grasp of mathematics, specifically linear algebra and calculus, as well as a strong foundation in programming. Python, with its NumPy and SciPy libraries, provides an excellent environment for this task due to its ease of use and efficient numerical computation capabilities.

Understanding the Building Blocks

Before diving into the construction of a neural network, it's crucial to understand its fundamental components. These include neurons, layers, and the connections between them, collectively referred to as edges. In statistical terms, these structures implement a function that maps inputs to outputs, enabling the network to learn from data.

AD
Building Convolutional Neural Network using NumPy from Scratch - KDnuggets
Building Convolutional Neural Network using NumPy from Scratch - KDnuggets
Build a Convolutional Neural Network from Scratch using Numpy | Towards Data Science
Build a Convolutional Neural Network from Scratch using Numpy | Towards Data Science
How to build a neural network from zero | Towards Data Science
How to build a neural network from zero | Towards Data Science

NumPy arrays serve as the perfect platform to represent these components. Scalar values represent neurons, matrices represent layers, and tensor products define the connections between them.

Neurons and Layers

Neurons are the basic processing units of a neural network. They take weighted inputs, sum them up, and apply an activation function to produce an output. In NumPy, a simple way to represent a neuron is to define a function that takes a vector of weights and a vector of inputs:

Artificial Neural Networks (ANN) Explained 🧠 | Build, Train & Predict with Python
Artificial Neural Networks (ANN) Explained 🧠 | Build, Train & Predict with Python
Build Your Own Neural Networks: Step-By-Step Explanation For Beginners
Build Your Own Neural Networks: Step-By-Step Explanation For Beginners
Make Your Own Neural Networks
Make Your Own Neural Networks
```python import numpy as np def neuron(weights, inputs): return np.dot(weights, inputs) ```

For a layer of neurons, we can apply this function to each neuron in the layer. Here's how you might represent a fully connected layer in NumPy:

Edges and Weight Matrices

Edges in a neural network represent the connections between neurons. Each edge has a weight, which determines how much influence the input neuron has on the output neuron. These weights are organized into matrices, known as weight matrices or simply weights.

AD

In NumPy, weights can be represented as matrices. For instance, a weight matrix connecting a layer of 4 neurons to another layer of 3 neurons would look like this:

Neural Networks Explained from Scratch using Python
Neural Networks Explained from Scratch using Python
Building a neural network FROM SCRATCH (no Tensorflow/Pytorch, just numpy & math)
Building a neural network FROM SCRATCH (no Tensorflow/Pytorch, just numpy & math)
Building a Recurrent Neural Network from Scratch
Building a Recurrent Neural Network from Scratch
Building a Deep Neural Network from Scratch using Numpy | Towards Data Science
Building a Deep Neural Network from Scratch using Numpy | Towards Data Science
Coding A Neural Network From Scratch in NumPy | Towards Data Science
Coding A Neural Network From Scratch in NumPy | Towards Data Science
How CNN (Convolutional neural network) works
How CNN (Convolutional neural network) works
```python weights = np.random.rand(4, 3) ```

To compute the output of a layer given its inputs and weights, we simply perform a matrix multiplication:

```python outputs = np.dot(inputs, weights) ```

Building the Network

With the building blocks in place, we can now construct a neural network. At its core, a neural network is just a stack of layers connected together through weight matrices. The forward pass through the network involves applying each layer's activation function to its inputs.

AD

A simple neural network might look like this in NumPy:

Neural networks fundamentals with Python – intro
Neural networks fundamentals with Python – intro
How to build a three-layer neural network from scratch
How to build a three-layer neural network from scratch
neural network
neural network
Recurrent Neural Networks (RNNs) Explained Simply 🚀 RNN Architecture + Python Code
Recurrent Neural Networks (RNNs) Explained Simply 🚀 RNN Architecture + Python Code
two diagrams showing different types of neurons and their functions in the human body
two diagrams showing different types of neurons and their functions in the human body
an image of several different types of networked devices and their connections to each other
an image of several different types of networked devices and their connections to each other
🧠 What is a Neural Network?
🧠 What is a Neural Network?
PySpark Neural Network from Scratch | Towards Data Science
PySpark Neural Network from Scratch | Towards Data Science
Coding up a Neural Network classifier from scratch
Coding up a Neural Network classifier from scratch
How to build your own Neural Network from scratch in Python
How to build your own Neural Network from scratch in Python
Convolutional Neural Networks (CNN) Explained 🖼️ | Deep Learning for Image Classification
Convolutional Neural Networks (CNN) Explained 🖼️ | Deep Learning for Image Classification
Building a Convolutional Neural Network (CNNs) from Scratch | Towards Data Science
Building a Convolutional Neural Network (CNNs) from Scratch | Towards Data Science
Artificial Neural Network Implementation using NumPy and Image Classification - KDnuggets
Artificial Neural Network Implementation using NumPy and Image Classification - KDnuggets
Build an Artificial Neural Network From Scratch: Part 1 - KDnuggets
Build an Artificial Neural Network From Scratch: Part 1 - KDnuggets

Forward Propagation

The forward pass involves multiplying the inputs by the weight matrix, adding a bias term, and finally applying an activation function. Here's a simple implementation of forward propagation in NumPy:

```python def forward(inputs, weights, bias, activation): return activation(np.dot(inputs, weights) + bias) ```

This function takes in the inputs to the layer, the weight matrix connecting to this layer, the bias terms for each neuron in the layer, and the activation function to apply. It returns the outputs of the layer.

AD

Backpropagation

After forward propagation, we need a way to adjust the weights and biases to minimize the error in our predictions. This is where backpropagation comes in. Backpropagation works by computing the gradient of the error with respect to the weights and biases, and then updating them in the direction that reduces the error.

Implementing backpropagation from scratch involves computing gradients using the chain rule from calculus. While NumPy doesn't have built-in support for automatic differentiation, it does provide tools that make implementing backpropagation easier. The numpy.grad function can be used to compute gradients, and numpy.linalg.solve can be used to solve the system of linear equations that arises during weight updates.

Once you have your backpropagation implementation, you can use an optimization algorithm like stochastic gradient descent to update your weights and biases. Over time, these updates will cause your network to learn from its mistakes and improve its performance.

Training the Network

With forward propagation, backpropagation, and gradient descent in place, we're ready to train our neural network. Training involves looping through the data, making predictions, calculating the error, and updating the weights and biases. This process is known as an epoch, and it's repeated many times until the network converges on a solution.

The following is a simple example of how you might train a neural network using NumPy:

```python def train(inputs, outputs, weights, biases, activation, loss_func, learning_rate): # Forward pass predictions = forward(inputs, weights, biases, activation) # Calculate error error = loss_func(predictions, outputs) # Backward pass and weight update gradients = np.grad(loss_func)(predictions, outputs) weights -= learning_rate * gradients[0] biases -= learning_rate * gradients[1] return weights, biases ```

In this example, the training function takes in the input data, the desired output, the current weights and biases, the activation function, the loss function, and the learning rate. It returns the updated weights and biases.

Training a neural network involves running this function many times, each time updating the weights and biases based on the calculated gradients. Over time, the network learns to map inputs to outputs more accurately.

Once your network is trained, you can use it to make predictions on new, unseen data. Simply run the forward propagation function on the input data to get the output. This is known as inference, and it's the primary way neural networks make predictions in the real world.

Building a neural network from scratch with NumPy may seem like a daunting task, but it's an incredibly rewarding one. By understanding the fundamentals of neural networks and implementing them from scratch, you gain a deep insight into how these powerful models work. And, as a bonus, you'll have a toolkit in NumPy that you can apply to a wide range of machine learning and data analysis tasks.

AD