forked from abhinuvpitale/Machine-Learning-Examples
-
Notifications
You must be signed in to change notification settings - Fork 2
/
LinearRegressionMSE.py
54 lines (42 loc) · 1.38 KB
/
LinearRegressionMSE.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
import numpy as np
class LinearRegression:
def __init__(self):
this.theta = np.empty(0)
this.bias = 0
def fit(self, X, y, alpha = 0.1, epochs = 100):
'''
This function is used to fit the data using MSE loss.
The function updates self.theta which will pe used to predict the values
in predict function.
Parameters:
----------
X - Features
y - Labels
alpha - Learning rate
epochs - Number of epochs
Returns: self
'''
# No of data points in dataset
n = len(y)
# Initializing the theta and bias
self.theta = np.zeros(X.shape[1])
self.bias = 0
for i in range(epochs):
# Predicted value = X matrix multiplied with theta
# Difference between the predicted and true value for training set
loss = X @ self.theta + self.bias - y
# Gradint descent : theta = theta - (learning_rate/n)*(partial derivative of cost function)
self.theta -= alpha*(1/n)*(np.sum([loss[j] * X[j] for j in range(n)]))
self.bias -= alpha*(1/n)*(np.sum(loss))
return self
def predict(self, X):
'''
Predicting values using the trained linear model.
Parameters
----------
X - 2-dimensional numpy array of shape (n_samples, n_features) which acts as testing data.
Returns
-------
y - 1-dimensional numpy array of shape (n_samples,) which contains the predicted values.
'''
return X @ self.theta + self.bias