Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linear regression 2d #35

Merged
merged 4 commits into from
Oct 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions ML_Algorithms/Linear_Regression/linear_regression_2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import math
import numpy as np

class LinearRegression2D():

def __init__(self,points,per_graph_epochs):
self.points=points
self.per_graph_epochs = per_graph_epochs

def dot_product(self,x,w,b):
z = 0.0
z = z + float(x[0])*float(w[0])
z = z + float(x[1])*float(w[1])
z = z + float(b)
return float(z)

def loss_function(self,w,b):
mse = 0.0
for i in range(len(self.points)):
z = self.dot_product(self.points[i],w,b)
mse = mse + math.pow((self.points[i][0]-z),2)
mse = (mse / float(len(self.points)))
return mse

def grad_descent(self,epochs,w,b):
for i in range(epochs):
del_w = [0.0 , 0.0]
del_b = 0.0
m = len(self.points)
for j in range(m):
h = self.dot_product(self.points[j],w,b)
del_w[0] = del_w[0] + (float(self.points[j][0])*(float(h) - float(self.points[j][2])))
del_w[1] = del_w[1] + (float(self.points[j][1])*(float(h) - float(self.points[j][2])))
del_b = del_b + (float(h) - float(self.points[j][2]))
del_w[0] = del_w[0] / float(m)
del_w[1] = del_w[1] / float(m)
del_b = del_b / float(m)
print(del_w)
print(del_b)
w[0] = w[0] - 0.005*float(del_w[0])
w[1] = w[1] - 0.005*float(del_w[1])
b = b - 0.05*float(del_b)
return w, b

def visualizer(self):
w = [np.random.randn() for i in range(len(self.points[0])-1)]
b = np.random.randn()
# print(w,b)
arr = [[0 for i in range(len(w)+1)] for j in range(7)]
for i in range(len(w)):
arr[0][i] = w[i]
arr[0][2] = b
for i in range(5):
w,b = self.grad_descent(int(self.per_graph_epochs),w,float(b))
arr[i+1][0] = w[0]
arr[i+1][1] = w[1]
arr[i+1][2] = b
w,b = self.grad_descent(2000,w,b)
arr[6][0] = w[0]
arr[6][1] = w[1]
arr[6][2] = b
return arr