forked from trekhleb/homemade-machine-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_regression.py
179 lines (128 loc) · 6.01 KB
/
linear_regression.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""Linear Regression Module"""
# Import dependencies.
import numpy as np
from ..utils.features import prepare_for_training
class LinearRegression:
"""Linear Regression Class"""
def __init__(self, data, labels, polynomial_degree=0, sinusoid_degree=0):
"""Linear regression constructor.
:param data: training set.
:param labels: training set outputs (correct values).
:param polynomial_degree: degree of additional polynomial features.
:param sinusoid_degree: multipliers for sinusoidal features.
"""
# Normalize features and add ones column.
(
data_processed,
features_mean,
features_deviation
) = prepare_for_training(data, polynomial_degree, sinusoid_degree)
self.data = data_processed
self.labels = labels
self.features_mean = features_mean
self.features_deviation = features_deviation
self.polynomial_degree = polynomial_degree
self.sinusoid_degree = sinusoid_degree
# Initialize model parameters.
num_features = self.data.shape[1]
self.theta = np.zeros((num_features, 1))
def train(self, alpha, lambda_param=0, num_iterations=500):
"""Trains linear regression.
:param alpha: learning rate (the size of the step for gradient descent)
:param lambda_param: regularization parameter
:param num_iterations: number of gradient descent iterations.
"""
# Run gradient descent.
cost_history = self.gradient_descent(alpha, lambda_param, num_iterations)
return self.theta, cost_history
def gradient_descent(self, alpha, lambda_param, num_iterations):
"""Gradient descent.
It calculates what steps (deltas) should be taken for each theta parameter in
order to minimize the cost function.
:param alpha: learning rate (the size of the step for gradient descent)
:param lambda_param: regularization parameter
:param num_iterations: number of gradient descent iterations.
"""
# Initialize J_history with zeros.
cost_history = []
for _ in range(num_iterations):
# Perform a single gradient step on the parameter vector theta.
self.gradient_step(alpha, lambda_param)
# Save the cost J in every iteration.
cost_history.append(self.cost_function(self.data, self.labels, lambda_param))
return cost_history
def gradient_step(self, alpha, lambda_param):
"""Gradient step.
Function performs one step of gradient descent for theta parameters.
:param alpha: learning rate (the size of the step for gradient descent)
:param lambda_param: regularization parameter
"""
# Calculate the number of training examples.
num_examples = self.data.shape[0]
# Predictions of hypothesis on all m examples.
predictions = LinearRegression.hypothesis(self.data, self.theta)
# The difference between predictions and actual values for all m examples.
delta = predictions - self.labels
# Calculate regularization parameter.
reg_param = 1 - alpha * lambda_param / num_examples
# Create theta shortcut.
theta = self.theta
# Vectorized version of gradient descent.
theta = theta * reg_param - alpha * (1 / num_examples) * (delta.T @ self.data).T
# We should NOT regularize the parameter theta_zero.
theta[1] = theta[1] - alpha * (1 / num_examples) * (self.data[:, 0].T @ delta).T
self.theta = theta
def get_cost(self, data, labels, lambda_param):
"""Get the cost value for specific data set.
:param data: the set of training or test data.
:param labels: training set outputs (correct values).
:param lambda_param: regularization parameter
"""
data_processed = prepare_for_training(
data,
self.polynomial_degree,
self.sinusoid_degree
)[0]
return self.cost_function(data_processed, labels, lambda_param)
def cost_function(self, data, labels, lambda_param):
"""Cost function.
It shows how accurate our model is based on current model parameters.
:param data: the set of training or test data.
:param labels: training set outputs (correct values).
:param lambda_param: regularization parameter
"""
# Calculate the number of training examples and features.
num_examples = data.shape[0]
# Get the difference between predictions and correct output values.
delta = LinearRegression.hypothesis(data, self.theta) - labels
# Calculate regularization parameter.
# Remember that we should not regularize the parameter theta_zero.
theta_cut = self.theta[1:, 0]
reg_param = lambda_param * (theta_cut.T @ theta_cut)
# Calculate current predictions cost.
cost = (1 / 2 * num_examples) * (delta.T @ delta + reg_param)
# Let's extract cost value from the one and only cost numpy matrix cell.
return cost[0][0]
def predict(self, data):
"""Predict the output for data_set input based on trained theta values
:param data: training set of features.
"""
# Normalize features and add ones column.
data_processed = prepare_for_training(
data,
self.polynomial_degree,
self.sinusoid_degree
)[0]
# Do predictions using model hypothesis.
predictions = LinearRegression.hypothesis(data_processed, self.theta)
return predictions
@staticmethod
def hypothesis(data, theta):
"""Hypothesis function.
It predicts the output values y based on the input values X and model parameters.
:param data: data set for what the predictions will be calculated.
:param theta: model params.
:return: predictions made by model based on provided theta.
"""
predictions = data @ theta
return predictions