IWriteAsILearn
Published in

IWriteAsILearn

Regression analysis with PyTorch

image courtesy

Imports

import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler

Data

The dataset I am going to use is celsius to fahrenheit data which can be found here: link

X_train = train_data.iloc[:,0].values
y_train = train_data.iloc[:,-1].values
sc = MinMaxScaler()
sct = MinMaxScaler()
X_train=sc.fit_transform(X_train.reshape(-1,1))
y_train =sct.fit_transform(y_train.reshape(-1,1))
X_train = torch.from_numpy(X_train.astype(np.float32)).view(-1,1)
y_train = torch.from_numpy(y_train.astype(np.float32)).view(-1,1)

Model building

input_size = 1
output_size = 1
class LinearRegressionModel(torch.nn.Module):    def __init__(self):
super(LinearRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1) # One in and one out
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = nn.Linear(input_size , output_size)
learning_rate = 0.0001
l = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr =learning_rate )

Training

num_epochs = 100for epoch in range(num_epochs):
#forward feed
y_pred = model(X_train.requires_grad_())
#calculate the loss
loss= l(y_pred, y_train)
#backward propagation: calculate gradients
loss.backward()
#update the weights
optimizer.step()
#clear out the gradients from the last step loss.backward()
optimizer.zero_grad()

print('epoch {}, loss {}'.format(epoch, loss.item()))

Evaluation

predicted = model(X_train).detach().numpy()
plt.scatter(X_train.detach().numpy()[:100] , y_train.detach().numpy()[:100])
plt.plot(X_train.detach().numpy()[:100] , predicted[:100] , "red")
plt.xlabel("Celcius")
plt.ylabel("Farenhite")
plt.show()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dipanwita Mallick

I am working as a Senior Data Scientist at Hewlett Packard Enterprise. I love exploring new ideas and new places !! :)