-
Notifications
You must be signed in to change notification settings - Fork 4
/
LinearRegression.py
64 lines (51 loc) · 1.4 KB
/
LinearRegression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import matplotlib.pyplot as plt
import numpy as np
class lr():
"""
Linear regression using least squares method
"""
def fit(self, x, y):
"""
Fit model
Parameters
----------
X : array_like, shape (n_samples, n_features)
Training data
y : array_like, shape (n_samples, )
Target value
Return
----------
self : returns an instance of self
"""
x2 = np.power(x, 2)
xy = x * y.reshape((-1,1))
sum_x = np.sum(x)
sum_y = np.sum(y)
sum_x2 = np.sum(x2)
sum_x_2 = np.power(sum_x, 2)
sum_xy = np.sum(xy)
self.n_samples = np.count_nonzero(x)
self.slope_ = ((self.n_samples * sum_xy) - (sum_x * sum_y)) / ((self.n_samples * sum_x2) - sum_x_2)
self.intercept_ = (sum_y - (self.slope_ * sum_x)) / self.n_samples
return self
def predict(self, x):
"""
Predict using the linear model
Parameters
----------
X : array_like or spare matrix, shape (n_samples, n_features)
Sample
Returns
----------
C : array, shape (n_samples, )
Returns predicted value
"""
self.y_pred = (self.slope_ * x) + self.intercept_
return self.y_pred
def visual(self, x, y, y_pred):
plt.plot(x,y,'o',color='blue')
plt.plot(x, y_pred, color='red', linewidth=2)
plt.xlabel('X - feature')
plt.ylabel('Y - label')
plt.title('Regression Graph')
plt.show()