A Beginner Guide to Neural Networks
LearningMachine LearningNeural NetworksDeep Learning

A Beginner Guide to Neural Networks

2023-01-06

If you're reading this, chances are you've at least heard of the concept, but for those who may be new to the topic: a neural network is a type of machine learning model inspired by the structure and function of the brain. These models are composed of layers of interconnected nodes, which process and transmit information in the form of data inputs and outputs. Neural networks have been incredibly successful in a variety of applications, including image and speech recognition, natural language processing, and even playing games like chess and Go.

In this post, we'll build up the basic foundation of how neural networks work under the hood, piece by piece — from a single neuron to a full training loop. Whether you're a seasoned machine learning practitioner or a curious learner, I hope you find this article informative and enjoyable.

Neural Network Layers

A neural network is composed of layers of interconnected nodes. The input layer receives the raw input data, and the output layer produces the final prediction or decision based on the computations performed by the hidden layers. The hidden layers perform intermediate computations on the data, and can vary in number and size depending on the complexity of the task and the desired network architecture.

A neural network with an input layer, two hidden layers, and an output layerA neural network with an input layer, two hidden layers, and an output layer

To fully understand the network, let's dig into how a single neuron works.

The Neuron

At the heart of a neural network are artificial neurons — interconnected nodes that process and transmit information. It's the way these neurons are connected, and the way they learn from data, that makes neural networks so powerful. A neuron uses a set of weights and biases to convey information through the different layers of the network.

A single artificial neuron: inputs, weights, bias, and an activation functionA single artificial neuron: inputs, weights, bias, and an activation function

A simplified description of what happens inside a single neuron:

  • The neuron receives some input xx, usually a number or a vector of numbers.
  • Each input is multiplied by a weight ww, which describes the strength of that connection. Weights are learnable parameters — adjustable numbers that get tuned to find an optimal output.
  • A bias bb is added. It's used to adjust the output of the neuron even when the input is zero, which helps the model fit the data better.
  • These are combined into a linear function zz, the weighted sum of the inputs plus the bias:
z=∑i=1nwixi+bz = \sum_{i=1}^{n} w_i x_i + b
  • Finally, an activation function ff is applied to zz to produce the neuron's output:
a=f(z)a = f(z)

The activation function is what introduces non-linearity into the model, letting the network learn far more complex patterns than a simple weighted sum ever could.

Activation Functions

An activation function is applied in every neuron to introduce non-linearity, so the network can learn more complex data structures. It's applied element-wise to the output of the previous layer, transforming the data into a space where it's easier for the model to extract useful features and make predictions. Here are a few common ones:

Sigmoid — maps the input to the range (0,1)(0, 1), which makes it useful for binary classification tasks. However, sigmoid saturates for large inputs: the output flattens out and the gradient vanishes, which can make the model slow or difficult to train.

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

Sigmoid — plot

Sigmoid plot

Hyperbolic tangent (tanh) — similar to sigmoid, but maps the input to the range (−1,1)(-1, 1). It saturates even more strongly than sigmoid, but it's zero-centered, which can make it easier to train with certain optimization algorithms.

tanh⁡(z)=ez−e−zez+e−z\tanh(z) = \frac{e^{z} - e^{-z}}{e^{z} + e^{-z}}

Tanh — plot

Tanh plot

Rectified Linear Unit (ReLU) — a simple, popular activation function that outputs the input directly if it's positive, and zero otherwise. It's fast to compute and works well in practice for many tasks.

ReLU(z)=max⁡(0,z)\text{ReLU}(z) = \max(0, z)

ReLU — plot

ReLU plot

Training

Training a neural network happens in two phases: forward propagation and backward propagation.

The forward pass feeds the input data through the layers of the network to produce a prediction. That prediction is then compared to the ground truth, and the error is calculated using a loss function.

The backward pass adjusts the weights and biases of the network to reduce that error. The error is "backpropagated" through the layers, and each weight and bias is nudged in the opposite direction of the error gradient, using an optimization algorithm such as stochastic gradient descent.

The forward and backward passes are repeated over many epochs, until the model reaches a satisfactory level of performance. The model is then evaluated on a separate test set to measure how well it generalizes, and to make sure it isn't just overfitting the training data.

A Worked Example

Let's make this concrete with a single neuron: two inputs x1=0.5x_1 = 0.5 and x2=0.8x_2 = 0.8, weights w1=0.4w_1 = 0.4 and w2=−0.6w_2 = -0.6, a bias b=0.1b = 0.1, a sigmoid activation, and a target output y=1y = 1.

Forward pass — compute the linear function, then the activation:

z=w1x1+w2x2+b=(0.4)(0.5)+(−0.6)(0.8)+0.1=−0.18z = w_1 x_1 + w_2 x_2 + b = (0.4)(0.5) + (-0.6)(0.8) + 0.1 = -0.18
a=σ(z)=11+e0.18≈0.455a = \sigma(z) = \frac{1}{1 + e^{0.18}} \approx 0.455

Using a simple squared error, L=12(a−y)2\mathcal{L} = \frac{1}{2}(a - y)^2, this prediction gives us a loss of:

L=12(0.455−1)2≈0.1485\mathcal{L} = \frac{1}{2}(0.455 - 1)^2 \approx 0.1485

Backward pass — walk backward through the chain rule to find how much each weight is responsible for that error:

∂L∂a=a−y≈−0.545∂a∂z=a(1−a)≈0.248∂L∂z=∂L∂a⋅∂a∂z≈−0.135\frac{\partial \mathcal{L}}{\partial a} = a - y \approx -0.545 \qquad \frac{\partial a}{\partial z} = a(1 - a) \approx 0.248 \qquad \frac{\partial \mathcal{L}}{\partial z} = \frac{\partial \mathcal{L}}{\partial a} \cdot \frac{\partial a}{\partial z} \approx -0.135
∂L∂w1=∂L∂z⋅x1≈−0.068∂L∂w2=∂L∂z⋅x2≈−0.108∂L∂b=∂L∂z≈−0.135\frac{\partial \mathcal{L}}{\partial w_1} = \frac{\partial \mathcal{L}}{\partial z} \cdot x_1 \approx -0.068 \qquad \frac{\partial \mathcal{L}}{\partial w_2} = \frac{\partial \mathcal{L}}{\partial z} \cdot x_2 \approx -0.108 \qquad \frac{\partial \mathcal{L}}{\partial b} = \frac{\partial \mathcal{L}}{\partial z} \approx -0.135

Each gradient points in the direction that increases the loss, so a gradient descent step nudges every parameter the other way. With a learning rate of 0.10.1: w1←w1−0.1×(−0.068)≈0.407w_1 \leftarrow w_1 - 0.1 \times (-0.068) \approx 0.407, and likewise for w2w_2 and bb. You can verify all of this yourself:

import numpy as np x = np.array([0.5, 0.8]) w = np.array([0.4, -0.6]) b = 0.1 y = 1.0 lr = 0.1 # Forward pass z = np.dot(w, x) + b a = 1 / (1 + np.exp(-z)) loss = 0.5 * (a - y) ** 2 # Backward pass dL_da = a - y da_dz = a * (1 - a) dL_dz = dL_da * da_dz dL_dw = dL_dz * x dL_db = dL_dz # Gradient descent update w -= lr * dL_dw b -= lr * dL_db print(f"a={a:.3f}, loss={loss:.4f}") print(f"updated w={w}, updated b={b:.5f}")

Loss

When we perform backpropagation, we need a loss (or error) function to tell the network how far off its predictions are. Which loss function to use depends on the problem: for classification, where the output is a class label, we typically use a loss that measures class probabilities, such as cross-entropy:

LCE=−∑iyilog⁡(y^i)\mathcal{L}_{CE} = -\sum_{i} y_i \log(\hat{y}_i)

For regression, where the output is a continuous value, we typically use a loss that measures the distance between the predicted and true value, such as mean squared error:

LMSE=1n∑i=1n(yi−y^i)2\mathcal{L}_{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2

The plot below shows what we're trying to achieve: we start with randomly initialized weights, and use backpropagation to nudge each parameter in the direction that minimizes the loss, step by step, until the error settles near a minimum.

Gradient descent — plot

Starting from a random initial weight, each step nudges the weight against the gradient — the slope of the cost curve at that point — moving it closer to the minimum cost.

Gradient descent plot

I hope you found this introduction to neural networks helpful, and that you now have a better understanding of how they work under the hood. If you enjoyed this post, feel free to reach out or follow along for future posts and projects.

References: