Skip to content

Commit 806936a

Browse files
authored
Merge pull request #119 from jeffin07/master
Multivariable Linear Regression
2 parents 1e998c7 + 18a878f commit 806936a

File tree

2 files changed

+1065
-0
lines changed

2 files changed

+1065
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import numpy as np
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
5+
class LinearRegression:
6+
def fit(self, x, y, learning_rate):
7+
self.n_weights = np.zeros(x.shape[1])
8+
self.learning_rate = learning_rate
9+
self.loss_=[]
10+
print("Initial cost {} ".format(model.cost_function(x, y, self.n_weights)))
11+
model.gradient(x, y, self.n_weights, 10000)
12+
print("Final cost {} ".format(model.cost_function(x, y, self.n_weights)))
13+
return self.n_weights
14+
15+
16+
def cost_function(self, x, y, n_weights):
17+
n = len(y)
18+
cost = np.sum((x.dot(self.n_weights.T) - y) ** 2) / (2 * n)
19+
return cost
20+
21+
22+
23+
def gradient(self, x, y, n_weights, epochs):
24+
m = len(y)
25+
for i in range(epochs):
26+
h = x.dot(n_weights.T)
27+
loss = h - y
28+
change=(x.T.dot(loss) / m) * self.learning_rate
29+
self.n_weights -= change
30+
self.loss_.append(model.cost_function(x, y, self.n_weights))
31+
if i % 10 == 0:
32+
print("Loss of {}th epoch is {} ".format(i , model.cost_function(x, y, self.n_weights)))
33+
return self.n_weights
34+
35+
def predict(self, x):
36+
x=np.insert(x, 0 ,1)
37+
print(x.T.dot(self.n_weights))
38+
39+
40+
41+
def plot(self):
42+
plt.plot(self.loss_)
43+
plt.xlabel("Epochs")
44+
plt.ylabel("Loss")
45+
plt.show()
46+
47+
48+
49+
if __name__ == "__main__":
50+
#Importing data and some preprocessing
51+
data = pd.read_csv('student.csv')
52+
data["one"] = [1 for i in data["Math"]]
53+
math = data["Math"]
54+
write = data["Writing"]
55+
read = data["Reading"]
56+
one = data["one"]
57+
x = np.array([one,math,read]).T
58+
y = np.array(write)
59+
learning_rate = 0.0001
60+
model = LinearRegression()
61+
model.fit(x, y, learning_rate)
62+
print("Plotting loss")
63+
model.plot()
64+
model.predict(np.array([45,48]))

0 commit comments

Comments
 (0)