# -*- coding: utf-8 -*-
"""linear.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1shB6vbT83PlKWLx9jUu9cP4W_SWy-cKn

An example of linear model using PyTorch in Google Colab
"""

import torch
from torch.autograd import Variable
class linearRegression(torch.nn.Module):
    def __init__(self, inputSize, outputSize):
        super(linearRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        out = self.linear(x)
        return out

import random
x_values = [i + (random.random() - random.random()) for i in range(11)]
print (x_values)

y_values = [(6 * i + (random.random() - random.random()) - 35) for i in range(11)]
print (y_values)

import matplotlib.pyplot as plt
plt.plot(x_values, y_values, 'o')
plt.show()

import numpy as np
x_train = np.array(x_values, dtype=np.float32)
x_train = x_train.reshape(-1, 1)
y_train = np.array(y_values, dtype=np.float32)
y_train = y_train.reshape(-1, 1)

inputDim = 1        # takes variable 'x' 
outputDim = 1       # takes variable 'y'
learningRate = 0.01 
epochs = 1000
model = linearRegression(inputDim, outputDim)
model.cuda()

criterion = torch.nn.MSELoss() 
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
for epoch in range(epochs):
    inputs = Variable(torch.from_numpy(x_train).cuda())
    labels = Variable(torch.from_numpy(y_train).cuda())
    optimizer.zero_grad()
    outputs = model(inputs)
    loss = criterion(outputs, labels)
    print(loss)
    loss.backward()
    optimizer.step()
    print('epoch {}, loss {}'.format(epoch, loss.item()))

with torch.no_grad(): # we don't need gradients in the testing phase
    predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy()
    print(predicted)
plt.clf()
plt.plot(x_train, y_train, 'go', label='Input data')
plt.plot(x_train, predicted, '--', label='Predictions')
plt.legend(loc='best')
plt.show()

print (model)
print(model.state_dict())
# -*- coding: utf-8 -*-
"""linear.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1shB6vbT83PlKWLx9jUu9cP4W_SWy-cKn

An example of linear model using PyTorch in Google Colab
"""

import torch
from torch.autograd import Variable
class linearRegression(torch.nn.Module):
    def __init__(self, inputSize, outputSize):
        super(linearRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        out = self.linear(x)
        return out

import random
x_values = [i + (random.random() - random.random()) for i in range(11)]
print (x_values)

y_values = [(6 * i + (random.random() - random.random()) - 35) for i in range(11)]
print (y_values)

import matplotlib.pyplot as plt
plt.plot(x_values, y_values, 'o')
plt.show()

import numpy as np
x_train = np.array(x_values, dtype=np.float32)
x_train = x_train.reshape(-1, 1)
y_train = np.array(y_values, dtype=np.float32)
y_train = y_train.reshape(-1, 1)

inputDim = 1        # takes variable 'x' 
outputDim = 1       # takes variable 'y'
learningRate = 0.01 
epochs = 1000
model = linearRegression(inputDim, outputDim)
model.cuda()

criterion = torch.nn.MSELoss() 
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
for epoch in range(epochs):
    inputs = Variable(torch.from_numpy(x_train).cuda())
    labels = Variable(torch.from_numpy(y_train).cuda())
    optimizer.zero_grad()
    outputs = model(inputs)
    loss = criterion(outputs, labels)
    print(loss)
    loss.backward()
    optimizer.step()
    print('epoch {}, loss {}'.format(epoch, loss.item()))

with torch.no_grad(): # we don't need gradients in the testing phase
    predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy()
    print(predicted)
plt.clf()
plt.plot(x_train, y_train, 'go', label='Input data')
plt.plot(x_train, predicted, '--', label='Predictions')
plt.legend(loc='best')
plt.show()

print (model)
print(model.state_dict())
# -*- coding: utf-8 -*- linear.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1shB6vbT83PlKWLx9jUu9cP4W_SWy-cKn  An example of linear model using PyTorch in Google Colab # takes variable 'x' # takes variable 'y' # we don't need gradients in the testing phase