forked from awasthiabhijeet/cs725-2020-assign1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLR.py
275 lines (224 loc) · 7.89 KB
/
LR.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
np.random.seed(42)
class Scaler():
# hint: https://machinelearningmastery.com/standardscaler-and-minmaxscaler-transforms-in-python/
def __init__(self):
raise NotImplementedError
def __call__(self,features, is_train=False):
raise NotImplementedError
def get_features(csv_path,is_train=False,scaler=None):
'''
Description:
read input feature columns from csv file
manipulate feature columns, create basis functions, do feature scaling etc.
return a feature matrix (numpy array) of shape m x n
m is number of examples, n is number of features
return value: numpy array
'''
'''
Arguments:
csv_path: path to csv file
is_train: True if using training data (optional)
scaler: a class object for doing feature scaling (optional)
'''
'''
help:
useful links:
* https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
* https://www.geeksforgeeks.org/python-read-csv-using-pandas-read_csv/
'''
raise NotImplementedError
def get_targets(csv_path):
'''
Description:
read target outputs from the csv file
return a numpy array of shape m x 1
m is number of examples
'''
raise NotImplementedError
def analytical_solution(feature_matrix, targets, C=0.0):
'''
Description:
implement analytical solution to obtain weights
as described in lecture 5d
return value: numpy array
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
targets: numpy array of shape m x 1
'''
raise NotImplementedError
def get_predictions(feature_matrix, weights):
'''
description
return predictions given feature matrix and weights
return value: numpy array
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
weights: numpy array of shape n x 1
'''
raise NotImplementedError
def mse_loss(feature_matrix, weights, targets):
'''
Description:
Implement mean squared error loss function
return value: float (scalar)
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
weights: numpy array of shape n x 1
targets: numpy array of shape m x 1
'''
raise NotImplementedError
def l2_regularizer(weights):
'''
Description:
Implement l2 regularizer
return value: float (scalar)
'''
'''
Arguments
weights: numpy array of shape n x 1
'''
raise NotImplementedError
def loss_fn(feature_matrix, weights, targets, C=0.0):
'''
Description:
compute the loss function: mse_loss + C * l2_regularizer
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
weights: numpy array of shape n x 1
targets: numpy array of shape m x 1
C: weight for regularization penalty
return value: float (scalar)
'''
raise NotImplementedError
def compute_gradients(feature_matrix, weights, targets, C=0.0):
'''
Description:
compute gradient of weights w.r.t. the loss_fn function implemented above
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
weights: numpy array of shape n x 1
targets: numpy array of shape m x 1
C: weight for regularization penalty
return value: numpy array
'''
raise NotImplementedError
def sample_random_batch(feature_matrix, targets, batch_size):
'''
Description
Batching -- Randomly sample batch_size number of elements from feature_matrix and targets
return a tuple: (sampled_feature_matrix, sampled_targets)
sampled_feature_matrix: numpy array of shape batch_size x n
sampled_targets: numpy array of shape batch_size x 1
'''
'''
Arguments:
feature_matrix: numpy array of shape m x n
targets: numpy array of shape m x 1
batch_size: int
'''
raise NotImplementedError
def initialize_weights(n):
'''
Description:
initialize weights to some initial values
return value: numpy array of shape n x 1
'''
'''
Arguments
n: int
'''
raise NotImplementedError
def update_weights(weights, gradients, lr):
'''
Description:
update weights using gradient descent
retuen value: numpy matrix of shape nx1
'''
'''
Arguments:
# weights: numpy matrix of shape nx1
# gradients: numpy matrix of shape nx1
# lr: learning rate
'''
raise NotImplementedError
def early_stopping(arg_1=None, arg_2=None, arg_3=None, arg_n=None):
# allowed to modify argument list as per your need
# return True or False
raise NotImplementedError
def do_gradient_descent(train_feature_matrix,
train_targets,
dev_feature_matrix,
dev_targets,
lr=1.0,
C=0.0,
batch_size=32,
max_steps=10000,
eval_steps=5):
'''
feel free to significantly modify the body of this function as per your needs.
** However **, you ought to make use of compute_gradients and update_weights function defined above
return your best possible estimate of LR weights
a sample code is as follows --
'''
weights = initialize_weights(n)
dev_loss = mse_loss(dev_feature_matrix, weights, dev_targets)
train_loss = mse_loss(train_feature_matrix, weights, train_targets)
print("step {} \t dev loss: {} \t train loss: {}".format(0,dev_loss,train_loss))
for step in range(1,max_steps+1):
#sample a batch of features and gradients
features,targets = sample_random_batch(train_feature_matrix,train_targets,batch_size)
#compute gradients
gradients = compute_gradients(features, weights, targets, C)
#update weights
weights = update_weights(weights, gradients, lr)
if step%eval_steps == 0:
dev_loss = mse_loss(dev_feature_matrix, weights, dev_targets)
train_loss = mse_loss(train_feature_matrix, weights, train_targets)
print("step {} \t dev loss: {} \t train loss: {}".format(step,dev_loss,train_loss))
'''
implement early stopping etc. to improve performance.
'''
return weights
def do_evaluation(feature_matrix, targets, weights):
# your predictions will be evaluated based on mean squared error
predictions = get_predictions(feature_matrix, weights)
loss = mse_loss(feature_matrix, weights, targets)
return loss
if __name__ == '__main__':
scaler = Scaler() #use of scaler is optional
train_features, train_targets = get_features('data/train.csv',True,scaler), get_targets('data/train.csv')
dev_features, dev_targets = get_features('data/dev.csv',False,scaler), get_targets('data/dev.csv')
a_solution = analytical_solution(train_features, train_targets, C=1e-8)
print('evaluating analytical_solution...')
dev_loss=do_evaluation(dev_features, dev_targets, a_solution)
train_loss=do_evaluation(train_features, train_targets, a_solution)
print('analytical_solution \t train loss: {}, dev_loss: {} '.format(train_loss, dev_loss))
print('training LR using gradient descent...')
gradient_descent_soln = do_gradient_descent(train_features,
train_targets,
dev_features,
dev_targets,
lr=1.0,
C=0.0,
batch_size=32,
max_steps=2000000,
eval_steps=5)
print('evaluating iterative_solution...')
dev_loss=do_evaluation(dev_features, dev_targets, gradient_descent_soln)
train_loss=do_evaluation(train_features, train_targets, gradient_descent_soln)
print('gradient_descent_soln \t train loss: {}, dev_loss: {} '.format(train_loss, dev_loss))