Learn practical skills, build real-world projects, and advance your career
Created 4 years ago
import torch
import numpy as np
import pandas as pd
import torch.nn as nn
# Defining Dummy Dataset and Parameters for a Mdel
X = torch.tensor([[1],[2],[3],[4],[5]], dtype = torch.float32)
y = torch.tensor([[2],[4],[6],[8],[10]], dtype = torch.float32)
# Extracting n_rows and n_cols for a simple ANN
n_rows, n_cols = X.shape
# Creating a Test Tensor to check the prediction before any Training
test = torch.tensor([5.0], dtype = torch.float32)
# 1st Method : By Using [General Class] for defining Linear Regression Model
# Linear_Regression Class containing functions like :
# 1- (layers initialization function)
# 2- (Forward function)
class Linear_Regression(nn.Module):
# __init__ Function of a Class
def __init__(self, input_size, output_size):
super(Linear_Regression, self).__init__()
# Defining the layers of the Simple ANN
self.layer1 = nn.Linear(input_size, output_size)
# Forward Function for a Layers defined in __init()__ Function
def forward(self, X):
return self.layer1(X)
input_size = n_cols
output_size = n_cols
model = Linear_Regression(input_size, output_size)
# Prediction a Test Tensor before any Training process
print(f'Prediction for f(5) is : {model.forward(test).item():.3f}')
Prediction for f(5) is : -4.113
# 2nd Method : By Using [PyTorch nn.Linear()] function to define Linear Regression Model
# input_size = n_cols
# output_size = n_cols
# model = nn.Linear(input_size, output_size)
# Defining Learning Rate for the Model
learning_rate = 0.02
# Loss Function
loss = nn.MSELoss()
# Optimizer Function
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)