-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_regression.py
More file actions
74 lines (60 loc) · 2.22 KB
/
linear_regression.py
File metadata and controls
74 lines (60 loc) · 2.22 KB
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
65
66
67
68
69
70
71
72
73
74
import csv
from utils import StandardScaler, train_test_split, add_bias, mse
import numpy as np
import math
import pickle
import os
data = []
with open('Real estate.csv') as f:
temp_data = csv.reader(f)
for row in temp_data:
data.append(row)
columns = data[0]
data = np.array(data[1:], dtype=np.float64)
X = data[:, 1:7]
y = data[:, 7]
X_train, y_train, X_test, y_test = train_test_split(X, y)
X_train, col_mean, col_std = StandardScaler(X_train)
X_train = add_bias(X_train)
class LinearRegression:
def __init__(self):
self.model = []
# Ordinary Least Squares Method
def Train(self, X_training, y_training):
xt_x_inv = np.linalg.inv(np.dot(X_training.T, X_training))
xt_y = np.dot(X_training.T, y_training)
self.model = np.dot(xt_x_inv, xt_y)
def predict(self, x_new):
assert len(self.model) > 0, "use the Train function first to obtain the parameters before predicting"
weight = self.model[:-1]
bias = self.model[-1]
return np.dot(x_new, weight) + bias
def save(self, filename):
if os.path.exists(filename):
change = input("A file with similar name already exists do you want to overwrite ?(Y/N) - ")
if change.lower() == 'y':
print("Saving the model")
with open(filename, 'wb') as f:
pickle.dump(self.model, f)
else:
return
else:
print("Saving the model")
with open(filename, 'wb') as f:
pickle.dump(self.model, f)
def load(self, filename):
assert os.path.exists(filename), "the file to be loaded doesn't exist"
with open(filename, 'rb') as f:
self.model = pickle.load(f)
regressor = LinearRegression()
file_name = "lr_estate.pickle"
if os.path.exists(file_name):
print("Trained model exists so, loading the model")
regressor.load(file_name)
else:
regressor.Train(X_train, y_train)
regressor.save(file_name)
X_test = StandardScaler(X_test, train=[col_mean, col_std])
y_predicted = regressor.predict(X_test)
print(np.mean(y_train))
print(math.sqrt(mse(y_predicted, y_test))) # Root Mean-Squared Error -> output in the same unit as our data