-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2487 lines (2272 loc) · 128 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from cProfile import label
import math
from time import time
from traceback import print_tb
import uuid
import autograd.numpy as np
import scipy.optimize as spo
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from mpl_toolkits import mplot3d
import autograd.numpy.random as npr
from autograd import grad
from autograd.misc.optimizers import unflatten_optimizer
from autograd.misc.optimizers import adam as adam_one_param
from autograd.builtins import SequenceBox
from autograd.misc import flatten
from memory_profiler import profile #@profile
import random
import functools
import math
####### Misc
def calltracker(func):
@functools.wraps(func)
def wrapper(*args):
wrapper.has_been_called = True
return func(*args)
wrapper.has_been_called = False
return wrapper
####### Data
class Sin_Reg():
def __init__(self, amp_range = (0.8,1.2), ph_range = (math.pi*-0.2,math.pi*0.2), sd = 0.1, sample_rng = (-5,5)):
self.amp_range = amp_range
self.ph_range = ph_range
self.sd = sd
self.sample_rng = sample_rng
def sin_fun_gen(self):
"""
Returns sin function with added noise from zero mean gaussian dist. with given standard deviation.
The sin function has randomly generated parameters for amplitude
and phase within given ranges
"""
a_1, a_2 = self.amp_range
p_1, p_2 = self.ph_range
a = npr.uniform(a_1,a_2) #Samples parameter for amplitude
b = npr.uniform(p_1,p_2) #Samples parameter for phase
def f(x):
return (np.sin(x+b)*a) + np.random.normal(scale=self.sd, size=len(x))
return f, str(uuid.uuid4()), {"Amplitude":a,"Phase":b} #Returns function of sin curve with random gaussian noise
def get_sin_points(self, sin_fun, num_points):
x_min , x_max = self.sample_rng
xs = npr.uniform(x_min, x_max, num_points)
ys = sin_fun(xs)
xs = np.transpose(np.array([xs]))
ys = np.transpose(np.array([ys]))
return [xs, ys]
class Sin_Time():
def __init__(self, amp=1.0, t_0=0, time_around_t_0=math.pi*0.1, sd = 0.1, sample_rng = (-5,5)):
self.amp = amp
self.t_0 = t_0
self.time_around_t_0 = time_around_t_0
self.sd = sd
self.sample_rng = sample_rng
def uni_time_dist():
return npr.uniform(t_0 - self.time_around_t_0, t_0 + self.time_around_t_0)
self.time_dist = uni_time_dist
def calc_phase_eq(time):
return time
self.get_phase = calc_phase_eq
def sin_fun_gen(self):
"""
Returns sin function with added noise from zero mean gaussian dist. with given standard deviation.
The sin function has set phase (class attribute) and is given a random time (phase)
"""
time = self.time_dist() #Samples parameter for phase
phase = self.get_phase(time)
def f(x):
return (np.sin(x+phase)*self.amp) + np.random.normal(scale=self.sd, size=len(x))
return f, "time:"+str(time) , {"Amplitude":self.amp,"Phase":phase} #Returns function of sin curve with random gaussian noise
def get_sin_points(self, sin_fun, num_points):
x_min , x_max = self.sample_rng
xs = npr.uniform(x_min, x_max, num_points)
ys = sin_fun(xs)
xs = np.transpose(np.array([xs]))
ys = np.transpose(np.array([ys]))
return [xs, ys]
class Clas_Time():
def __init__(self, t_0=0, time_around_t_0=0.5, sd = 0.5, mean_0=0, mean_1=1):
self.t_0 = t_0
self.time_around_t_0 = time_around_t_0
self.sd = sd
self.mean_0 = mean_0
self.mean_1 = mean_1
def clas_fun_gen(self):
"""
Returns a tuple of functions for generating points from two normal distributions offset from t_0
by a time picked uniformly from [t_0 - time_around_t_0, t_0 + time_around_t_0],
along with a task-id and dictionary of information on the task
"""
time = npr.uniform(self.t_0 - self.time_around_t_0, self.t_0 + self.time_around_t_0)
mean_zero = self.mean_0 + time
mean_one = self.mean_1 + time
def f(num_points):
return np.random.normal(loc=mean_zero,scale=self.sd, size=num_points)
def g(num_points):
return np.random.normal(loc=mean_one,scale=self.sd, size=num_points)
return (f,g), "time:"+str(time) , {"Mean of zero":mean_zero,"Mean of one":mean_one,"Sd":self.sd}
def get_clas_points(self, class_funs, num_points):
f_zero, f_one = class_funs
xs = np.append(f_zero(math.floor(num_points/2)), f_one(math.ceil(num_points/2)))
ys = np.append(np.zeros(math.floor(num_points/2)), np.ones(math.ceil(num_points/2)))
perm = np.random.permutation(num_points)
xs = xs[perm]
ys = ys[perm]
xs = np.transpose(np.array([xs]))
ys = np.transpose(np.array([ys]))
return [xs, ys]
class Data_Generator():
def __init__(self, task_gen, datapoint_retreiver):
self.task_gen = task_gen # This function should generate a random task and return it along with a unique ID pertaining to the task and useful task info (could be None)
self.dp_ret = datapoint_retreiver # This function when given a task and a number n, should get n data-points for given task
# data-points returned as a list, containing a list of inputs to the network and a second list of targets for the output
def k_shot(self, k):
task, task_id, task_info = self.task_gen()
points = self.dp_ret(task, k)
return (task_id, [np.array([points[0]]), np.array([points[1]])] ), task, task_info
def task_data(self, num_batches_fortask, num_points_pbatch):
task, task_id, task_info = self.task_gen()
batches_for_task_xs = []
batches_for_task_ys = []
for _ in range(num_batches_fortask):
one_batch = self.dp_ret(task, num_points_pbatch)
batches_for_task_xs.append(one_batch[0])
batches_for_task_ys.append(one_batch[1])
batches_for_task = (task_id, [np.array(batches_for_task_xs), np.array(batches_for_task_ys)])
return batches_for_task, task, task_info
def multiple_tasks_data(self, num_batches_oftasks, num_tasks_pbatch, num_batches_ptask, num_points_pbatch):
batches_oftasks = []
all_tasks = []
all_tasks_info = []
for _ in range(num_batches_oftasks):
ls = [ self.task_data(num_batches_ptask, num_points_pbatch) for _ in range(num_tasks_pbatch) ]
data = [item[0] for item in ls]
tasks = [item[1] for item in ls]
tasks_info = [item[2] for item in ls]
batches_oftasks.append(data)
all_tasks.append(tasks)
all_tasks_info.append(tasks_info)
return batches_oftasks, all_tasks, all_tasks_info
def multiple_tasks_test_data(self, num_tasks_pbatch, num_batches_ptask, num_points_pbatch):
ls = [ self.task_data(num_batches_ptask, num_points_pbatch) for _ in range(num_tasks_pbatch) ]
batch_oftasks = [[item[0] for item in ls]]
tasks = [[item[1] for item in ls]]
tasks_info = [[item[2] for item in ls]]
return batch_oftasks, tasks, tasks_info
def task_test_data(self, num_points_pbatch):
task, task_id, task_info = self.task_gen()
batch = self.dp_ret(task, num_points_pbatch)
xs = batch[0]
ys = batch[1]
batch_for_task = (task_id, [np.array(xs), np.array(ys)])
return batch_for_task, task, task_info
####### Activation functions
def ReLu(input, comparator=0.0):
return np.maximum(input,comparator) #ReLu activation function
def sigmoid(input):
return 1 / (1 + np.exp(-input)) #Sigmoid activation function
def hyperbolic(input):
return np.tanh(input) #Hyperbolic activation function
####### Loss
def least_squares(output, d_out):
"""
Returns least squares error of the network for given output of network and desired output
"""
return np.sum( (d_out - output)**2 ) #Returns the Least squares error between given ys and ys_dash output from network
def neg_log_likelihood(output, d_out):
"""
Computes negative log likelihood
"""
label_probabilities = output * d_out + (1 - output) * (1 - d_out)
return -np.sum(np.log(label_probabilities))
def forward_pass(input, w_b, act_fun):
"""
Performs forward pass of network, given network parameters and input
"""
output = False
for t in w_b:
weights, biases = t
input = np.matmul(input,weights) + biases #Sum over the inputs multiplied by their respective weights + bias
input = act_fun(input) #Assigns output of neurons using activation function assigned to class
output = input
return output
class Loss():
def __init__(self, task, act_fun, loss_fun, num_batches_ptask, track_loss=False, test_data_gen = False):
self.task = task #Inits the current task data
self.act_fun = act_fun #Inits the activation function of the class
self.num_batches = num_batches_ptask #Inits the number of batches we are using for the data
self.loss_fun = loss_fun #Inits the loss function to be used
self.track_loss = track_loss
self.loss_tracker = []
if test_data_gen != False:
self.test_data_gen = test_data_gen
self.test_tracker = []
self.test_fun = False
else:
self.test_data_gen = test_data_gen
""" We initialise some attributes to keep track of whats going on during use of this class for learning"""
self.pass_num = "Not assigned yet"
self.batch_num = "Not assigned yet"
def update_atrributes(self, task):
self.task = task #Updates the current task data
def get_indices(self, iter):
batch_num = iter%self.num_batches
epoch_num = int(iter/self.num_batches)
self.epoch_num = epoch_num
self.batch_num = batch_num
return epoch_num, batch_num
@calltracker
def objective(self, w_b, iter):
"""
This is function called during learning,
It keeps track (by updating attributes) of current data being used,
It also more importantly returns the error for learning on the data
given current weights and biases and data iteration number
"""
_, batch_num = self.get_indices(iter)
out = self.forward_pass(self.task[1][0][batch_num], w_b)
l = self.loss_fun(out, self.task[1][1][batch_num])
if self.track_loss : self.loss_tracker.append(l._value)
return l
@calltracker
def objective_kshot(self, w_b, _):
out = self.forward_pass(self.task[0][0], w_b)
return self.loss_fun(out, self.task[0][1])
def print_perf(self, *args, **kargs):
"""
Prints information to keep us in the know about the learning process
"""
if self.test_data_gen != False:
if self.test_fun == False:
if self.objective.has_been_called and (not self.objective_kshot.has_been_called):
l = Loss(self.test_data_gen(), self.act_fun, self.loss_fun, self.num_batches)
def test(args):
l.task = self.test_data_gen()
w_b, iter = args[0:2]
return l.objective(w_b, 0)
self.test_fun = test
self.test_tracker.append(self.test_fun(args))
elif self.objective_kshot.has_been_called:
l = Loss(self.test_data_gen(), self.act_fun, self.loss_fun, self.num_batches)
def test(args):
l.task = self.test_data_gen()
w_b = args[0]
return l.objective_kshot(w_b)
self.test_fun = test
self.test_tracker.append(self.test_fun(args))
else:
self.test_tracker.append(self.test_fun(args))
print("Epoch: ",self.epoch_num,", Batch: ",self.batch_num) #,", Point: ",self.point_num)
def forward_pass(self, input, w_b):
"""
Performs forward pass of network, given network parameters and input
"""
output = False
for t in w_b:
weights, biases = t
input = np.matmul(input,weights) + biases #Sum over the inputs multiplied by their respective weights + bias
input = self.act_fun(input) #Assigns output of neurons using activation function assigned to class
output = input
return output
class Meta_Loss():
def __init__(self, batched_tasks_data, act_fun, opt_fun, loss_fun, num_batches_ptask, num_of_tasks_pbatch, num_batches_oftasks,
inner_param, track_loss=False, test_data_gen = False, inner_callback=None):
self.tau_tracker = [] #TODO: remove
self.batched_tasks_data = batched_tasks_data
self.loss_fun = loss_fun
self.act_fun = act_fun
self.opt_fun = opt_fun
self.inner_param = inner_param
self.num_batches_oftasks = num_batches_oftasks
self.num_of_tasks_pbatch = num_of_tasks_pbatch
self.num_batches_ptask = num_batches_ptask
self.losses, self.grad_losses = self.init_losses(act_fun, loss_fun, num_batches_ptask)
self.track_loss = track_loss
self.loss_tracker = []
if test_data_gen != False:
self.test_data_gen = test_data_gen
self.test_tracker = []
self.test_fun = False
else:
self.test_data_gen = test_data_gen
self.inner_callback = inner_callback
def init_losses(self, act_fun, loss_fun, num_batches_ptask):
losses = []
grad_losses = []
for i in range(self.num_of_tasks_pbatch):
loss = Loss(None, act_fun, loss_fun, num_batches_ptask)
losses.append(loss)
grad_losses.append(grad(loss.objective))
return losses, grad_losses
def update_losses(self, batch_num):
ids = []
for i in range(self.num_of_tasks_pbatch):
id, _ = self.batched_tasks_data[batch_num][i]
self.losses[i].update_atrributes(self.batched_tasks_data[batch_num][i])
ids.append(id)
return ids
def get_indices(self, iter):
batch_num = iter%self.num_batches_oftasks
epoch_num = int(iter/self.num_batches_oftasks)
self.epoch_num = epoch_num
self.batch_num = batch_num
return epoch_num, batch_num
@calltracker
def objective_std(self, w_b, iter):
_, batch_num = self.get_indices(iter)
self.update_losses(batch_num)
sum = 0
for index in range(len(self.losses)):
theta_i = self.opt_fun(self.grad_losses[index], w_b, step_size=self.inner_param, num_iters=self.num_batches_ptask, callback=self.inner_callback)
out = self.losses[index].forward_pass(self.losses[index].task[1][0], theta_i)
calc_losses = self.loss_fun(out, self.losses[index].task[1][1])
sum = sum + calc_losses
if self.track_loss : self.loss_tracker.append(sum._value)
return sum
@calltracker
def objective_with_alpha(self, w_b, alphas, iter):
_, batch_num = self.get_indices(iter)
alpha_ids = self.update_losses(batch_num)
sum = 0
for index in range(len(self.losses)):
theta_i = self.opt_fun(self.grad_losses[index], w_b, step_size=alphas.get(alpha_ids[index]), num_iters=self.num_batches_ptask, callback=self.inner_callback)
out = self.losses[index].forward_pass(self.losses[index].task[1][0], theta_i)
calc_losses = self.loss_fun(out, self.losses[index].task[1][1])
sum = sum + calc_losses
if self.track_loss : self.loss_tracker.append(sum._value)
return sum
@calltracker
def objective_with_time(self, w_b, tau, iter):
if isinstance(tau, float):
self.tau_tracker.append(tau) #TODO: remove
elif isinstance(tau, np.ndarray):
self.tau_tracker.append(tau) #TODO: remove
# else:
# self.tau_tracker.append(tau._value) #TODO: remove
_, batch_num = self.get_indices(iter)
times = self.update_losses(batch_num)
sum = 0
for index in range(len(self.losses)):
alpha = tau *abs( self.t_0-float(times[index][5:]) )
theta_i = self.opt_fun(self.grad_losses[index], w_b, step_size=alpha, num_iters=self.num_batches_ptask, callback=self.inner_callback)
out = self.losses[index].forward_pass(self.losses[index].task[1][0], theta_i)
calc_losses = self.loss_fun(out, self.losses[index].task[1][1])
sum = sum + calc_losses
if self.track_loss and isinstance(w_b, SequenceBox) : self.loss_tracker.append(sum._value)
return sum
def print_perf(self, *args, **kargs):
"""
Prints information to keep us in the know about the learning process
"""
if self.test_data_gen != False:
if self.test_fun == False:
if self.objective_std.has_been_called:
ml = Meta_Loss(self.test_data_gen(), self.act_fun, self.opt_fun, self.loss_fun, self.num_batches_ptask,
self.num_of_tasks_pbatch, self.num_batches_oftasks, self.inner_param)
def test(args):
ml.batched_tasks_data = self.test_data_gen()
w_b, iter = args[0:2]
return ml.objective_std(w_b, 0)
self.test_fun = test
self.test_tracker.append(self.test_fun(args))
elif self.objective_with_alpha.has_been_called:
ml = Meta_Loss(self.test_data_gen(), self.act_fun, self.opt_fun, self.loss_fun, self.num_batches_ptask,
self. num_of_tasks_pbatch, self.num_batches_oftasks, self.inner_param)
def test(args):
ml.batched_tasks_data = self.test_data_gen()
w_b, alphas, iter = args[0:3]
return ml.objective_with_alpha(w_b, alphas, 0)
self.test_fun = test
self.test_tracker.append(self.test_fun(args))
elif self.objective_with_time.has_been_called:
ml = Meta_Loss(self.test_data_gen(), self.act_fun, self.opt_fun, self.loss_fun, self.num_batches_ptask,
self. num_of_tasks_pbatch, self.num_batches_oftasks, self.inner_param)
ml.t_0 = self.t_0
def test(args):
ml.batched_tasks_data = self.test_data_gen()
w_b, tau, iter = args[0:3]
return ml.objective_with_time(w_b, tau, 0)
self.test_fun = test
self.test_tracker.append(self.test_fun(args))
else:
self.test_tracker.append(self.test_fun(args))
print("Meta Epoch: ",self.epoch_num,", Meta Batch: ",self.batch_num)
####### Optimizers
def adam(grad_x0, x0, step_size=0.001, num_iters=100, callback=None, **kwargs):
"""
Performs optimization using adam
"""
def two_param(grad_x0, x0, grad_x1, x1, callback=None, step_size=0.001, num_iters=100, b1=0.9, b2=0.999, eps=10**-8):
len0, _ = flatten(x0)
m0 = np.zeros(len(len0))
v0 = np.zeros(len(len0))
len1, _ = flatten(x1)
m1 = np.zeros(len(len1))
v1 = np.zeros(len(len1))
for i in range(num_iters):
g_x0 = grad_x0(x0, x1, i)
x0, unflat_x0 = flatten(x0)
g_x0, _ = flatten(g_x0)
m0 = (1 - b1) * g_x0 + b1 * m0 # First moment estimate.
v0 = (1 - b2) * (g_x0**2) + b2 * v0 # Second moment estimate.
mhat0 = m0 / (1 - b1**(i + 1)) # Bias correction.
vhat0 = v0 / (1 - b2**(i + 1))
x0 = x0 - step_size*mhat0/(np.sqrt(vhat0) + eps)
x0 = unflat_x0(x0)
g_x1 = grad_x1(x0, x1, i)
x1, unflat_x1 = flatten(x1)
g_x1, _ = flatten(g_x1)
m1 = (1 - b1) * g_x1 + b1 * m1 # First moment estimate.
v1 = (1 - b2) * (g_x1**2) + b2 * v1 # Second moment estimate.
mhat1 = m1 / (1 - b1**(i + 1)) # Bias correction.
vhat1 = v1 / (1 - b2**(i + 1))
x1 = x1 - step_size*mhat1/(np.sqrt(vhat1) + eps)
x1 = unflat_x1(x1)
if callback: callback(x0, x1, i)
return x0, x1
if len(kwargs) == 0:
return adam_one_param(grad_x0, x0, callback=callback, step_size=step_size, num_iters=num_iters)
elif len(kwargs) == 2:
grad_x1 = kwargs.get("grad_x1")
x1 = kwargs.get("x1")
return two_param(grad_x0, x0, grad_x1, x1, callback=callback, step_size=step_size, num_iters=num_iters)
else:
raise Exception("Only support optimizing over one or two parameters")
def basic(grad_x0, x0, step_size=0.001, num_iters=100, callback=None, **kwargs):
"""
Performs basic optimization
"""
@unflatten_optimizer
def one_param(grad, params, callback=None, step_size=0.001, num_iters=100):
"""
Performs basic optimization
"""
for i in range(num_iters):
g = grad(params, i)
if callback: callback(params, i, g)
params = params - (step_size*g)
return params
def two_param(grad_x0, x0, grad_x1, x1, callback=None, step_size=0.001, num_iters=100):
for i in range(num_iters):
g_x0 = grad_x0(x0, x1, i)
x0, unflat_x0 = flatten(x0)
g_x0, _ = flatten(g_x0)
x0 -= g_x0 * step_size
x0 = unflat_x0(x0)
g_x1 = grad_x1(x0, x1, i)
x1, unflat_x1 = flatten(x1)
g_x1, _ = flatten(g_x1)
x1 -= g_x1 * step_size
x1 = unflat_x1(x1)
if callback: callback(x0, x1, i)
return x0, x1
if len(kwargs) == 0:
return one_param(grad_x0, x0, callback=callback, step_size=step_size, num_iters=num_iters)
elif len(kwargs) == 2:
grad_x1 = kwargs.get("grad_x1")
x1 = kwargs.get("x1")
return two_param(grad_x0, x0, grad_x1, x1, callback=callback, step_size=step_size, num_iters=num_iters)
else:
raise Exception("Only support optimizing over one or two parameters")
####### Neural Network
def init_alphas(alpha, data):
ids = {task[0] for batch_of_tasks in data for task in batch_of_tasks}
d = {key:alpha for key in ids}
d["init_param_for_alpha"] = alpha
return d
def init_weights_biases(scale, num_neurons):
"""
Return a list of tuples containing the matrices for the weights and biases of each layer
(matrices of the appropriate size for given layer sizes in the neural network)
"""
weights = [] #List where we will append our weight matrices for each layer
for i in range(len(num_neurons)-1):
weights.append( (npr.random((num_neurons[i],num_neurons[i+1])) * scale , npr.random(num_neurons[i+1])) ) #Appends randomised scaled matrix of weights and bias vector (of correct sixe)
return weights
class NeuralNetwork():
def __init__(self, inner_param, beta, activation_function, loss_function, scale=0.1, num_neurons = [1,128,64,1], optimizer="basic"):
self.w_b = init_weights_biases(scale, num_neurons) #Initialises weights for the network
self.num_neurons = num_neurons #Initialises class attribute containing number of neurons on each layer
self.inner_param = inner_param #Initialise alpha hyper-parameter for network
self.beta = beta #Initialise beta hyper-parameter for network
self.act_fun = activation_function
self.loss_fun = loss_function
self.assign_opt(optimizer)
def assign_opt(self, opt_string):
if opt_string == "adam":
self.opt = adam
elif opt_string == "basic":
self.opt = basic
else:
raise ValueError("Not given valid optimizer string")
def train(self, task_data, num_iters, num_batches, task_id=False, set_params=True, track_loss=False, test_data_gen=False, time=False):
"""
Trains the network on given data for a task using given activation function and loss function
on num_iters iterations, and retuns loss_function object with final parameters assigned to its attribute theta_i
and trains according to name of optimization function given
"""
loss = Loss(task_data, self.act_fun, self.loss_fun, num_batches, track_loss=track_loss, test_data_gen=test_data_gen)
grad_loss = grad( loss.objective )
if task_id == False:
if isinstance(self.inner_param,dict):
alpha = self.inner_param.get("init_param_for_alpha")
elif task_data[0][0:5] == "time:" and isinstance(self.inner_param, tuple):
alpha = self.inner_param[0] * abs(self.inner_param[1] - float(task_data[0][5:]))
else:
alpha = self.inner_param
else:
alpha = self.inner_param.get(task_id)
theta_i = self.opt(grad_loss, self.w_b, step_size=alpha, num_iters=num_iters*num_batches, callback=loss.print_perf)
if set_params : self.w_b = theta_i
return loss, theta_i
def meta_train(self, tasks_data, num_iters, num_batches_ptask, num_of_tasks_pbatch, num_batches_oftasks,
gd_wrt_alpha = False, set_params = True, track_loss=False, time=False, test_data_gen=False):
"""
Performs meta-learning, given data on tasks, along with various knowledge on the structure of that data
"""
meta_loss = Meta_Loss(tasks_data, self.act_fun, self.opt, self.loss_fun, num_batches_ptask, num_of_tasks_pbatch, num_batches_oftasks,
self.inner_param, track_loss=track_loss, test_data_gen=test_data_gen)
if gd_wrt_alpha:
if time!=False:
raise Exception("Cant have time and gd_wrt_alpha arguments")
if tasks_data[0][0][0][0:5] == "time":
raise Exception("Data has wrong id format, is using time format")
grad_obj_w_b = grad(meta_loss.objective_with_alpha, argnum=0)
grad_obj_alpha = grad(meta_loss.objective_with_alpha, argnum=1)
alphas = init_alphas(self.inner_param, tasks_data)
theta, alphas = self.opt( grad_obj_w_b, self.w_b, step_size=self.beta, num_iters=num_iters, callback=meta_loss.print_perf, grad_x1=grad_obj_alpha, x1=alphas)
if set_params :
self.w_b = theta
self.inner_param = alphas
return meta_loss, theta
elif time != False:
if tasks_data[0][0][0][0:5] != "time:":
raise Exception("Data has wrong id format, is not using time format")
grad_obj_w_b = grad(meta_loss.objective_with_time, argnum=0)
grad_obj_tau = grad(meta_loss.objective_with_time, argnum=1)
meta_loss.t_0 = time[1]
theta, tau = self.opt( grad_obj_w_b, self.w_b, step_size=self.beta, num_iters=num_iters, callback=meta_loss.print_perf, grad_x1=grad_obj_tau, x1=time[0])
if set_params :
self.w_b = theta
self.inner_param = (tau, time[1])
return meta_loss, theta
else:
grad_obj_w_b = grad(meta_loss.objective_std, argnum=0)
theta = self.opt( grad_obj_w_b, self.w_b, step_size=self.beta, num_iters=num_iters, callback=meta_loss.print_perf)
if set_params : self.w_b = theta
return meta_loss, theta
####### K-shot
def k_shot(k, data_gen, neural_net):
k_data, task, task_info = data_gen.k_shot(k)
_, updated_theta = neural_net.train(k_data, 1, 1, set_params=False)
return updated_theta, task, task_info, k_data
def n_k_shot(n, k, data_gen, neural_net):
ls_updated_theta = []
ls_task = []
ls_task_info = []
ls_k_data = []
for i in range(n):
updated_theta, task, task_info, k_data = k_shot(k, data_gen, neural_net)
ls_updated_theta.append(updated_theta)
ls_task.append(task)
ls_task_info.append(task_info)
ls_k_data.append(k_data)
return ls_updated_theta, ls_task, ls_task_info, ls_k_data
####### Plotting - Sin Regression
class sin():
def __init__(self):
pass
@staticmethod
def get_outputs(inputs, act_fun, w_b):
loss = Loss(None, act_fun, None, None)
results = []
xs_t = np.transpose([inputs])
for x in xs_t:
results.append( loss.forward_pass(x, w_b)[0] )
results = np.array(results)
return results
@staticmethod
def flat_data(data_to_flat):
"""
Give data in meta structure, will flatten such that all x_values pertaining to a certain
task appear in the same list, does the same for y-values (also strips out the ids for the tasks)
"""
batches_of_tasks = [batches_of_task for meta_batch in data_to_flat for batches_of_task in meta_batch] #List containing list of batches for each task
batches_of_tasks = [batches_of_task[1] for batches_of_task in batches_of_tasks] #We get rid of the ID's
xs = [np.concatenate([np.transpose(batch)[0] for batch in task[0]]) for task in batches_of_tasks] #We flatten the together the batches of each task to get list of x-values for each task
ys = [np.concatenate([np.transpose(batch)[0] for batch in task[1]]) for task in batches_of_tasks] #We do the same for the y-values (Note that for both we also transpose the batches)
data = [(xs[index],ys[index]) for index in range(len(xs))] #We create a list of tuples, by putting the x-values and y-values belonging to the same task into a tuple
return data
@staticmethod
def flat_funs_or_params(thing_to_flat):
"""
Flattens meta structured (only to task depth) data such that it is just a list with each element corresponding to whats at the task depth
"""
batches_of_tasks = [batches_of_task for meta_batch in thing_to_flat for batches_of_task in meta_batch] #List containing list of batches for each task
return batches_of_tasks
@staticmethod
def plot_fun(file_stem, xs, training_data, results, fun_parameters, loss_function, show=False):
"""
Debugging plot
"""
if len(xs)!=len(results):
raise Exception("Number of x-values does not match number of y-values (results)")
amp , phase = fun_parameters[0].values()
avg_loss = loss_function(results[0], np.sin(xs+phase)*amp )/len(xs)
fig = plt.figure()
plt.plot(xs, np.sin(xs+phase)*amp, color='blue') #Scatter plot of true Sin curve
# train_xs = [item for batch in training_data[index] for item in batch[0]]
# train_ys = [item for batch in training_data[index] for item in batch[1]]
train_xs = training_data[0].flatten()
train_ys = training_data[1].flatten()
plt.scatter(train_xs,train_ys, color="lightblue") #Scatter plot of training points used
plt.scatter(xs, results, color='red') #Scatter plot of Test points
plt.title("Simple sin regression")
plt.xlabel("x\n\n"+"mean "+loss_function.__name__+" loss = "+str(avg_loss))
plt.ylabel("y")
# loss_function.__name__+" loss = "+str(avg_loss)
plt.savefig(file_stem+"_function_"+"_graph", bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def plot_test_data_vs_output(training_data, xs, results, filename="test_data_vs_metaout", show=False):
"""
Plots the data (data given in meta structure) used to train the neural network, each task with a different color,
then plots on the same graph the results of the network (given) corresponding to the x-values in xs (given)
"""
colors = {}
for i in range(len(training_data)):
for j in range(len(training_data[0])):
train_xs = training_data[i][j][1][0].flatten()
train_ys = training_data[i][j][1][1].flatten()
if colors.get(training_data[i][j][0]) == None :
r = npr.random()
g = npr.random()
b = npr.random()
color = (r, g, b, 0.4)
colors[training_data[i][j][0]] = color
else:
color = colors.get(training_data[i][j][0])
plt.scatter(train_xs,train_ys, color=color)
plt.scatter(xs, results, color='red')
plt.title("Simple sin regression")
plt.xlabel("x")
plt.ylabel("y")
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def write_info(*args, filename="sim_info"):
"""
Creates a file and then writes to the file, on each line printing each key and value pair,
it does this for each dictionary given as an argument
"""
f = open(filename, "w")
for arg in args:
for key in arg.keys():
f.write( str(key) + " : " + str(arg.get(key)) + "\n")
f.close()
@staticmethod
def vis_sin_data(params, data_points, filename="visualisation_of_sin_data", info=True, show=False):
"""
Plots data points against their underlying sin curves,
data_points is a list of tuples containing a list of x and a list of y coordinates for a single task (cant have ids)
(can use flat_data to obtain this kind of structure from meta structured data)
"""
if len(params) != len(data_points):
raise Exception("Dont have data points corresponding to each function")
if (not isinstance(params,list)) and (not isinstance(data_points,list)):
# We format arguments as lists if only single function and tuple of data given
params = [params]
data_points = [data_points]
colors = [(random.random(),random.random(),random.random()) for i in range(len(params))]
min = data_points[0][0][0]
max = data_points[0][0][0]
for index in range(len(data_points)):
if data_points[index][0].min() <= min:
min = data_points[index][0].min()
if data_points[index][0].max() >= max:
max = data_points[index][0].max()
plt.scatter(data_points[index][0], data_points[index][1], color=colors[index], label="Sampled Data Points From Sin Curve "+str(index)) #Scatter plot of sampled data points
for index in range(len(params)):
xs = np.linspace(min,max)
amp = params[index].get("Amplitude")
ph = params[index].get("Phase")
ys = np.sin(xs+ph)*amp
plt.plot(xs, ys, color=colors[index], label="Sin Curve "+str(index)) #Scatter plot of true Sin curve
if info == "not_time" :
for i in range(len(params)):
if str(params[i]["Phase"])[0] == '-':
plt.figtext(0.95, 0.42-(i*0.08), "Sin curve "+str(i)+" : amplitude="+str(params[i]["Amplitude"])[0:5]+", phase="+str(params[i]["Phase"])[0:6])
else:
plt.figtext(0.95, 0.42-(i*0.08), "Sin curve "+str(i)+" : amplitude="+str(params[i]["Amplitude"])[0:5]+", phase="+str(params[i]["Phase"])[0:5])
elif info == "time" :
for i in range(len(params)):
if str(params[i]["Phase"])[0] == '-':
plt.figtext(0.98, 0.42-(i*0.08), "Sin curve "+str(i)+" : time="+str(params[i]["Phase"])[0:6])
else:
plt.figtext(0.98, 0.42-(i*0.08), "Sin curve "+str(i)+" : time="+str(params[i]["Phase"])[0:5])
plt.title("Underlying Sin Curve and Sampled Points")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc=(1.1,0.5))
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def plot_k_shot(k_shot_data, w_b, act_fun, amp=1.0 , rng=(-5,5), time=False , filename="k_shot", show=False):
"""
Given list of k - (x, y) coords, with no ids, plots them against the output of the network using parameters of the network after k-shot learning (w_b)
"""
plt.scatter(k_shot_data[0], k_shot_data[1],label=str(len(k_shot_data[0]))+" Training Data Points")
ins = np.linspace(rng[0],rng[1])
outs = get_outputs(ins, act_fun, w_b)
plt.plot(ins, outs, label="Learned Network Output for Specific Task")
plt.ylim(-1.0*amp -0.5 ,1.0*amp +0.5)
if time != False :
if time[5] == '-':
plt.figtext(1, 0.42, "Time of task: "+time[5:12])
else:
plt.figtext(1, 0.42, "Time of task: "+time[5:11])
plt.title("K - Sample Points and Output of K-shot Learning")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc=(1.1,0.5))
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def plot_n_k_shot(n_k_shot_data, w_bs, act_fun, amps=False ,rng=(-5,5), times=False, filename="k_shot", show=False):
"""
Given a list of k-shot data, where each element in structure requested by plot_k_shot, and list of w_b after the k-shot learning
"""
if amps == False: amps = [amps for i in range(len(n_k_shot_data))]
if times == False: times = [times for i in range(len(n_k_shot_data))]
for index in range(len(n_k_shot_data)):
plot_k_shot(n_k_shot_data[index], w_bs[index], act_fun, amp=amps[index] ,rng=rng, time=times[index], filename=filename+"_"+str(index), show=show)
@staticmethod
def plot_k_shot_with_meta(k_shot_data, k_w_b, meta_w_b, act_fun, max_amp=1.0 , rng=(-5,5), time=False , filename="k_shot", show=False):
"""
Given list of k - (x, y) coords, with no ids, plots them against the output of the network using parameters of the network after k-shot learning (k_w_b),
and the output of the network immediately after meta-learning (using params meta_w_b)
"""
xs = np.transpose(k_shot_data[0][0])[0]
ys = np.transpose(k_shot_data[1][0])[0]
plt.scatter(xs, ys, label=str(len(xs))+" Training Data Points")
ins = np.linspace(rng[0],rng[1])
k_outs = sin.get_outputs(ins, act_fun, k_w_b)
meta_outs = sin.get_outputs(ins, act_fun, meta_w_b)
plt.plot(ins, k_outs, label="Learned Network Output for Specific Task")
plt.plot(ins, meta_outs, label="Learned Network Output After Meta-Learning")
plt.ylim(-1.0*max_amp *1.2 ,1.0*max_amp *1.2)
if time != False :
if time[5] == '-':
plt.figtext(1, 0.42, "Time of task: "+time[5:12])
else:
plt.figtext(1, 0.42, "Time of task: "+time[5:11])
plt.title("K - Sample Points and Output of K-shot Learning")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc=(1.1,0.5))
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def plot_n_k_shot_with_meta(n_k_shot_data, k_w_bs, meta_w_b, act_fun, max_amp=1.0 ,rng=(-5,5), times=False, filename="k_shot", show=False):
"""
Given list of k-shot data, parameters after k-shot learning plots (where each element in list uses data structure required for plot_k_shot_with_meta),
plots the k-shot data against the output of the network after k-shot learning and the output of the network immediately after meta-learning (using params meta_w_b)
"""
if times == False: times = [times for i in range(len(n_k_shot_data))]
for index in range(len(n_k_shot_data)):
sin.plot_k_shot_with_meta(n_k_shot_data[index], k_w_bs[index], meta_w_b, act_fun, max_amp=max_amp ,rng=rng, time=times[index], filename=filename+"_"+str(index), show=show)
@staticmethod
def metaparam_vs_sin(w_b, act_fun, rng=(-5,5), filename="network_out_vs_sin", show=False):
"""
Plots output of neural network given network parameters and activation function used for network against a sin curve
"""
ins = np.linspace(rng[0],rng[1])
outs = sin.get_outputs(ins, act_fun, w_b)
plt.plot(ins, outs, label="Network Output")
plt.plot(ins, np.sin(ins), label="Sin curve")
plt.title("Output of Meta-learning Trained Network and Generic Sin Curve")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc=(1.1,0.5))
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def training_loss(loss_list, filename="training_loss", show=False, loss_function="Least Squares"):
"""
Given a list of integer valued training loss values (ordered chronologically for each epoch), it plots them against the epoch it corresponds to
"""
plt.plot([i for i in range(len(loss_list))], loss_list)
plt.title("Loss Over Training")
plt.xlabel("Epoch")
plt.ylabel(loss_function+" Loss")
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def test_loss(loss_list, filename="test_loss", show=False, loss_function="Least Squares"):
"""
Given a list of integer valued test loss values (ordered chronologically for each epoch), it plots them against the epoch it corresponds to
"""
plt.plot([i for i in range(len(loss_list))], loss_list)
plt.title("Loss on Test Data Over Training")
plt.xlabel("Epoch")
plt.ylabel(loss_function+" Test Loss")
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def train_and_test_loss(test_loss_list, train_loss_list, filename="test_and_train_loss", show=False, loss_function="Least Squares"):
"""
Given a list of integer valued test and training loss values (ordered chronologically for each epoch), it plots them against the epoch it corresponds to
"""
plt.plot([i for i in range(len(test_loss_list))], test_loss_list, label="Test Loss")
plt.plot([i for i in range(len(train_loss_list))], train_loss_list, label="Train Loss")
plt.title("Loss on Test and Train Data Over Training")
plt.xlabel("Epoch")
plt.ylabel(loss_function+" Loss")
plt.legend()
plt.savefig(filename, bbox_inches="tight")
if show == True:
plt.show()
else:
plt.close()
@staticmethod
def sin_points_vs_expected_sin(amp_range, phase_range,num_curves=200,num_points_per_curve=10, rng=(-5,5), time=False):
x_min, x_max = rng
a_min, a_max = amp_range
p_min, p_max = phase_range
for i in range(num_curves):
xs = npr.uniform(x_min, x_max, num_points_per_curve)
a_i = npr.uniform(a_min, a_max)
p_i = npr.uniform(p_min, p_max)
ys = np.sin(xs+p_i) * a_i
r = npr.random()
g = npr.random()
b = npr.random()
color = (r, g, b, 0.4)
plt.scatter(xs,ys, color=color)
xs = np.linspace(x_min, x_max)
plt.plot(xs, np.sin(xs+((p_min+p_max)/2))*((a_min+a_max)/2),color="black")
plt.xlabel("x")
plt.ylabel("y")
if time == False : plt.title("Points from sin curves in task distribution and \"expected\" sin curve")
else : plt.title("Points from sin curves in task distribution and sin curve at $\mathregular{t_0}$")
plt.savefig("sin_points_vs_expected_sin")
plt.close()
@staticmethod
def dl_plot_test_data_vs_output(training_data, xs, results, filename="test_data_vs_out", show=False):
"""
Plots the data used to train the neural network,
then plots on the same graph the results of the network (given) corresponding to the x-values in xs (given)
"""
r = npr.random()
g = npr.random()
b = npr.random()
color = (r, g, b, 0.4)
for i in range(len(training_data[1][0])):
train_xs = training_data[1][0][i].flatten()
train_ys = training_data[1][1][i].flatten()
plt.scatter(train_xs,train_ys, color=color)
plt.plot(xs, results, color='red')