import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
# Training Data
train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
7.042,10.791,5.313,7.997,5.654,9.27,3.1],dtype='float32')
train_Y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
2.827,3.465,1.65,2.904,2.42,2.94,1.3],dtype='float32')
n_samples = train_X.shape[0]
print(train_X.shape)
train_X = train_X.reshape(-1,1) # Note the Size of this numpy array after reshape
train_Y = train_Y.reshape(-1,1)
print(train_X.shape)
Create Model
1) Derive from nn.Module
2) write the forward() function
class linearRegModel(nn.Module):
def __init__(self,input_dim,output_dim):
super(linearRegModel,self).__init__()
#Applies a linear transformation to the data: :math:`y = Ax + b`
self.linear = nn.Linear(input_dim,output_dim)
def forward(self,x):
out = self.linear(x)
return out
input_dim = 1 #In our simple Example we are trying to find linear fit for set of points (x,y)
output_dim = 1
#Create Model
model = linearRegModel(1,1)
#Create Loss Function. This should be a scalar to use backward from pyTorch
criterion = nn.MSELoss()
#Create Optimizer
learning_rate=0.014
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)
epochs = 1000
displayStep = 50
for epoch in range(epochs):
#Create Torch Variables from numpy Array
inp = Variable(torch.from_numpy(train_X))
labels = Variable(torch.from_numpy(train_Y))
#Clear Gradients in the Optimizer every epoch
optimizer.zero_grad()
outputs = model(inp) # This actually calls operator() and it has some bells and whistles before it calls forward
loss = criterion(outputs,labels)
#Get the Gradients w.r.t Params
loss.backward()
#Update the Parameters
optimizer.step()
if(epoch%displayStep==0):
print('epoch {}, loss {}'.format(epoch,loss.data[0])) # Note How the Scalar Value loss is being accessed
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(train_X,train_Y,'ro',label="Original Data")
#Note: How Data needs to be converted to Variable before calling the model
Pred_Y = model(Variable(torch.from_numpy(train_X)))
#Note: How data is extracted from a Torch Variable
plt.plot(train_X,Pred_Y.data.numpy(),label="Fitted Line")