Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 21

Feedforward Neural Network Architecture

This lesson is built with resources from turing.com and deeplearningwizard.com.

Hello! Welcome to the first lesson in our new module, Deep Learning with PyTorch.

In the previous module, you built a solid foundation in model training fundamentals. We explored how to train models from scratch using gradient descent, evaluate them, and use regularization techniques like L1/L2 and Dropout to combat overfitting. Now, we'll transition from these "from-scratch" implementations to using PyTorch, a powerful and widely-used deep learning framework that will allow us to build and train complex models much more efficiently. This shift is similar to moving from writing raw database queries to using an ORM (Object-Relational Mapper) in backend development—it handles the low-level details so you can focus on the high-level architecture.

Today's lesson addresses the learning outcome: Describe the architecture of a feedforward neural network, including layers, neurons, and weights. We will dissect the most fundamental type of neural network, understanding its components and how they fit together. This is the "Hello, World!" of neural network architectures and the foundation for the advanced models we'll study later.

1. What is a Feedforward Neural Network?

A Feedforward Neural Network (FNN), also known as a Multi-Layer Perceptron (MLP), is the simplest type of artificial neural network. Its defining characteristic is that information flows in only one direction—forward. Data enters through the input layer, passes through one or more "hidden" layers, and exits through the output layer. There are no loops or cycles in the network, hence the term "feedforward."

To get a more formal introduction, let's start with a short reading.

Understanding Feed Forward Neural Networks in Deep ...

This article from Turing.com provides a concise definition of a feedforward neural network and its basic working principle.

Please read the sections 'What is a feed forward neural network?' and 'What is the working principle of a feed forward neural network?'. Focus on the core idea of information flowing in one direction and the high-level description of how inputs are processed.


2. The Core Components of a Neural Network

Now, let's break down the architecture of an FNN into its three main components: layers, neurons, and weights.

Feedforward Neural Network Architecture
This diagram shows a typical feedforward neural network. Data flows from the input layer (x) on the left, through one or more hidden layers (h), to the output layer (y) on the right. Each connection has a weight (W), and each neuron in the hidden and output layers applies an activation function (φ) to its inputs.

Let's examine each part in detail, using this diagram as our reference.

Layers

A neural network is organized into a series of layers.

  • Input Layer: This is the entry point of the network. It doesn't perform any computation; it simply passes the raw input data (your features) to the first hidden layer. The number of neurons in this layer is equal to the number of features in your dataset. For example, if you're trying to predict a house price from 5 features (e.g., area, number of bedrooms, etc.), your input layer will have 5 neurons.

  • Hidden Layers: These are the intermediate layers between the input and output layers. They are the true computational engines of the network. Each neuron in a hidden layer receives inputs from the previous layer, performs a calculation, and passes the result to the next layer. The "deep" in "deep learning" refers to having multiple hidden layers. The number of hidden layers and the number of neurons in each are key hyperparameters that you, the architect, will decide.

  • Output Layer: This is the final layer that produces the model's prediction. The structure of this layer depends on the task:

    • Regression: For predicting a single continuous value (e.g., price), the output layer typically has just one neuron.
    • Classification: For an N-class classification problem (e.g., classifying an image as one of 10 digits), the output layer will have N neurons, one for each class.

Neurons (or Nodes)

A neuron is the basic computational unit of the network. It takes in multiple inputs, processes them, and produces an output. A single neuron performs two simple mathematical operations:

  1. Weighted Sum: It calculates a weighted sum of its inputs, then adds a bias. If the inputs are and the corresponding weights are , the calculation is:

    This is a linear transformation, just like in the linear regression model you built in the previous module. The w and b are the learnable parameters of the neuron.

  2. Activation Function: The result of the weighted sum, , is then passed through a non-linear activation function, .

    This non-linearity is crucial. Without it, stacking multiple layers would be mathematically equivalent to a single linear layer, and the network wouldn't be able to learn complex patterns. We will explore different activation functions in detail in the next lesson.

Weights and Biases

Weights () and biases () are the parameters of the network. These are the numbers that the model "learns" during the training process through gradient descent.

  • A weight represents the strength of the connection between two neurons. A large positive weight means the input from one neuron strongly excites the next neuron, while a large negative weight means it strongly inhibits it.
  • A bias can be thought of as a way to shift the activation function to the left or right, making it easier or harder for the neuron to activate.

The entire process of training is about finding the optimal values for all the weights and biases in the network to minimize the loss function.

This next reading summarizes these components clearly.

Understanding Feed Forward Neural Networks in Deep ...

This section of the Turing.com article provides clear definitions for each of the components we've just discussed.

Read the subsections under 'Layers of feed forward neural network', starting from 'Input layer' and ending with 'Activation Function'. This will reinforce your understanding of layers, neurons, weights, and the role of activation functions.

Test your understanding!

Imagine you are building a simple FNN with one hidden layer.

  • The input layer has 10 neurons (for 10 features).
  • The hidden layer has 5 neurons.
  • The output layer has 1 neuron (for a regression task).

Ignoring biases, how many weights are there in total in this network?

Show answer

There are two sets of weights:

  1. From the input layer to the hidden layer: Each of the 10 input neurons is connected to each of the 5 hidden neurons. So, there are weights.
  2. From the hidden layer to the output layer: Each of the 5 hidden neurons is connected to the single output neuron. So, there are weights.

Total number of weights = .


3. From Architecture to PyTorch Code

Understanding the architecture conceptually is the first step. As a software engineer, the next step is seeing how it's implemented in code. In PyTorch, a model's architecture is defined within a Python class that inherits from torch.nn.Module.

You typically define two key methods:

  • __init__(self): The constructor. Here, you declare all the layers your network will use (e.g., linear layers, activation functions).
  • forward(self, x): This method defines the forward pass. You specify how the input data x flows through the layers you defined in __init__.

Let's look at a concrete example of a simple FNN with one hidden layer.

Feedforward Neural Network with PyTorch

This article from DeepLearningWizard provides a practical walkthrough of building an FNN in PyTorch. We'll focus on how the architecture is defined in code.

Please read the sections 'Step 3: Create Model Class' and 'Step 4: Instantiate Model Class'. Pay close attention to the FeedforwardNeuralNetModel class definition. Notice how nn.Linear is used to create the layers in __init__ and how they are connected in the forward method.

As you saw in the reading, the code to define the architecture is surprisingly concise:

import torch.nn as nn

class FeedforwardNeuralNetModel(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(FeedforwardNeuralNetModel, self).__init__()
        # Define the layers
        self.fc1 = nn.Linear(input_dim, hidden_dim)  # Layer 1: Input -> Hidden
        self.sigmoid = nn.Sigmoid()                  # Activation Function
        self.fc2 = nn.Linear(hidden_dim, output_dim) # Layer 2: Hidden -> Output

    def forward(self, x):
        # Define the data flow
        out = self.fc1(x)
        out = self.sigmoid(out)
        out = self.fc2(out)
        return out

The nn.Linear(in_features, out_features) module automatically creates the weight matrix and bias vector for you. For self.fc1, PyTorch creates a weight matrix of size (hidden_dim, input_dim) and a bias vector of size (hidden_dim,).


4. Inspecting the Model Parameters

One of the benefits of using a framework like PyTorch is that you can easily inspect the objects you create. We can "look inside" our model and see the parameters (weights and biases) that it has created. This is a great way to verify that the architecture you've built matches your theoretical understanding.

Feedforward Neural Network with PyTorch

Let's continue with the same article to see how to inspect the model's parameters. This is like debugging or examining an object's properties in standard software engineering.

Read the subsection 'Parameters In-Depth'. This section shows you how to access model.parameters() and print the size of the weights and biases for each linear layer. Try to connect the tensor shapes shown (e.g., torch.Size([100, 784])) back to the input_dim and hidden_dim of the model.

This ability to programmatically inspect the dimensions of your model's parameters is invaluable for debugging, especially as you start building more complex architectures. It confirms that the data will flow through your network with the correct dimensions at each step.


5. Building Deeper Networks

The real power of this modular approach becomes clear when you want to build a "deeper" network with more hidden layers. You simply define more nn.Linear layers in __init__ and chain them together in the forward method.

Feedforward Neural Network with PyTorch

Finally, let's see how easy it is to extend our simple FNN to a deeper one with three hidden layers.

Skim through the code under 'Model E: 3 Hidden Layer Feedforward Neural Network (ReLU Activation)'. You don't need to read the whole text, just focus on the FeedforwardNeuralNetModel class definition. Notice how it now has fc1, fc2, fc3, and fc4 linear layers, each followed by an activation function in the forward method. This demonstrates the 'building block' nature of defining network architectures.

This composability is a core design principle of PyTorch and makes experimenting with different architectures very straightforward.


Conclusion

In this lesson, we've established the fundamental blueprint of a feedforward neural network. You've transitioned from the theoretical underpinnings of model training to the practical reality of defining a neural network architecture in PyTorch.

Key Takeaways:

  • A Feedforward Neural Network (FNN) processes information in one direction through an input layer, one or more hidden layers, and an output layer.
  • The network is composed of neurons, which compute a weighted sum of their inputs and apply a non-linear activation function.
  • Weights and biases are the learnable parameters of the network, adjusted during training to minimize a loss function.
  • In PyTorch, network architectures are defined as classes inheriting from nn.Module, with layers declared in __init__ and the data flow defined in the forward method.
  • Building deeper networks is as simple as adding more layers to these two methods.

Next up:

We briefly mentioned activation functions as a critical component that introduces non-linearity. In the next lesson, we will dive deep into this topic. You will learn to apply common activation functions including Sigmoid, Tanh, and ReLU, understanding their mathematical properties, advantages, and disadvantages, and when to choose one over the other.