-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGE-461-Project3-MuhammadAbdullahMulkana-21801075.py
241 lines (187 loc) · 7.26 KB
/
GE-461-Project3-MuhammadAbdullahMulkana-21801075.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
# -*- coding: utf-8 -*-
"""GE3.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1VQT0IxBtF1Pk-GJQOHIcWjTPytKfZ4Jo
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
train = pd.read_csv("train1.txt", delimiter = '\t',header=None, names=["data", "target"])
test = pd.read_csv("test1.txt", delimiter = '\t',header=None, names=["data", "target"])
x_train = train['data'].to_numpy()
y_train = train['target'].to_numpy()
x_test = test['data'].to_numpy()
y_test = test['target'].to_numpy()
plt.plot(x_train, y_train, 'o' , label = 'train')
plt.plot(x_test, y_test, 'o', label = 'test')
plt.legend()
plt.title('Training and Testing data points')
plt.show()
y_train = (y_train-y_train.min())/(y_train.max()-y_train.min())
y_test = (y_test-y_test.min())/(y_test.max()-y_test.min())
class ANN:
def sigmoid(self,x):
y = np.exp(x)/(1+np.exp(x))
return y
def init_wandb(self, init_val, model = None, input_units = None, output_units = None):
if model == None:
w = np.random.uniform(-init_val, init_val)
b = np.random.uniform(-init_val, init_val)
elif model == 'two':
w = np.random.uniform(-init_val, init_val, [input_units,output_units])
b = np.random.uniform(-init_val, init_val, [1,output_units])
return w, b
#[1]
def train(self, hidden_units, data_train, target_train, data_test, target_test, epochs, lr, init_sigma, epsilon = 5e-4):
self.wh, self.bh = self.init_wandb(init_sigma, 'two',1,hidden_units)
self.wy, self.by = self.init_wandb(init_sigma, 'two', hidden_units,1)
self.avg_mse = []
self.test_mse = []
flag = False
for e in range(epochs):
if flag == False:
rand_ind = np.random.permutation(len(data_train))
avg_mse = 0
for i in range(len(data_train)):
sample = data_train[rand_ind[i]]
label = target_train[rand_ind[i]]
h_hat = self.sigmoid(sample*self.wh.T+self.bh.T)
y_hat = (np.matmul(self.wy.T,h_hat)+self.by)
mse = ((label-y_hat)**2)/2
avg_mse += mse[0]
error = label-y_hat
upd_wy = (error*h_hat)
upd_by = error
error_h = (error * self.wy)
der_h = np.multiply(h_hat,(1-h_hat))
delta_h = np.multiply(error_h,der_h)
upd_wh = (delta_h.T*sample)
upd_bh = sum(delta_h)
self.wy += lr*upd_wy
self.by += lr*upd_by.T
self.wh += lr*upd_wh
self.bh += lr*upd_bh
test_loss, test_se = self.eval(data_test, target_test)
train_loss, train_se = self.eval(data_train, target_train)
self.train_se = train_se
self.test_se = test_se
self.test_mse.append(test_loss)
self.avg_mse.append(train_loss)
diff = abs(self.avg_mse[e-1]-self.avg_mse[e])
if e > 50 and diff < epsilon:
flag = True
if e == (epochs-1):
flag = True
def eval(self, data, target):
data_1 = np.expand_dims(data,axis = 1)
target_1 = np.expand_dims(target,axis = 1)
h_hat = self.sigmoid(self.wh.T*data_1.T+np.repeat(self.bh.T,data_1.shape[0], axis = 1))
y_hat = np.matmul(h_hat.T, self.wy)+self.by
se = (target_1-y_hat)**2
loss = sum(se)/2
return loss, se
def train_regressor(self, data_train, target_train, data_test, target_test, epochs, lr, init_sigma, epsilon):
self.w, self.b = self.init_wandb(init_sigma)
self.avg_mse = []
self.test_mse = []
flag = False
for e in range(epochs):
if flag == False:
rand_ind = np.random.permutation(len(data_train))
avg_mse = 0
for i in range(len(data_train)):
sample = data_train[rand_ind[i]]
label = target_train[rand_ind[i]]
y_hat = (self.w*sample+self.b)
mse = ((label-y_hat)**2)/2
avg_mse += mse
error = label-y_hat
upd_w = (error*sample)
upd_b = error
self.w += lr*upd_w
self.b += lr*upd_b
test_loss, test_se = self.eval_regressor(data_test, target_test)
train_loss, train_se = self.eval_regressor(data_train, target_train)
self.train_se = train_se
self.test_se = test_se
self.avg_mse.append(train_loss)
self.test_mse.append(test_loss)
diff = abs(self.avg_mse[e-1]-self.avg_mse[e])
if e > 50 and diff < epsilon:
flag = True
if e == (epochs-1):
flag = True
def eval_regressor(self,data, label):
pred_y = self.w*data+self.b
se = (label-pred_y)**2
loss = sum(se)/2
return loss, se
"""#Single ANN"""
model = ANN()
model.train_regressor(x_train, y_train, x_test, y_test, 5000, 0.00005,0.05, 5e-12)
plt.figure(figsize = (15,8))
plt.plot(model.avg_mse, label = 'Train MSE')
plt.plot(model.test_mse, label = 'Test MSE')
plt.legend()
plt.show()
x = np.arange(-10, 8)
y_r = model.w*x_train+model.b
plt.plot(x_train, y_r, label = 'recons')
plt.plot(x_train, y_train, 'o' , label = 'train')
plt.show()
sum((y_r-y_train)**2)/60
"""#Two Layer ANN"""
model2 = ANN()
model2.train(5, x_train, y_train, x_test, y_test, 4000, 0.03,1, 2e-6)
plt.plot(model2.avg_mse, label = 'Train')
plt.plot(model2.test_mse, label = 'Test')
plt.legend()
plt.show()
x_t = np.expand_dims(np.linspace(x_train.min(),x_train.max(), 60),axis = 1)
h_hat = model2.sigmoid(model2.wh*x_t+model2.bh)
y_r2 = np.matmul(h_hat,model2.wy)+model2.by
plt.plot(x_t, y_r2.flatten(), label = 'model output')
plt.plot(x_train, y_train, 'o' , label = 'train data')
plt.legend()
plt.title('Train data and fitted line.')
plt.show()
x_te = np.expand_dims(np.linspace(x_train.min(),x_train.max(), len(x_test)),axis = 1)
h_hat = model2.sigmoid(model2.wh*x_te+model2.bh)
y_r2 = np.matmul(h_hat,model2.wy)+model2.by
plt.plot(x_te, y_r2.flatten(), label = 'model output')
plt.plot(x_test, y_test, 'o' , label = 'test data')
plt.title('Test data and fitted line.')
plt.legend()
plt.show()
print('Averaged Training loss: ' + str(model2.train_se.mean()))
print('Averaged Test loss: ' + str(model2.test_se.mean()))
"""#Part 3"""
model = ANN()
model.train_regressor(x_train, y_train, x_test, y_test, 5000, 0.00005,0.05, 5e-12)
y_r = model.w*x_t+model.b
plt.plot(x_t, y_r, label = 'model output')
plt.plot(x_train, y_train, 'o' , label = 'train data')
plt.legend()
plt.title('Model with single linear regressor')
plt.show()
print('Averaged Training loss: ' + str(model.train_se.mean()))
print('Averaged Test loss: ' + str(model.test_se.mean()))
print('STD Training loss: ' + str(model.train_se.std()))
print('STD Test loss: ' + str(model.test_se.std()))
hidden_units_arr = [2, 4, 8, 16, 32]
for hu in hidden_units_arr:
model2 = ANN()
model2.train(hu, x_train, y_train, x_test, y_test, 4000, 0.03,1, 2e-6)
h_hat = model2.sigmoid(model2.wh*x_t+model2.bh)
y_r2 = np.matmul(h_hat,model2.wy)+model2.by
plt.plot(x_t, y_r2.flatten(), label = 'model output')
plt.plot(x_train, y_train, 'o' , label = 'train data')
plt.legend()
plt.title('Model with ' + str(hu) + ' hidden units')
plt.show()
print(len(model2.test_mse))
print('Averaged Training loss: ' + str(model2.train_se.mean()))
print('Averaged Test loss: ' + str(model2.test_se.mean()))
print('STD Training loss: ' + str(model2.train_se.std()))
print('STD Test loss: ' + str(model2.test_se.std()))