Build Neural Network from Scratch with Numpy
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.
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:
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.
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:
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.
A simple neural network might look like this in NumPy:
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.
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.