Version of Python¶

In [1]:
!python -V
Python 3.12.6

Import Required Packages¶

In [2]:
# Suppress warnings
import warnings
for warn in [UserWarning, FutureWarning]: warnings.filterwarnings("ignore", category = warn)

import os
import numpy as np
import torch
import torch.nn as nn
import pandas as pd
import jupyterlab as jlab

from dataclasses import dataclass

Versions of Required Libraries¶

In [3]:
packages = [
    "Torch", "NumPy", "Pandas", "JupyterLab",
]

package_objects = [
    torch, np, pd, jlab
]

versions = list(map(lambda obj: obj.__version__, package_objects))

pkgs = {"Package": packages, "Version": versions}
df_pkgs = pd.DataFrame(data = pkgs)
df_pkgs.index.name = "#"
df_pkgs.index += 1

display(df_pkgs)

path_to_reqs = "."
reqs_name = "requirements.txt"

def get_packages_and_versions():
    """Generate strings with libraries and their versions in the format: package==version"""
    
    for package, version in zip(packages, versions):
        yield f"{package.lower()}=={version}\n"

with open(os.path.join(path_to_reqs, reqs_name), "w", encoding = "utf-8") as f:
    f.writelines(get_packages_and_versions())
Package Version
#
1 Torch 2.2.2
2 NumPy 1.26.4
3 Pandas 2.2.3
4 JupyterLab 4.2.5

Example of a Single Layer Neural Network¶

In [4]:
@dataclass
class SLNN(nn.Module):
    input_size: int # Input layer
    hidden_size: int # Hidden layer
    output_size: int # Output layer

    # Called immediately after __init__ when using dataclass
    def __post_init__(self):
        super(SLNN, self).__init__()

        # Define the hidden layer
        self.hidden = nn.Linear(self.input_size, self.hidden_size)
        # Define the output layer
        self.output = nn.Linear(self.hidden_size, self.output_size)

        # Determine the activation function for the hidden layer
        self.g = nn.ReLU()

    # Direct data flow through the neural network
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # Pass through hidden layer with activation function
        x = self.g(self.hidden(x))
        # Pass through the output layer
        x = self.output(x)

        return x

# Check for GPU availability
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Create a model instance
model = SLNN(input_size = 10, hidden_size = 20, output_size = 5).to(device)

# Create a random tensor
input = torch.randn(2, model.input_size).to(device)

# Run through the model
output = model(input)

# Output of the resulting tensor after passing through the model
print("Resulting tensor after passing through the model:")
print(output)

# Output the size of the resulting tensor
print("Size of the resulting tensor:")
print(output.size())
Resulting tensor after passing through the model:
tensor([[ 0.1114, -0.6370, -0.2935, -0.0662, -0.2534],
        [-0.2545, -0.7270, -0.0806, -0.0072, -0.2839]],
       grad_fn=<AddmmBackward0>)
Size of the resulting tensor:
torch.Size([2, 5])