Code To Implement Linear Regression Algorithm in Python from scratch Using Numpy only.

Following is the code to implement Linear Regression Algorithm in Python from Scratch using Numpy only.

 

import numpy as np
import pandas as pd
def Loss_Function(target,Y_pred):
return np.mean(pow((Y_pred-target),2))
def pred(X_test):
return np.dot(X_test,w)+b
dataset = pd.read_csv('E:/tutorials/linreg_data.csv')

#print(dataset)
X_train = dataset.iloc[:,:-1].values
Y_train = dataset.iloc[:,1].values
print(X_train)
print(np.shape(Y_train))

Y_train = Y_train.reshape(-1,1)
print(np.shape(Y_train))

# initializing weights and bais
w=.5
b=.5
for i in range(1000000):
Y_pred = np.dot(X_train,w)+b
loss = Loss_Function(Y_train,Y_pred)
if(i%100==0):
print("iteration",i,"loss---------------->>>>>", loss)

grad_weight = np.dot((Y_pred-Y_train).T,X_train)/X_train.shape[0]
grad_bais = np.mean(Y_pred-Y_train)

w = w - .0001*grad_weight
b = b - .0001*grad_bais

Y_out = pred(1)
print(Y_out)


To understand Basic concepts of Linear Regression Algorithm visit here.

You can Download the code here.

Leave a Reply

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert
%d bloggers like this: