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

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1rHJ9vLfYdAtzOuPBPrrmB24yxVH5mBbI
"""

"""
always follow the following steps in partcular order

1) design your model , the input size , output size
2) construct your loss and your optimizer
3) training loop :
    1) forward pass
    2) backward pass - calculate the gradients 
    3) update the weights

import torch
import torch.nn 
import numpy as np
from sklearn import datasets


# importing the data that we need

x_train,y_train=datasets.make_regression(n_samples=100,n_features=1,n_targets=1)

print(x_train.shape,y_train.shape)

#we know that torch needs to be worked on with float data type
# lets see the type of input data and change it

print(y_train.dtype)

#its already in float 
# but we need TORCH TYpe and not just np array

x=torch.from_numpy(x_train.astype(np.float32))

y=torch.from_numpy(y_train.astype(np.float32))
#now change the shape of the vector y to give 1000,1

y=y.view(y.shape[0],1)

# define the model
inpshape=x[0].shape
outshape=y[0].shape


print(inpshape,y[0].shape)

inpsize,inpshape=x.shape
outputshape=y.shape[1]
print(outputshape,inpsize,inpshape)


#model definition
model=torch.nn.Linear(inpshape,outputshape)

#loss and optimizer

loss=nn.MSELoss()
optimizer=torch.optim.SGD(model.parameters(),lr=0.1)


# training loop

for epoch in range(10000):
  #forward pass
  ypred=model(x)

  #backward
  lossval=loss(ypred,y)
  lossval.backward()
  #updating the weights
  optimizer.step()

  optimizer.zero_grad()

  if epoch%100==0:
    print("epoch  {}   loss   {} %".format(epoch,lossval*100))



#j truying to plot
predictions=model(x).detach()
import matplotlib.pyplot as plt
plt.plot(x,predictions,'b')
plt.plot(x,y,'ro')

