-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path_revamp.py
1845 lines (1375 loc) · 72.1 KB
/
_revamp.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
""" Feed Forward Network with Parallel Tempering for Multi-Core Systems"""
from __future__ import print_function, division
import multiprocessing
import os
import sys
import gc
import numpy as np
import random
import time
import operator
import math
import matplotlib as mpl
mpl.use('agg')
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import nn_mcmc_plots as mcmcplt
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
params = {'legend.fontsize': 10,
'legend.handlelength': 2}
plt.rcParams.update(params)
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from scipy.stats import multivariate_normal
from scipy.stats import norm
import io
from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout
from keras.objectives import MSE, MAE
from keras.callbacks import EarlyStopping
from keras.models import model_from_json
from keras.models import load_model
from datetime import datetime
import sys
import time
mplt = mcmcplt.Mcmcplot()
class Network:
def __init__(self, Topo, Train, Test, learn_rate):
self.Top = Topo # NN topology [input, hidden, output]
self.TrainData = Train
self.TestData = Test
self.lrate = learn_rate
self.W1 = np.random.randn(self.Top[0], self.Top[1]) / np.sqrt(self.Top[0])
self.B1 = np.random.randn(1, self.Top[1]) / np.sqrt(self.Top[1]) # bias first layer
self.W2 = np.random.randn(self.Top[1], self.Top[2]) / np.sqrt(self.Top[1])
self.B2 = np.random.randn(1, self.Top[2]) / np.sqrt(self.Top[1]) # bias second layer
self.hidout = np.zeros((1, self.Top[1])) # output of first hidden layer
self.out = np.zeros((1, self.Top[2])) # output last layer
self.pred_class = 0
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sampleEr(self, actualout):
error = np.subtract(self.out, actualout)
sqerror = np.sum(np.square(error)) / self.Top[2]
return sqerror
def ForwardPass(self, X):
z1 = X.dot(self.W1) - self.B1
self.hidout = self.sigmoid(z1) # output of first hidden layer
z2 = self.hidout.dot(self.W2) - self.B2
self.out = self.sigmoid(z2) # output second hidden layer
self.pred_class = np.argmax(self.out)
## print(self.pred_class, self.out, ' ---------------- out ')
'''def BackwardPass(self, Input, desired):
out_delta = (desired - self.out).dot(self.out.dot(1 - self.out))
hid_delta = out_delta.dot(self.W2.T) * (self.hidout * (1 - self.hidout))
# print(self.B2.shape)
self.W2 += (self.hidout.T.reshape(self.Top[1],1).dot(out_delta) * self.lrate)
self.B2 += (-1 * self.lrate * out_delta)
self.W1 += (Input.T.reshape(self.Top[0],1).dot(hid_delta) * self.lrate)
self.B1 += (-1 * self.lrate * hid_delta)'''
def BackwardPass(self, Input, desired): # since data outputs and number of output neuons have different orgnisation
onehot = np.zeros((desired.size, self.Top[2]))
onehot[np.arange(desired.size),int(desired)] = 1
desired = onehot
out_delta = (desired - self.out)*(self.out*(1 - self.out))
hid_delta = np.dot(out_delta,self.W2.T) * (self.hidout * (1 - self.hidout))
self.W2 += np.dot(self.hidout.T,(out_delta * self.lrate))
self.B2 += (-1 * self.lrate * out_delta)
Input = Input.reshape(1,self.Top[0])
self.W1 += np.dot(Input.T,(hid_delta * self.lrate))
self.B1 += (-1 * self.lrate * hid_delta)
def decode(self, w):
w_layer1size = self.Top[0] * self.Top[1]
w_layer2size = self.Top[1] * self.Top[2]
w_layer1 = w[0:w_layer1size]
self.W1 = np.reshape(w_layer1, (self.Top[0], self.Top[1]))
w_layer2 = w[w_layer1size:w_layer1size + w_layer2size]
self.W2 = np.reshape(w_layer2, (self.Top[1], self.Top[2]))
self.B1 = w[w_layer1size + w_layer2size:w_layer1size + w_layer2size + self.Top[1]].reshape(1,self.Top[1])
self.B2 = w[w_layer1size + w_layer2size + self.Top[1]:w_layer1size + w_layer2size + self.Top[1] + self.Top[2]].reshape(1,self.Top[2])
def encode(self):
w1 = self.W1.ravel()
w1 = w1.reshape(1,w1.shape[0])
w2 = self.W2.ravel()
w2 = w2.reshape(1,w2.shape[0])
w = np.concatenate([w1.T, w2.T, self.B1.T, self.B2.T])
w = w.reshape(-1)
return w
def softmax(self):
prob = np.exp(self.out)/np.sum(np.exp(self.out))
return prob
def langevin_gradient(self, data, w, depth): # BP with SGD (Stocastic BP)
self.decode(w) # method to decode w into W1, W2, B1, B2.
size = data.shape[0]
Input = np.zeros((1, self.Top[0])) # temp hold input
Desired = np.zeros((1, self.Top[2]))
fx = np.zeros(size)
for i in range(0, depth):
for i in range(0, size):
pat = i
Input = data[pat, 0:self.Top[0]]
Desired = data[pat, self.Top[0]:]
self.ForwardPass(Input)
self.BackwardPass(Input, Desired)
w_updated = self.encode()
return w_updated
def evaluate_proposal(self, data, w ): # BP with SGD (Stocastic BP)
self.decode(w) # method to decode w into W1, W2, B1, B2.
size = data.shape[0]
Input = np.zeros((1, self.Top[0])) # temp hold input
Desired = np.zeros((1, self.Top[2]))
fx = np.zeros(size)
prob = np.zeros((size,self.Top[2]))
for i in range(0, size): # to see what fx is produced by your current weight update
Input = data[i, 0:self.Top[0]]
self.ForwardPass(Input)
fx[i] = self.pred_class
prob[i] = self.softmax()
## print(fx, 'fx')
## print(prob, 'prob' )
return fx, prob
class surrogate: #General Class for surrogate models for predicting likelihood given the weights
def __init__(self, model, X, Y, min_X, max_X, min_Y , max_Y, path, save_surrogate_data, model_topology):
self.path = path + '/surrogate'
indices = np.where(Y==np.inf)[0]
X = np.delete(X, indices, axis=0)
Y = np.delete(Y, indices, axis=0)
self.model_signature = 0.0
self.X = X
self.Y = Y
self.min_Y = min_Y
self.max_Y = max_Y
self.min_X = min_X
self.max_X = max_X
self.model_topology = model_topology
self.save_surrogate_data = save_surrogate_data
if model=="gp":
self.model_id = 1
elif model == "nn":
self.model_id = 2
elif model == "krnn": # keras nn
self.model_id = 3
self.krnn = Sequential()
else:
print("Invalid Model!")
def normalize(self, X):
maxer = np.zeros((1,X.shape[1]))
miner = np.ones((1,X.shape[1]))
for i in range(X.shape[1]):
maxer[0,i] = max(X[:,i])
miner[0,i] = min(X[:,i])
X[:,i] = (X[:,i] - min(X[:,i]))/(max(X[:,i]) - min(X[:,i]))
return X, maxer, miner
def create_model(self):
krnn = Sequential()
if self.model_topology == 1:
krnn.add(Dense(64, input_dim=self.X.shape[1], kernel_initializer='uniform', activation ='relu')) #64
krnn.add(Dense(16, kernel_initializer='uniform', activation='relu')) #16
if self.model_topology == 2:
krnn.add(Dense(120, input_dim=self.X.shape[1], kernel_initializer='uniform', activation ='relu')) #64
krnn.add(Dense(40, kernel_initializer='uniform', activation='relu')) #16
if self.model_topology == 3:
krnn.add(Dense(200, input_dim=self.X.shape[1], kernel_initializer='uniform', activation ='relu')) #64
krnn.add(Dense(50, kernel_initializer='uniform', activation='relu')) #16
krnn.add(Dense(1, kernel_initializer ='uniform', activation='sigmoid'))
return krnn
def train(self, model_signature):
#X_train, X_test, y_train, y_test = train_test_split(self.X, self.Y, test_size=0.10, random_state=42)
X_train = self.X
X_test = self.X
y_train = self.Y
y_test = self.Y #train_test_split(self.X, self.Y, test_size=0.10, random_state=42)
self.model_signature = model_signature
if self.model_id is 3:
if self.model_signature==1.0:
self.krnn = self.create_model()
else:
while True:
try:
# You can see two options to initialize model now. If you uncomment the first line then the model id loaded at every time with stored weights. On the other hand if you uncomment the second line a new model will be created every time without the knowledge from previous training. This is basically the third scheme we talked about for surrogate experiments.
# To implement the second scheme you need to combine the data from each training.
self.krnn = load_model(self.path+'/model_krnn_%s_.h5'%(model_signature-1))
#self.krnn = self.create_model()
break
except EnvironmentError as e:
# pass
# # print(e.errno)
# time.sleep(1)
print ('ERROR in loading latest surrogate model, loading previous one in TRAIN')
early_stopping = EarlyStopping(monitor='val_loss', patience=5)
self.krnn.compile(loss='mse', optimizer='adam', metrics=['mse'])
train_log = self.krnn.fit(X_train, y_train.ravel(), batch_size=50, epochs=20, validation_split=0.1, verbose=0, callbacks=[early_stopping])
scores = self.krnn.evaluate(X_test, y_test.ravel(), verbose = 0)
# print("%s: %.5f" % (self.krnn.metrics_names[1], scores[1]))
self.krnn.save(self.path+'/model_krnn_%s_.h5' %self.model_signature)
# print("Saved model to disk ", self.model_signature)
'''plt.plot(train_log.history["loss"], label="loss")
plt.plot(train_log.history["val_loss"], label="val_loss")
plt.savefig(self.path+'/%s_0.png'%(self.model_signature))
plt.clf()'''
results = np.array([scores[1]])
# print(results, 'train-metrics')
with open(('%s/train_metrics.txt' % (self.path)),'ab') as outfile:
np.savetxt(outfile, results)
if self.save_surrogate_data is True:
with open(('%s/learnsurrogate_data/X_train.csv' % (self.path)),'ab') as outfile:
np.savetxt(outfile, X_train)
with open(('%s/learnsurrogate_data/Y_train.csv' % (self.path)),'ab') as outfile:
np.savetxt(outfile, y_train)
with open(('%s/learnsurrogate_data/X_test.csv' % (self.path)),'ab') as outfile:
np.savetxt(outfile, X_test)
with open(('%s/learnsurrogate_data/Y_test.csv' % (self.path)),'ab') as outfile:
np.savetxt(outfile, y_test)
def predict(self, X_load, initialized):
if self.model_id == 3:
if initialized == False:
model_sign = np.loadtxt(self.path+'/model_signature.txt')
self.model_signature = model_sign
while True:
try:
self.krnn = load_model(self.path+'/model_krnn_%s_.h5'%self.model_signature)
# # print (' Tried to load file : ', self.path+'/model_krnn_%s_.h5'%self.model_signature)
break
except EnvironmentError as e:
print(e)
# pass
self.krnn.compile(loss='mse', optimizer='rmsprop', metrics=['mse'])
krnn_prediction =-1.0
prediction = -1.0
else:
krnn_prediction = self.krnn.predict(X_load)[0]
prediction = krnn_prediction*(self.max_Y[0,0]-self.min_Y[0,0]) + self.min_Y[0,0]
return prediction, krnn_prediction
class ptReplica(multiprocessing.Process):
def __init__(self, use_surrogate, use_langevin_gradients, learn_rate, save_surrogate_data, w, minlim_param, maxlim_param, samples, traindata, testdata, topology, burn_in, temperature, swap_interval, path, parameter_queue, pause_chain_event, resume_chain_event, surrogate_parameter_queue, surrogate_interval, surrogate_prob, surrogate_start, surrogate_resume, surrogate_topology):
#MULTIPROCESSING VARIABLES
multiprocessing.Process.__init__(self)
self.processID = temperature
self.parameter_queue = parameter_queue
self.pause_chain_event = pause_chain_event
self.resume_chain_event = resume_chain_event
#SURROGATE VARIABLES
self.surrogate_parameter_queue = surrogate_parameter_queue
self.surrogate_start = surrogate_start
self.surrogate_resume = surrogate_resume
self.surrogate_interval = surrogate_interval
self.surrogate_prob = surrogate_prob
#PARALLEL TEMPERING VARIABLES
self.temperature = temperature
self.surrogate_topology = surrogate_topology
self.adapttemp = self.temperature #* ratio #
self.swap_interval = swap_interval
self.path = path
self.burn_in = burn_in
#FNN CHAIN VARIABLES (MCMC)
self.samples = samples
self.topology = topology
self.traindata = traindata
self.testdata = testdata
self.w = w
self.num_param = w.shape[0]
self.minY = np.zeros((1,1))
self.maxY = np.zeros((1,1))
self.minlim_param = minlim_param
self.maxlim_param = maxlim_param
self.use_surrogate = use_surrogate
self.use_langevin_gradients = use_langevin_gradients
self.save_surrogate_data = save_surrogate_data
self.compare_surrogate = True
self.sgd_depth = 1 # always should be 1
self.learn_rate = learn_rate # learn rate for langevin
self.l_prob = 0.5 # can be evaluated for diff problems - if data too large keep this low value since the gradients cost comp time
langevin_count = 0
def rmse(self, pred, actual):
return np.sqrt(((pred-actual)**2).mean())
def accuracy(self,pred,actual ):
count = 0
for i in range(pred.shape[0]):
if pred[i] == actual[i]:
count+=1
return 100*(count/pred.shape[0])
def likelihood_func(self, fnn, data, w):
y = data[:, self.topology[0]]
fx, prob = fnn.evaluate_proposal(data,w)
rmse = self.rmse(fx,y)
z = np.zeros((data.shape[0],self.topology[2]))
lhood = 0
for i in range(data.shape[0]):
for j in range(self.topology[2]):
if j == y[i]:
z[i,j] = 1
lhood += z[i,j]*np.log(prob[i,j])
return [lhood/self.adapttemp, fx, rmse, lhood]
def prior_likelihood(self, sigma_squared, nu_1, nu_2, w):
h = self.topology[1] # number hidden neurons
d = self.topology[0] # number input neurons
part1 = -1 * ((d * h + h + self.topology[2]+h*self.topology[2]) / 2) * np.log(sigma_squared)
part2 = 1 / (2 * sigma_squared) * (sum(np.square(w)))
log_loss = part1 - part2
return log_loss
def run(self):
# rmse_train_file = open(self.path+'/predictions/rmse_train_chain_'+ str(self.temperature)+ '.txt')
# rmse_test_file = open(self.path+'/predictions/rmse_test_chain_'+ str(self.temperature)+ '.txt')
# acc_train_file = open(self.path+'/predictions/acc_train_chain_'+ str(self.temperature)+ '.txt')
# acc_test_file = open(self.path+'/predictions/acc_test_chain_'+ str(self.temperature)+ '.txt')
#INITIALISING FOR FNN
testsize = self.testdata.shape[0]
trainsize = self.traindata.shape[0]
samples = self.samples
self.sgd_depth = 1
x_test = np.linspace(0,1,num=testsize)
x_train = np.linspace(0,1,num=trainsize)
netw = self.topology
y_test = self.testdata[:,netw[0]]
y_train = self.traindata[:,netw[0]]
w_size = (netw[0] * netw[1]) + (netw[1] * netw[2]) + netw[1] + netw[2] # num of weights and bias
pos_w = np.ones((samples, w_size)) #Posterior for all weights
s_pos_w = np.ones((samples, w_size)) #Surrogate Trainer
lhood_list = np.zeros((samples,1))
surrogate_list = np.zeros((samples ,1))
#fxtrain_samples = np.ones((samples/100, trainsize)) #Output of regression FNN for training samples
#fxtest_samples = np.ones((samples/100, testsize)) #Output of regression FNN for testing samples
rmse_train = np.zeros(samples)
rmse_test = np.zeros(samples)
acc_train = np.zeros(samples)
acc_test = np.zeros(samples)
learn_rate = 0.5
naccept = 0
#Random Initialisation of weights
w = self.w
eta = 0 #Junk variable
## print(w,self.temperature)
w_proposal = np.random.randn(w_size)
#Randomwalk Steps
step_w = 0.025
#Declare FNN
fnn = Network(self.topology, self.traindata, self.testdata, learn_rate)
#Evaluate Proposals
pred_train, prob_train = fnn.evaluate_proposal(self.traindata,w) #
pred_test, prob_test = fnn.evaluate_proposal(self.testdata, w) #
#Check Variance of Proposal
sigma_squared = 25
nu_1 = 0
nu_2 = 0
sigma_diagmat = np.zeros((w_size, w_size)) # for Equation 9 in Ref [Chandra_ICONIP2017]
np.fill_diagonal(sigma_diagmat, step_w)
delta_likelihood = 0.5 # an arbitrary position
prior_current = self.prior_likelihood(sigma_squared, nu_1, nu_2, w) # takes care of the gradients
#Evaluate Likelihoods
[likelihood, pred_train, rmsetrain, likl_without_temp] = self.likelihood_func(fnn, self.traindata, w)
[_, pred_test, rmsetest, likl_without_temp] = self.likelihood_func(fnn, self.testdata, w)
#Beginning Sampling using MCMC RANDOMWALK
likelihood_copy = likelihood
#accept_list = open(self.path+'/acceptlist_'+str(int(self.temperature*10))+'.txt', "a+")
trainacc = 0
testacc=0
prop_list = np.zeros((samples,w_proposal.size))
likeh_list = np.zeros((samples,2)) # one for posterior of likelihood and the other for all proposed likelihood
likeh_list[0,:] = [-100, -100] # to avoid prob in calc of 5th and 95th percentile later
surg_likeh_list = np.zeros((samples,3))
accept_list = np.zeros(samples)
num_accepted = 0
is_true_lhood = True
lhood_counter = 0
lhood_counter_inf = 0
reject_counter = 0
reject_counter_inf = 0
langevin_count = 0
pt_samples = samples * 1# this means that PT in canonical form with adaptive temp will work till pt samples are reached
burnsamples = int(self.samples * self.burn_in)
init_count = 0
trainset_empty = True
surrogate_model = None
surrogate_counter = 0
surr_train_set = np.zeros((1000, self.num_param+1))
self.resume_chain_event.clear()
count_real = 0
local_model_signature = 0.0
for i in range(samples-1):
timer1 = time.time()
lx = np.random.uniform(0,1,1)
ratio = ((samples -i) /(samples*1.0))
#self.adapttemp = self.temperature
if i < pt_samples:
self.adapttemp = self.temperature #* ratio #
if i == pt_samples and init_count ==0: # move to MCMC canonical
self.adapttemp = 1
[likelihood, pred_train, rmsetrain, likl_without_temp] = self.likelihood_func(fnn, self.traindata, w)
[_, pred_test, rmsetest, likl_without_temp] = self.likelihood_func(fnn, self.testdata, w)
init_count = 1
w_proposal = np.random.normal(w, step_w, w_size)
ku = random.uniform(0,1)
if trainset_empty == True:
surr_train_set = np.zeros((1, self.num_param+1))
if ku<self.surrogate_prob and i>=self.surrogate_interval+1:
is_true_lhood = False
if surrogate_model == None:
minmax = np.loadtxt(self.path+'/surrogate/minmax.txt')
self.minY[0,0] = minmax[0]
self.maxY[0,0] = minmax[1]
surrogate_model = surrogate("krnn",surrogate_X.copy(),surrogate_Y.copy(), self.minlim_param, self.maxlim_param, self.minY, self.maxY, self.path, self.save_surrogate_data, self.surrogate_topology)
surrogate_likelihood, nn_predict = surrogate_model.predict(w_proposal.reshape(1,w_proposal.shape[0]),False)
surrogate_likelihood = surrogate_likelihood *(1.0/self.adapttemp)
elif self.surrogate_init == 0.0:
surrogate_likelihood, nn_predict = surrogate_model.predict(w_proposal.reshape(1,w_proposal.shape[0]), False)
surrogate_likelihood = surrogate_likelihood *(1.0/self.adapttemp)
else:
surrogate_likelihood, nn_predict = surrogate_model.predict(w_proposal.reshape(1,w_proposal.shape[0]), True)
surrogate_likelihood = surrogate_likelihood *(1.0/self.adapttemp)
likelihood_mov_ave = (surg_likeh_list[i,2] + surg_likeh_list[i-1,2]+ surg_likeh_list[i-2,2])/3
likelihood_proposal = (surrogate_likelihood[0] * 0.5) + ( likelihood_mov_ave * 0.5)
if self.compare_surrogate is True:
[likelihood_proposal_true, pred_train, rmsetrain, likl_without_temp] = self.likelihood_func(fnn, self.traindata, w_proposal)
else:
likelihood_proposal_true = 0
#print ('\nSample : ', i, ' Chain :', self.adapttemp, ' -A', likelihood_proposal_true, ' vs. P ', likelihood_proposal, ' ---- nnPred ', nn_predict, self.minY, self.maxY )
surrogate_counter += 1
surg_likeh_list[i+1,0] = likelihood_proposal_true
surg_likeh_list[i+1,1] = likelihood_proposal
surg_likeh_list[i+1,2] = likelihood_mov_ave
else:
is_true_lhood = True
trainset_empty = False
surg_likeh_list[i+1,1] = np.nan
[likelihood_proposal, pred_train, rmsetrain, likl_without_temp] = self.likelihood_func(fnn, self.traindata, w_proposal)
[_, pred_test, rmsetest, likl_without_temp_] = self.likelihood_func(fnn, self.testdata, w_proposal)
likl_wo_temp = np.array([likl_without_temp])
X, Y = w_proposal,likl_wo_temp
X = X.reshape(1, X.shape[0])
Y = Y.reshape(1, Y.shape[0])
param_train = np.concatenate([X, Y],axis=1)
surr_train_set = np.vstack((surr_train_set, param_train))
surg_likeh_list[i+1,0] = likelihood_proposal
surg_likeh_list[i+1,2] = likelihood_proposal
surr_train_set[count_real, :] = param_train
count_real = count_real +1
prior_prop = self.prior_likelihood(sigma_squared, nu_1, nu_2, w_proposal) # takes care of the gradients
diff_likelihood = likelihood_proposal - likelihood_copy # (lhood_list[i,] /self.adapttemp) #
diff_prior = prior_prop - prior_current
try:
mh_prob = min(1, math.exp(diff_likelihood + diff_prior))
except OverflowError as e:
mh_prob = 1
accept_list[i+1] = naccept
#likeh_list[i+1,0] = surrogate_var
#prop_list[i+1,] = v_proposal
u = random.uniform(0, 1)
prop_list[i+1,] = w_proposal
likeh_list[i+1,0] = likl_without_temp
if u < mh_prob:
naccept = naccept + 1
likelihood = likelihood_proposal
likelihood_copy = likelihood_proposal
prior_current = prior_prop
w = w_proposal
pos_w[i + 1,] = w_proposal
if is_true_lhood is True:
lhood_list[i+1,] = (likelihood*self.adapttemp)
#fxtrain_samples[i + 1,] = pred_train
#fxtest_samples[i + 1,] = pred_test
rmse_train[i + 1,] = rmsetrain
rmse_test[i + 1,] = rmsetest
acc_train[i+1,] = self.accuracy(pred_train, y_train )
acc_test[i+1,] = self.accuracy(pred_test, y_test )
lhood_counter = lhood_counter + 1
print (i, self.adapttemp, lhood_counter , likelihood , diff_likelihood , diff_prior, acc_train[i+1,], acc_test[i+1,], self.adapttemp, 'accepted')
else:
lhood_list[i+1,] = np.inf
#fxtrain_samples[i + 1,] = np.inf
#fxtest_samples[i + 1,] = np.inf
rmse_train[i + 1,] = np.inf
rmse_test[i + 1,] = np.inf
acc_train[i+1,] = np.inf
acc_test[i+1,] = np.inf
'''rmse_train[i + 1,] = rmse_train[lhood_counter,]
rmse_test[i + 1,] = rmse_test[lhood_counter,]
acc_train[i+1,] = acc_train[lhood_counter,]
acc_test[i+1,] = acc_test[lhood_counter,] '''
lhood_counter_inf = lhood_counter_inf + 1
## print (i,lhood_counter , likelihood, self.adapttemp, acc_train[i+1,], acc_test[i+1,], 'accepted sur')
print (i,lhood_counter , likelihood, mh_prob, math.exp(diff_likelihood + diff_prior), diff_likelihood , diff_prior, acc_train[i+1,], acc_test[i+1,], self.adapttemp, ' not accepted')
else:
pos_w[i+1,] = pos_w[i,]
if is_true_lhood is True:
lhood_list[i+1,] = (likelihood_proposal*self.adapttemp)
#fxtrain_samples[i + 1,] = fxtrain_samples[i,]
#fxtest_samples[i + 1,] = fxtest_samples[i,]
rmse_train[i + 1,] = rmse_train[i,]
rmse_test[i + 1,] = rmse_test[i,]
acc_train[i+1,] = acc_train[i,]
acc_test[i+1,] = acc_test[i,]
reject_counter = reject_counter + 1
print (i,lhood_counter , likelihood, acc_train[lhood_counter,], acc_test[lhood_counter,], self.adapttemp, 'rejected true-lhood ')
else:
lhood_list[i+1,] = np.inf
#fxtrain_samples[i + 1,] = np.inf
#fxtest_samples[i + 1,] = np.inf
rmse_train[i + 1,] = np.inf
rmse_test[i + 1,] = np.inf
acc_train[i+1,] = np.inf
acc_test[i+1,] = np.inf
'''rmse_train[i + 1,] = rmse_train[lhood_counter,]
rmse_test[i + 1,] = rmse_test[lhood_counter,]
acc_train[i+1,] = acc_train[lhood_counter,]
acc_test[i+1,] = acc_test[lhood_counter,] '''
reject_counter_inf = reject_counter_inf + 1
print (i,lhood_counter , likelihood, self.adapttemp, rmsetrain, rmsetest, acc_train[i+1,], acc_test[i+1,], 'accepted surr ')
#SWAPPING PREP
'''if i%self.swap_interval == 0 and i != 0:
print("\n\nSample:{}\n\n".format(i))
param = np.concatenate([w, np.asarray([eta]).reshape(1), np.asarray([likelihood*self.adapttemp]),np.asarray([self.adapttemp]),np.asarray([i])])
# add parameters to the swap param queue and surrogate params queue
self.parameter_queue.put(param)
self.surrogate_parameter_queue.put(surr_train_set)
# Pause the chain execution and signal main process
self.pause_chain_event.set()
print("Temperature: {} waiting for swap and surrogate training complete signal. Event: {}".format(self.temperature, self.pause_chain_event.is_set()))
# Wait for the main process to complete the swap and surrogate training
self.resume_chain_event.clear()
self.resume_chain_event.wait()
result = self.parameter_queue.get()
w= result[0:w.size]
#eta = result[w.size]
#likelihood = result[w.size+1]/self.adapttemp
model_sign = np.loadtxt(self.path+'/surrogate/model_signature.txt')
self.model_signature = model_sign
#print("model_signature updated")
if self.model_signature==1.0:
minmax = np.loadtxt(self.path+'/surrogate/minmax.txt')
self.minY[0,0] = minmax[0]
self.maxY[0,0] = minmax[1]
# # print 'min ', self.minY, ' max ', self.maxY
dummy_X = np.zeros((1,1))
dummy_Y = np.zeros((1,1))
surrogate_model = surrogate("krnn", dummy_X, dummy_Y, self.minlim_param, self.maxlim_param, self.minY, self.maxY, self.path, self.save_surrogate_data, self.surrogate_topology )
self.surrogate_init, nn_predict = surrogate_model.predict(w_proposal.reshape(1,w_proposal.shape[0]), False)
# print("Surrogate init ", self.surrogate_init , " - should be -1")
del surr_train_set
trainset_empty = True'''
if i%self.surrogate_interval == 0 and i != 0:
print("\n\nSample:{}\n\n".format(i))
#param = np.concatenate([v_current, np.asarray([eta]).reshape(1), np.asarray([likelihood*self.adapttemp]),np.asarray([self.adapttemp]),np.asarray([i])])
# add parameters to the swap param queue and surrogate params queue
#self.parameter_queue.put(param)
surr_train = surr_train_set[1:count_real, :]
#self.surrogate_parameter_queue.put(all_param)
self.surrogate_parameter_queue.put(surr_train)
# Pause the chain execution and signal main process
self.pause_chain_event.set()
print("Temperature: {} waiting for swap and surrogate training complete signal. Event: {}".format(self.temperature, self.pause_chain_event.is_set()))
# Wait for the main process to complete the swap and surrogate training
self.resume_chain_event.clear()
self.resume_chain_event.wait()
# retrieve parameters fom queues if it has been swapped
''' comment below 2 lines to stop swap '''
#result = self.parameter_queue.get()
#v_current= result[0:v_current.size]
#eta = result[w.size]
#likelihood = result[w.size+1]/self.adapttemp
model_sign = np.loadtxt(self.path+'/surrogate/model_signature.txt')
self.model_signature = model_sign
#print("model_signature updated")
if self.model_signature==1.0:
minmax = np.loadtxt(self.path+'/surrogate/minmax.txt')
self.minY[0,0] = minmax[0]
self.maxY[0,0] = minmax[1]
# # print 'min ', self.minY, ' max ', self.maxY
dummy_X = np.zeros((1,1))
dummy_Y = np.zeros((1,1))
surrogate_model = surrogate("krnn", dummy_X, dummy_Y, self.minlim_param, self.maxlim_param, self.minY, self.maxY, self.path, self.save_surrogate_data, self.surrogate_topology )
local_model_signature = local_model_signature +1
self.surrogate_init, nn_predict = surrogate_model.predict(w_proposal.reshape(1,w_proposal.shape[0]), False)
#del surr_train_set
trainset_empty = True
np.savetxt(self.path+'/surrogate/traindata_'+ str(int(self.temperature*10)) +'_'+str(local_model_signature) +'_.txt', surr_train_set)
#surr_train_set = np.zeros((1, self.num_param+1))
count_real = 0
parameters= np.concatenate([w, np.asarray([eta]).reshape(1), np.asarray([likelihood]), np.asarray([self.adapttemp]), np.asarray([i])])
self.parameter_queue.put(parameters)
parameters = np.concatenate([s_pos_w[i-self.surrogate_interval:i,:],lhood_list[i-self.surrogate_interval:i,:]],axis=1)
self.surrogate_parameter_queue.put(parameters)
accept_ratio = naccept / (samples * 1.0) * 100
print("Temperature: {} accept ratio: {}".format(self.temperature, accept_ratio))
file_name = self.path+'/posterior/pos_w/'+'chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,pos_w )
'''file_name = self.path+'/predictions/fxtrain_samples_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, fxtrain_samples, fmt='%1.2f')
file_name = self.path+'/predictions/fxtest_samples_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, fxtest_samples, fmt='%1.2f') '''
file_name = self.path+'/predictions/rmse_test_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, rmse_test, fmt='%1.2f')
file_name = self.path+'/predictions/rmse_train_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, rmse_train, fmt='%1.2f')
file_name = self.path+'/predictions/acc_test_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, acc_test, fmt='%1.2f')
file_name = self.path+'/predictions/acc_train_chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name, acc_train, fmt='%1.2f')
#surg_likeh_list = surg_likeh_list[:,0:1]
file_name = self.path+'/posterior/surg_likelihood/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,surg_likeh_list, fmt='%1.4f')
file_name = self.path+'/posterior/pos_likelihood/chain_'+ str(self.temperature)+ '.txt'
np.savetxt(file_name,likeh_list, fmt='%1.4f')
file_name = self.path + '/posterior/accept_list/chain_' + str(self.temperature) + '_accept.txt'
np.savetxt(file_name, [accept_ratio], fmt='%1.4f')
file_name = self.path + '/posterior/accept_list/chain_' + str(self.temperature) + '.txt'
np.savetxt(file_name, accept_list, fmt='%1.4f')
print("Temperature {} chain dead!".format(self.temperature))
self.pause_chain_event.set()
return
class ParallelTempering:
def __init__(self, use_surrogate, use_langevin_gradients, learn_rate, save_surrogate_data, traindata, testdata, topology, num_chains, maxtemp, NumSample, swap_interval, surrogate_interval, surrogate_prob, path, path_db, surrogate_topology):
#FNN Chain variables
self.traindata = traindata
self.testdata = testdata
self.topology = topology
self.num_param = (topology[0] * topology[1]) + (topology[1] * topology[2]) + topology[1] + topology[2]
#Parallel Tempering variables
self.swap_interval = swap_interval
self.path = path
self.path_db = path_db
self.maxtemp = maxtemp
self.num_swap = 0
self.total_swap_proposals = 0
self.num_chains = num_chains
self.chains = []
self.temperatures = []
self.NumSamples = int(NumSample/self.num_chains)
self.sub_sample_size = max(1, int( 0.05* self.NumSamples))
# create queues for transfer of parameters between process chain
self.parameter_queue = [multiprocessing.Queue() for i in range(num_chains)]
self.chain_queue = multiprocessing.JoinableQueue()
self.pause_chain_events = [multiprocessing.Event() for i in range (self.num_chains)]
self.resume_chain_events = [multiprocessing.Event() for i in range (self.num_chains)]
# create variables for surrogates
self.surrogate_interval = surrogate_interval
self.surrogate_prob = surrogate_prob
self.surrogate_resume_events = [multiprocessing.Event() for i in range(self.num_chains)]
self.surrogate_start_events = [multiprocessing.Event() for i in range(self.num_chains)]
self.surrogate_parameter_queues = [multiprocessing.Queue() for i in range(self.num_chains)]
self.surrchain_queue = multiprocessing.JoinableQueue()
self.all_param = None
self.geometric = True # True (geometric) False (Linear)
self.minlim_param = 0.0
self.maxlim_param = 0.0
self.minY = np.zeros((1,1))
self.maxY = np.ones((1,1))
self.model_signature = 0.0
self.use_surrogate = use_surrogate
self.surrogate_topology = surrogate_topology
self.save_surrogate_data = save_surrogate_data
self.use_langevin_gradients = use_langevin_gradients
self.learn_rate = learn_rate
def default_beta_ladder(self, ndim, ntemps, Tmax): #https://github.com/konqr/ptemcee/blob/master/ptemcee/sampler.py
"""
Returns a ladder of :math:`\beta \equiv 1/T` under a geometric spacing that is determined by the
arguments ``ntemps`` and ``Tmax``. The temperature selection algorithm works as follows:
Ideally, ``Tmax`` should be specified such that the tempered posterior looks like the prior at
this temperature. If using adaptive parallel tempering, per `arXiv:1501.05823
<http://arxiv.org/abs/1501.05823>`_, choosing ``Tmax = inf`` is a safe bet, so long as
``ntemps`` is also specified.
"""
if type(ndim) != int or ndim < 1:
raise ValueError('Invalid number of dimensions specified.')
if ntemps is None and Tmax is None:
raise ValueError('Must specify one of ``ntemps`` and ``Tmax``.')
if Tmax is not None and Tmax <= 1:
raise ValueError('``Tmax`` must be greater than 1.')
if ntemps is not None and (type(ntemps) != int or ntemps < 1):
raise ValueError('Invalid number of temperatures specified.')
tstep = np.array([25.2741, 7., 4.47502, 3.5236, 3.0232,
2.71225, 2.49879, 2.34226, 2.22198, 2.12628,
2.04807, 1.98276, 1.92728, 1.87946, 1.83774,
1.80096, 1.76826, 1.73895, 1.7125, 1.68849,
1.66657, 1.64647, 1.62795, 1.61083, 1.59494,
1.58014, 1.56632, 1.55338, 1.54123, 1.5298,
1.51901, 1.50881, 1.49916, 1.49, 1.4813,
1.47302, 1.46512, 1.45759, 1.45039, 1.4435,
1.4369, 1.43056, 1.42448, 1.41864, 1.41302,
1.40761, 1.40239, 1.39736, 1.3925, 1.38781,
1.38327, 1.37888, 1.37463, 1.37051, 1.36652,
1.36265, 1.35889, 1.35524, 1.3517, 1.34825,
1.3449, 1.34164, 1.33847, 1.33538, 1.33236,
1.32943, 1.32656, 1.32377, 1.32104, 1.31838,
1.31578, 1.31325, 1.31076, 1.30834, 1.30596,
1.30364, 1.30137, 1.29915, 1.29697, 1.29484,
1.29275, 1.29071, 1.2887, 1.28673, 1.2848,
1.28291, 1.28106, 1.27923, 1.27745, 1.27569,
1.27397, 1.27227, 1.27061, 1.26898, 1.26737,
1.26579, 1.26424, 1.26271, 1.26121,
1.25973])
if ndim > tstep.shape[0]:
# An approximation to the temperature step at large
# dimension
tstep = 1.0 + 2.0*np.sqrt(np.log(4.0))/np.sqrt(ndim)
else:
tstep = tstep[ndim-1]
appendInf = False
if Tmax == np.inf:
appendInf = True
Tmax = None
ntemps = ntemps - 1
if ntemps is not None:
if Tmax is None:
# Determine Tmax from ntemps.
Tmax = tstep ** (ntemps - 1)
else:
if Tmax is None:
raise ValueError('Must specify at least one of ``ntemps'' and '
'finite ``Tmax``.')
# Determine ntemps from Tmax.
ntemps = int(np.log(Tmax) / np.log(tstep) + 2)
betas = np.logspace(0, -np.log10(Tmax), ntemps)
if appendInf:
# Use a geometric spacing, but replace the top-most temperature with
# infinity.
betas = np.concatenate((betas, [0]))
return betas
def assign_temperatures(self):
# #Linear Spacing
# temp = 2
# for i in range(0,self.num_chains):
# self.temperatures.append(temp)
# temp += 2.5 #(self.maxtemp/self.num_chains)
# # print (self.temperatures[i])
#Geometric Spacing
if self.geometric == True:
betas = self.default_beta_ladder(2, ntemps=self.num_chains, Tmax=self.maxtemp)
for i in range(0, self.num_chains):
self.temperatures.append(np.inf if betas[i] is 0 else 1.0/betas[i])
# print (self.temperatures[i])
else:
tmpr_rate = (self.maxtemp /self.num_chains)
temp = 1
for i in range(0, self.num_chains):
self.temperatures.append(temp)
temp += tmpr_rate
# print(self.temperatures[i])
def initialize_chains(self, burn_in):
self.burn_in = burn_in
self.assign_temperatures()
self.minlim_param = np.repeat([-100] , self.num_param) # priors for nn weights
self.maxlim_param = np.repeat([100] , self.num_param)
w = np.random.randn(self.num_param)
for i in range(0, self.num_chains):
self.chains.append(ptReplica(self.use_surrogate, self.use_langevin_gradients, self.learn_rate, self.save_surrogate_data, w, self.minlim_param, self.maxlim_param, self.NumSamples, self.traindata, self.testdata, self.topology, self.burn_in, self.temperatures[i], self.swap_interval, self.path, self.parameter_queue[i], self.pause_chain_events[i], self.resume_chain_events[i], self.surrogate_parameter_queues[i], self.surrogate_interval, self.surrogate_prob, self.surrogate_start_events[i], self.surrogate_resume_events[i], self.surrogate_topology))
def swap_procedure(self, parameter_queue_1, parameter_queue_2):
# if parameter_queue_2.empty() is False and parameter_queue_1.empty() is False:
swapped = False
param1 = parameter_queue_1.get()
param2 = parameter_queue_2.get()
w1 = param1[0:self.num_param]
eta1 = param1[self.num_param]
lhood1 = param1[self.num_param+1]
T1 = param1[self.num_param+2]
w2 = param2[0:self.num_param]
eta2 = param2[self.num_param]
lhood2 = param2[self.num_param+1]
T2 = param2[self.num_param+2]
#SWAPPING PROBABILITIES
try:
swap_proposal = min(1,0.5*np.exp(min(709, lhood2 - lhood1)))
except OverflowError:
swap_proposal = 1
u = np.random.uniform(0,1)
if u < swap_proposal:
self.num_swap += 1
param_temp = param1
param1 = param2
param2 = param_temp
swapped = True
else:
swapped = False
self.total_swap_proposals += 1
print("swapped: {} {}".format(param1[:2], param2[:2]))
return param1, param2, swapped
def surrogate_trainer(self,params):
#X = params[:,:self.num_param]
#Y = params[:,self.num_param].reshape(X.shape[0],1)
#indices = np.where(Y==np.inf)[0]
#X = np.delete(X, indices, axis=0)
#Y = np.delete(Y,indices, axis=0)
#surrogate_model = surrogate("nn",X,Y,self.path)
#surrogate_model.train()
X = params[:,:self.num_param]
Y = params[:,self.num_param].reshape(X.shape[0],1)
for i in range(Y.shape[1]):
min_Y = min(Y[:,i])
max_Y = max(Y[:,i])
self.minY[0,i] = min_Y * 2
self.maxY[0,i] = -1#max_Y
self.model_signature += 1.0
if self.model_signature == 1.0:
np.savetxt(self.path+'/surrogate/minmax.txt',[self.minY[0, 0], self.maxY[0, 0]])
np.savetxt(self.path+'/surrogate/model_signature.txt', [self.model_signature])