Programming In Python 2 - U6
Exercise 1: SimpleNetwork Class Implementation
- In this exercise we just have to implement class with 5 trainable of Linear Layers with an activation func which is passed as an argument.
# From pdf
def __init__(
self,
input_neurons: int,
hidden_neurons: list,
output_neurons: int,
use_bias: bool,
activation_function: torch.nn.Module = torch.nn.ReLU()
):
Define a structure for our class. Define an __init__ method and a forward() method.
import torch
class SimpleNetwork(torch.nn.Module):
def __init__(
self,
input_neurons: int,
hidden_neurons: list,
output_neurons: int,
use_bias: bool,
activation_function: torch.nn.Module = torch.nn.ReLU()
):
super().__init__()
self.activation_function = activation_function # Because we need to use it in forward method
def forward(self, x: torch.tensor):
pass
Define the layers in the __init__ method. We will use torch.nn.Linear for the layers.
- input_neurons is the number of input neurons that our network should use.
- The rest of the layer is hidden_neurons.
- output_neurons is the number of output neurons.
In the end we will have 5 layers.
which should look like this,
input_neurons → hidden_neurons[0] → hidden_neurons[1] → hidden_neurons[2] → hidden_neurons[3] → output_neurons
self.fc1 = torch.nn.Linear(input_neurons, hidden_neurons[0], use_bias)
self.fc2 = torch.nn.Linear(hidden_neurons[0], hidden_neurons[1], use_bias)
self.fc3 = torch.nn.Linear(hidden_neurons[1], hidden_neurons[2], use_bias)
self.fc4 = torch.nn.Linear(hidden_neurons[2], output_neurons, use_bias)
That’s it for the __init__ method.
Now the forward() method.
We will use the activation function that is passed as an argument to the class.
Just use it after each layer.
def forward(self, x: torch.tensor):
l1 = self.activation_function(self.fc1(x))
l2 = self.activation_function(self.fc2(l1))
l3 = self.activation_function(self.fc3(l2))
output = self.fc4(l3) # No activation func for output because it was mentioned in the assignment.
return output
That’s it for the SimpleNetwork class.
Test it with the following code. (Pulled from the pdf)
if __name__ == "__main__":
torch.random.manual_seed(1234)
simple_network = SimpleNetwork(40, [10, 20, 30], 5, True)
input = torch.randn(1, 40, requires_grad = False)
output = simple_network(input)
print(output)
Example output (might differ due to PyTorch version differences):
tensor([[-0.0208, 0.1605, -0.2080, 0.0140, 0.0723]], grad_fn=<AddmmBackward0>)
Exercise 2: SimpleCNN Class Implementation
Like the one above, we have to implement a class with 5 trainable layers. This time we will use Conv2d layers.
def __init__(
self, input_channels: int, hidden_channels: list, use_batchnormalization: bool, num_classes: int,
kernel_size: list, activation_function: torch.nn.Module = torch.nn.ReLU()
):
But in this model we will be dynamically generating the layers from the arguments.
Unlike the previoous one which had a fixed number of layers.
In this one we will have a variable number of layers. which can be chnage from the arguments.
Like the previous one, we will define the __init__ method and the forward() method.
import torch
import torch.nn as nn
class SimpleCNN(nn.Module):
def __init__(
self, input_channels: int, hidden_channels: list, use_batchnormalization: bool, num_classes: int,
kernel_size: list, activation_function: torch.nn.Module = torch.nn.ReLU()
):
super().__init__()
def forward(self, input_images: torch.Tensor):
pass
- The structure should look like this :
- input_channels
- hidden_channels[0]
- hidden_channels[1]
- hidden_channels[2]
- num_classes
- input_channels → hidden_channels[0]
- if use_batchnormalization is True then BatchNorm2d
- hidden_channels[0] → hidden_channels[1]
- if use_batchnormalization is True then BatchNorm2d
- hidden_channels[1] → hidden_channels[2]
- if use_batchnormalization is True then BatchNorm2d
- num_classes
🔴 BUT
Our model should have a BatchNorm2D layer after each Conv2d layer. If use_batchnormalization is set to True.
So the structure of layers should look like this :
You can see how the structure is more complicated than the one before.
to do this we will use a for loop to generate the layers.
self.conv_layers = nn.ModuleList() # makes use of modulelist to append layers to
in_channels = input_channels
for output, k_size in zip(hidden_channels, kernel_size):
# APPEND CONV2D LAYER
if use_batchnormalization:
# APPEND BATCHNORM2D LAYER
#APPEND ACTIVATION FUNCTION
in_channels = output # update in_channels
#ADD FINAL LAYER
We add the final layer after the loop ony because we should flatten before the final layer.
So in code it should look like this :
self.conv_layers = nn.ModuleList() # makes use of modulelist to append layers to
in_channels = input_channels
for output, k_size in zip(hidden_channels, kernel_size):
self.conv_layers.append(
nn.Conv2d(
in_channels,
output,
kernel_size=k_size,
padding=k_size // 2
)
)
if use_batchnormalization:
self.conv_layers.append(
nn.BatchNorm2d(output)
)
self.conv_layers.append(activation_function)
in_channels = output # update in_channels
self.output_layer = nn.Linear(hidden_channels[-1] * 70 * 100, num_classes)
Now the forward() method.
we will just loop through the layers and apply them to the input.
before the last one we will flatten the output. otherwise the output will be a 4D tensor of shape (Minibatch Size, n_output_neurons, 70, 100)
so we use torch.flatten() with start_dim=1 to flatten the output.
def forward(self, input_images: torch.Tensor):
x = input_images
for layer in self.conv_layers:
x = layer(x)
x = self.output_layer(x)
x = torch.flatten(x, start_dim=1)
return x
for checking th output we can use the following code. (Pulled from the pdf)
if __name__ == "__main__":
torch.random.manual_seed(1234)
simple_cnn = SimpleCNN(3, [10, 20, 30], True, 5, [3, 3, 3])
input = torch.randn(1, 3, 70, 100, requires_grad = False)
output = simple_cnn(input)
print(output)
Well that’s it for the SimpleCNN class.