-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
333 lines (272 loc) · 10.8 KB
/
main.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import matplotlib.pyplot as plt
import numpy as np
import argparse
import pickle
import os
parser = argparse.ArgumentParser()
parser.add_argument("--task", type=str, default="linear", help="which kind of data to process: [linear, xor]")
parser.add_argument("--lr", type=float, default=0.01, help="learning rate")
parser.add_argument("--hidden-size", type=tuple, default=(512, 32),
help="two hidden layer neuron numbers (layer1,layer2)")
parser.add_argument("--load", type=bool, default=True, help="if testing weight is loading from file")
parser.add_argument("--model-path",type=str,default="./checkpoints/linear_0.01_(512,32).pkl",help="pretrained model path")
args = parser.parse_args()
def generate_linear(n=100):
pts = np.random.uniform(0, 1, (n, 2))
inputs = []
labels = []
for pt in pts:
inputs.append([pt[0], pt[1]])
distance = (pt[0] - pt[1]) / 1.414
if pt[0] > pt[1]:
labels.append(0)
else:
labels.append(1)
return np.array(inputs), np.array(labels).reshape(n, 1)
def generate_XOR_easy():
inputs = []
labels = []
for i in range(11):
inputs.append([0.1 * i, 0.1 * i])
labels.append(0)
if 0.1 * i == 0.5:
continue
inputs.append([0.1 * i, 1 - 0.1 * i])
labels.append(1)
return np.array(inputs), np.array(labels).reshape(21, 1)
def sigmoid(x):
# Sigmoid function.
return 1 / (1 + np.exp(-x))
def der_sigmoid(y):
# First derivative of Sigmoid function.
return y * (1 - y)
class Model:
def __init__(self, hidden_size, epochs, lr):
"""
Feedforward network with 2 hidden layers
:parma hidden_size: two hidden layers neurons (layer1,layer2)
: param epochs: num of training epochs
"""
self.epochs = epochs
# Model parameters initialization
input_size = 2
output_size = 1
self.lr = lr
self.initial_lr = lr
self.momentum = 0.9
(layer1, layer2) = hidden_size
self.layer1 = layer1
self.layer2 = layer2
self.w1 = np.random.randn(input_size, layer1)
self.w2 = np.random.randn(layer1, layer2)
self.w3 = np.random.randn(layer2, output_size)
self.b1 = np.zeros((1, layer1))
self.b2 = np.zeros((1, layer2))
self.b3 = np.zeros((1, output_size))
self.v_w1 = np.zeros((input_size, layer1))
self.v_w2 = np.zeros((layer1, layer2))
self.v_w3 = np.zeros((layer2, output_size))
self.v_b1 = np.zeros((1, layer1))
self.v_b2 = np.zeros((1, layer2))
self.v_b3 = np.zeros((1, output_size))
def plot_result(self, data, gt_y, pred_y):
"""
Data visualization with ground truth and predicted data comparison. There are two plots for them and each of them use different colors to differentiate the data with different labels.
:param data: the input data
:param gt_y: ground truth to the data
:param pred_y: predicted results to the data
"""
task = args.task
assert data.shape[0] == gt_y.shape[0]
assert data.shape[0] == pred_y.shape[0]
plt.figure()
plt.subplot(1, 2, 1)
plt.title('Ground Truth', fontsize=18)
for idx in range(data.shape[0]):
if gt_y[idx] == 0:
plt.plot(data[idx][0], data[idx][1], 'ro')
else:
plt.plot(data[idx][0], data[idx][1], 'bo')
plt.subplot(1, 2, 2)
plt.title('Prediction', fontsize=18)
for idx in range(data.shape[0]):
if pred_y[idx] == 0:
plt.plot(data[idx][0], data[idx][1], 'ro')
else:
plt.plot(data[idx][0], data[idx][1], 'bo')
plt.savefig(f"./results/{task}__{self.initial_lr}_({self.layer1},{self.layer2})_pred.jpg")
plt.show()
def forward(self, inputs):
# Forward pass
self.input = inputs
self.a1 = sigmoid(np.dot(self.input, self.w1) + self.b1)
self.a2 = sigmoid(np.dot(self.a1, self.w2) + self.b2)
output = sigmoid(np.dot(self.a2, self.w3) + self.b3)
return output
def backward(self):
# backward pass
dout = self.error
grad_a3 = np.multiply(dout, der_sigmoid(self.output))
grad_w3 = np.dot(self.a2.T, grad_a3)
grad_b3 = np.sum(grad_a3, axis=0)
grad_z2 = np.dot(grad_a3, self.w3.T)
grad_a2 = np.multiply(grad_z2, der_sigmoid(self.a2))
grad_w2 = np.dot(self.a1.T, grad_a2)
grad_b2 = np.sum(grad_a2, axis=0)
grad_z1 = np.dot(grad_a2, self.w2.T)
grad_a1 = np.multiply(grad_z1, der_sigmoid(self.a1))
grad_w1 = np.dot(self.input.T, grad_a1)
grad_b1 = np.sum(grad_a1, axis=0)
self.v_w1 = self.momentum * self.v_w1 + self.lr * grad_w1
self.v_w2 = self.momentum * self.v_w2 + self.lr * grad_w2
self.v_w3 = self.momentum * self.v_w3 + self.lr * grad_w3
self.v_b1 = self.momentum * self.v_b1 + self.lr * grad_b1
self.v_b2 = self.momentum * self.v_b2 + self.lr * grad_b2
self.v_b3 = self.momentum * self.v_b3 + self.lr * grad_b3
self.w1 -= self.v_w1
self.w2 -= self.v_w2
self.w3 -= self.v_w3
self.b1 -= self.v_b1
self.b2 -= self.v_b2
self.b3 -= self.v_b3
def train(self, inputs, labels):
"""
model training
:param inputs: the training (and testing) data used in the model.
:param labels: the ground truth of correspond to input data.
"""
# make sure that the amount of data and label is match
assert inputs.shape[0] == labels.shape[0]
n = inputs.shape[0]
self.pre_error = 1000
error = 0
loss_list = []
acc_list = []
for epochs in range(self.epochs):
for idx in range(n):
self.output = self.forward(inputs[idx:idx + 1, :])
self.error = self.output - labels[idx:idx + 1, :]
self.backward()
train_loss, train_acc = self.test(inputs, labels)
train_loss = train_loss.squeeze().squeeze()
print(f"Epoch {epochs + 1}/{self.epochs} train_loss: {train_loss:.4f} train_acc: {train_acc:.4f}")
if train_loss > self.pre_error:
self.lr *= 0.9
pass
self.pre_error = error
loss_list.append(train_loss)
acc_list.append(train_acc)
self.plot_curve(loss_list, acc_list)
self.save_model()
print('Training finished')
test_loss, test_acc = self.test(inputs, labels, True)
test_loss = test_loss.squeeze().squeeze()
print(f"test_loss: {test_loss:.4f}\ttest_acc: {test_acc:.4f}")
def save_model(self):
task = args.task
model_dict = {'w1': self.w1,
'w2': self.w2,
'w3': self.w3,
'b1': self.b1,
'b2': self.b2,
'b3': self.b3}
with open(f"./checkpoints/{task}_{self.initial_lr}_({self.layer1},{self.layer2}).pkl", 'wb') as handle:
pickle.dump(model_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
def plot_curve(self, loss, acc):
task = args.task
x = np.linspace(0, 999, 1000).astype(int)
plt.figure()
plt.subplot(1, 2, 1)
plt.title('Loss', fontsize=18)
plt.plot(x, loss)
plt.subplot(1, 2, 2)
plt.title('Accuracy', fontsize=18)
plt.plot(x, acc)
plt.savefig(f"./results/{task}_{self.initial_lr}_({self.layer1},{self.layer2})_curve.jpg")
plt.show()
def test(self, inputs, labels, print_res=False):
"""
testing
:param inputs: the testing data. One or several data samples are both okay.
The shape is expected to be [BatchSize, 2].
:param labels: the ground truth correspond to the inputs.
"""
n = inputs.shape[0]
error = 0
acc = 0
all_result = []
for idx in range(n):
result = self.forward(inputs[idx:idx + 1, :])
all_result.append(result)
error += abs(result - labels[idx:idx + 1, :])
acc += (result[0][0] >= 0.5) == labels[idx:idx + 1, :][0][0]
error /= n
acc /= n
if print_res:
for res in all_result:
print(res)
return error, acc
def load_model(self, load_path):
with open(load_path, 'rb') as pickle_in:
model_dict = pickle.load(pickle_in)
self.w1 = model_dict['w1']
self.w2 = model_dict['w2']
self.w3 = model_dict['w3']
self.b1 = model_dict['b1']
self.b2 = model_dict['b2']
self.b3 = model_dict['b3']
def get_pred(model, data):
"""
get the prediction label from forward output
:param model: the simple feedforward network
:param data: data points
"""
data_size = data.shape[0]
pred = np.zeros(data_size, dtype=int)
output = model.forward(data)
for i in range(data_size):
pred[i] = 0 if output[i, :] < 0.5 else 1
return pred
if __name__ == "__main__":
task = args.task
lr = args.lr
hidden_size = args.hidden_size
load = args.load
model_path=args.model_path
if not os.path.isdir("./data"):
os.mkdir("./data")
if not os.path.isdir("./results"):
os.mkdir("./results")
if not os.path.isdir("./checkpoints"):
os.mkdir("./checkpoints")
# generate data
if task == "linear":
if not os.path.exists("./data/linear_data.csv"):
data, label = generate_linear(n=100)
data = np.append(data, label, axis=1)
np.savetxt("./data/linear_data.csv", data, delimiter=",")
else:
all_data = np.genfromtxt("./data/linear_data.csv", delimiter=",")
data, label = all_data[:, :2], all_data[:, 2]
label = label.astype(int).reshape(-1, 1)
if task == "xor":
if not os.path.exists("./data/xor_data.csv"):
data, label = generate_XOR_easy()
data = np.append(data, label, axis=1)
np.savetxt("./data/xor_data.csv", data, delimiter=",")
else:
all_data = np.genfromtxt("./data/xor_data.csv", delimiter=",")
data, label = all_data[:, :2], all_data[:, 2]
label = label.astype(int).reshape(-1, 1)
# training and testing
model = Model(hidden_size, 1000, lr)
# model.train(data, label)
# ./checkpoints/linear_0.01_512,32.pkl
# ./checkpoints/xor_0.1_512,32.pkl
if load == True:
model.load_model(model_path)
test_loss, test_acc = model.test(data, label,print_res=True)
test_loss = test_loss.squeeze().squeeze()
print(f"test_loss: {test_loss:.4f}\ttest_acc: {test_acc:.4f}")
pred = get_pred(model, data)
model.plot_result(data, label, pred)