-
Notifications
You must be signed in to change notification settings - Fork 0
/
DL Entanglement Entropy (Source code).py
1823 lines (1382 loc) · 69.8 KB
/
DL Entanglement Entropy (Source code).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
#!/usr/bin/env python
# coding: utf-8
# ### The following provides the source code for reproducing results in section 3 of arXiv: 2305.00997 of using classical deep neural networks to predict von Neumann entropy. This is based on TensorFlow-Keras.
# In[ ]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import scienceplots
import tensorflow as tf
import os
import json
from sklearn.model_selection import train_test_split
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.python import metrics
import keras_tuner as kt
from keras.models import load_model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras import regularizers
get_ipython().run_line_magic('matplotlib', 'inline')
import warnings
warnings.filterwarnings('ignore')
plt.style.reload_library()
plt.style.use(['science','no-latex'])
plt.rcParams['figure.dpi'] = 500
"Hyperparameters"
# Please adjust the hyperparameters and the hypermodel_base function below.
# the following are hyperparameters for the KerasTuner
max_trials = 100
executions_per_trial = 2
patience = 8
search_epochs = 500
top_n = 5 # we pick the top_n models, note that this has to be at least the same as the max-trials
# the following are hyperparameters for retrained models
batch_size = 512
Retrain_training_times = 20
retrain_patience = 8
retrain_max_epochs = 1000
def hypermodel_base(hp):
#units = hp.Int(name="units", min_value=16, max_value=64, step=16)
activation = hp.Fixed("activation", "relu")
#learning_rate = hp.Fixed("learning_rate", 9e-3)
learning_rate = hp.Float("learning_rate", min_value=3e-3, max_value=9e-3, sampling="log")
dropout_rate = hp.Float("dropout_rate", min_value=0.1, max_value=0.5, sampling="log") # step=0.1
initializer = tf.keras.initializers.GlorotNormal(seed=42) # GlorotNormal is the default one, we add a seed
model = keras.Sequential()
for i in range(hp.Int("num_layers", 1, 4)):
if hp.Boolean("BatchNormalization"):
model.add(
Dense(
units=hp.Int(f"units_{i}", min_value=16, max_value=128, step=16), # num of units will be indep
use_bias = False, # if we use BatchNormalization, set bias to false and no activation
kernel_initializer=initializer,
)
)
model.add(BatchNormalization())
model.add(Activation(activation=activation)) # set activation after BatchNormalization
else:
model.add(
Dense(
units=hp.Int(f"units_{i}", min_value=16, max_value=128, step=16), # num of units will be indep
activation=activation,
kernel_initializer=initializer,
)
)
if hp.Boolean("dropout"):
model.add(layers.Dropout(rate=dropout_rate))
model.add(Dense(1))
optimizer = tf.keras.optimizers.Adam(
learning_rate=learning_rate,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
amsgrad=True) #hp.Boolean("amsgrad")
model.compile(optimizer=optimizer, loss="mse",
metrics=["mae"])
return model
class DataLoader(object):
def __init__(self, path, ratio=(0.8,0.1,0.1)):
X, y = self.load_dataset(path)
self.split_dataset(X, y, ratio)
self.X = X
self.y = y
def load_dataset(self, path):
df = pd.read_csv(path, encoding='utf-8')
X = df.drop(['Correct Entropy','Approx Entropy'], axis = 1)
y = df['Correct Entropy']
return X, y
def shuffle_dataset(self, path):
df = pd.read_csv(path, encoding='utf-8')
df_shuffle = df.sample(frac=1., axis=0, random_state = 42).reset_index(drop=True)
df_shuffle1 = df_shuffle.drop(['Correct Entropy', 'Approx Entropy'], axis = 1)
y_targets = df_shuffle['Correct Entropy']
return df_shuffle1, y_targets
def split_dataset(self, X, y, ratio):
'''
Args:
X: the training inputs array
y: the ground truth data array
ratio: (train, validation, test)
'''
assert sum(ratio) == 1
seed = 42
X_train_full, X_test, y_train_full, y_test = train_test_split(X, y, test_size=ratio[2], random_state = seed)
X_train, X_val, y_train, y_val = train_test_split(X_train_full, y_train_full,
test_size=round(ratio[1]/(ratio[0]+ratio[1]), 16),
random_state=seed)
self.X_train_full = X_train_full
self.y_train_full = y_train_full
self.X_train = X_train
self.y_train = y_train
self.X_val = X_val
self.y_val = y_val
self.X_test = X_test
self.y_test = y_test
def load_tuner(hypermodel, load_dir, load_project):
tuner = kt.BayesianOptimization(hypermodel,
objective="val_loss",
directory=load_dir,
project_name=load_project,
overwrite=False,
max_trials=max_trials,
executions_per_trial=executions_per_trial,
)
return tuner
def load_best_hyperparam(hypermodel, load_dir, load_project, top_n):
tuner = load_tuner(hypermodel, load_dir, load_project)
return tuner.get_best_hyperparameters(top_n)
# if you want to see the top_n hyper params, use below
# best_trials = tuner.oracle.get_best_trials(num_trials=top_n)
# for trial in best_trials:
# trial.summary()
# model = tuner.load_model(trial)
# Do some stuff to the model
def train_with_tuner_ensemble_models(data_path, hypermodel, hp_dir, hp_proj):
# the saved checkpoint is under "hp_dir/hp_proj/"
dataloader = DataLoader(data_path)
tuner = load_tuner(hypermodel, hp_dir, hp_proj)
callbacks = [keras.callbacks.EarlyStopping(monitor="val_loss", patience=patience)]
# keras.callbacks.ModelCheckpoint(model_name, save_best_only=True)]
tuner.search(x = dataloader.X_train, y = dataloader.y_train,
batch_size = batch_size, epochs=search_epochs, validation_data=(dataloader.X_val, dataloader.y_val),
callbacks=callbacks, verbose=1,)
tuner.results_summary()
return tuner
def train_with_tuner_ensemble_models_retrain(path_train, path_val, hypermodel, best_hps, max_epochs, model_save_path):
# Now we re-train each model with the best epoch*ratio and the full data.
# We monitor loss with EarlyStopping, the epoch*ratio will be the maximum possible epoch.
# We train each model multiple times and use the one with the best training loss.
dataloader = DataLoader(path_train)
dataloader_val = DataLoader(path_val)
X_full, y_full = dataloader_val.shuffle_dataset(path_val)
ratio = (len(dataloader.X_train)+len(dataloader.X_val))/len(dataloader.X_train)
# best_hps = tuner.get_best_hyperparameters(top_n)
callbacks = [keras.callbacks.EarlyStopping(monitor="loss", patience=retrain_patience, restore_best_weights=True)]
model_retrain = {}
model_history_retrain = {}
df_store_test = {}
df_store_test_final = {}
df_store_val = {}
df_store_test_over_training = {}
df_store_val_over_training = {}
relative_errors_sum = {}
pred_df = pd.DataFrame(dataloader.y_test).reset_index(drop=True) # the targets of the original train_test split
pred_val_df = pd.DataFrame(y_full) # the targets of the full validation dataset
Average_Epoch_List = []
model_re_save = {}
model_number_save = []
for i in range(0, top_n):
# n = 0
# while n < training_times:
# Average_Epoch_List.append(max_epochs)
# Average_Epoch_List.append(Average_Epoch[str(i) + str(n)])
# n = n + 1
j = 0
while j < Retrain_training_times:
# best_epoch = int(np.array(Average_Epoch_List).mean())
# Best_training_epochs = int(best_epoch * ratio)
model_retrain[str(i)] = hypermodel(best_hps[i])
model_re = model_retrain[str(i)]
model_re.fit(dataloader.X_train_full, dataloader.y_train_full,
epochs = max_epochs,
batch_size = batch_size,
callbacks=callbacks,
verbose=1,
)
model_re_save[str(i) + str(j)] = model_re
model_history_retrain[str(i) + str(j)] = model_re.history.history
test_predictions = model_re.predict(dataloader.X_test) # for the original train-test split
test_pred = pd.DataFrame(test_predictions)
test_pred.columns = ['Model_' + str(i) + ' #'+ str(j) + ' Predictions']
df_store_test[str(i) + str(j)] = test_pred
# save final model
model_re.save(os.path.join(model_save_path, f'top_{i}_times_{j}'))
j = j + 1
# We choose the smallest overall relative error in the "test dataset" as the final output
df_test_all = df_store_test[str(i) + str(0)]
for k in range(1, Retrain_training_times):
df_test_all = pd.concat([df_test_all, df_store_test[str(i) + str(k)]], axis=1)
df_compare = pd.concat([pred_df, df_test_all], axis = 1)
for l in range(0, Retrain_training_times):
df_rel_error = (abs(df_compare['Correct Entropy']-df_compare['Model_' + str(i) + ' #'+ str(l) + ' Predictions'])/df_compare['Correct Entropy'])*100
df_compare.insert(2+2*l, str(i)+'Rel Error (%) ' + str(l), df_rel_error)
print(df_compare)
relative_errors_sum[str(i)] = df_compare[[str(i)+'Rel Error (%) '+str(m) for m in range(0, Retrain_training_times)]].sum()
model_number = df_compare[[str(i)+'Rel Error (%) '+str(m) for m in range(0, Retrain_training_times)]].sum().argmin()
model_number_save.append(model_number)
print(f"{relative_errors_sum[str(i)]}")
print(f"# {model_number} has the smallest relative errors.")
df_store_test_final[str(i)] = df_compare['Model_' + str(i) + ' #'+ str(model_number) + ' Predictions']
# Then we choose the final model to predict the PredVal dataset
model_re = model_re_save[str(i)+str(model_number)]
val_predictions = model_re.predict(X_full) # for the Pred_validation dataset
val_pred = pd.DataFrame(val_predictions)
val_pred.columns = ['Model_' + str(i) + ' Pred_Val']
df_store_val[str(i)] = val_pred
# save final model
model_re.save(os.path.join(model_save_path, 'top_'+str(i)))
relative_errors_sum_df = pd.DataFrame(relative_errors_sum[str(0)])
for k in range(0, top_n):
relative_errors_sum_df = pd.concat([relative_errors_sum_df, pd.DataFrame(relative_errors_sum[str(k)])], axis=0)
print(f"# {relative_errors_sum_df.idxmin()} has the smallest relative errors.")
filepath = os.path.join(model_save_path, 'model_history_retrain.json')
with open(filepath, 'w') as handle:
json.dump(model_history_retrain, handle)
model_numbers_save_str = [str(i) for i in model_number_save]
path = os.path.join(*model_numbers_save_str)
with open(os.path.join(model_save_path, "model_number.txt"), "w") as f:
f.write(path)
# this shows how to load a model
# print(load_model(save_model_path+'/top_0').summary())
# print(load_model(save_model_path+'/top_1').summary())
return df_store_test_final, df_store_val, pred_df, pred_val_df, df_compare
def Ensemble_Retrained_Plots(save_model_path, save_path, best_model):
# Load the model_history_retrain
with open(os.path.join(save_model_path, "model_history_retrain.json"), "r") as f:
model_history_retrain = json.load(f)
# Load the model_number
with open(os.path.join(save_model_path, "model_number.txt"), "r") as f:
contents = f.read()
contents = contents.split("\n")
contents = [i.replace("\\", "") for i in contents]
str_list = str(contents[0])
model_number_save = [int(i) for i in str_list]
x_range_list = []
legend_labels = []
#fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=False, figsize=(20, 16))
fig, (ax1, ax3) = plt.subplots(2, 1, sharex=False, figsize=(20, 16))
y_max = []
y_max_mae = []
j = 0
while j < top_n:
y_max.append(max(model_history_retrain[str(j)+str(model_number_save[j])]["loss"][:].copy()))
y_max_mae.append(max(model_history_retrain[str(j)+str(model_number_save[j])]["mae"][:].copy()))
j = j +1
i = 0
while i < top_n:
y_loss = model_history_retrain[str(i)+str(model_number_save[i])]['loss']
y_metrics = model_history_retrain[str(i)+str(model_number_save[i])]["mae"]
x = range(1,len(y_loss)+1)
ax1.plot(x, y_loss, '.--')
#ax2.plot(x, y_loss, '.--')
ax3.plot(x, y_metrics, '.--')
#ax4.plot(x, y_metrics, '.--')
x_range_list.append(len(y_loss))
legend_labels.append('Model_' + str(i) + ' (Epoch= '+ str(x_range_list[i])+ ')')
i = i + 1
y_loss = model_history_retrain[str(i)+str(model_number_save[i])]['loss']
y_metrics = model_history_retrain[str(i)+str(model_number_save[i])]["mae"]
x = range(1,len(y_loss)+1)
ax1.plot(x, y_loss, '.--')
#ax2.plot(x, y_loss, '.--')
ax3.plot(x, y_metrics, '.--')
#ax4.plot(x, y_metrics, '.--')
x_range_list.append(len(y_loss))
legend_labels.append('Model_' + str(i) + ' (Epoch= '+ str(x_range_list[i])+ ')')
fig.legend(legend_labels, loc="right", bbox_to_anchor=(1.13, 0.5), frameon=False, edgecolor='black', borderpad=1, labelspacing=2, handlelength=3)
ax1.set_title("Loss Function")
ax1.set_xlabel("Epochs")
ax1.set_ylabel("MSE")
ax1.set_xlim([1, len(y_loss)-retrain_patience])
ax1.set_xticks(range(50,max(x_range_list),50))
ax1.set_yscale('log')
#ax1.set_xticklabels(range(5,max(x_range_list),5))
ax3.set_title("Metrics")
ax3.set_xlabel("Epochs")
ax3.set_ylabel("MAE")
ax3.set_xlim([1, len(y_loss)-retrain_patience])
ax3.set_xticks(range(50,max(x_range_list),50))
#ax3.set_xticklabels(range(5,max(x_range_list),5))
ax3.set_yscale('log')
fig.tight_layout()
plt.savefig(os.path.join(save_path, 'Ensem_Retrain.png'))
def generate_figures(train_data_path, test_data_path, model_path, save_fig_dir, best_model, best_model_number):
i = best_model
j = best_model_number
train_dataloader = DataLoader(train_data_path)
df_train = pd.DataFrame(train_dataloader.y_test)
df_train
df = pd.read_csv(test_data_path, encoding='utf-8')
df_shuffle = df.sample(frac=1., axis=0, random_state = 42)
X_test = df_shuffle.drop(['Correct Entropy', 'Approx Entropy'], axis = 1)
y_test = df_shuffle['Correct Entropy']
df_test = pd.DataFrame(y_test)
df_test
ymin = pd.concat([df_train, df_test], axis = 1)[['Correct Entropy','Correct Entropy']].min().min()*0.90
ymax = pd.concat([df_train, df_test], axis = 1)[['Correct Entropy','Correct Entropy']].max().max()*1.05
def compute_model_prediction(X_test, y_test, model):
inputs = X_test.to_numpy()
actual = y_test.to_numpy()
approx = inputs.sum(1)
sort_idx = np.argsort(actual)
inputs, actual, approx = inputs[sort_idx], actual[sort_idx], approx[sort_idx]
pred = model.predict(inputs).reshape(-1)
return (pred, actual, approx)
# def plot_entropy_comparison(pred, actual, approx, save_fig_dir):
# plt.figure(figsize=(10,10))
# plt.plot(actual)
# plt.plot(pred)
# plt.plot(approx)
# plt.legend(["von Neumann entropy", "Model predictions", "Approximate entropy"])
# plt.ylim([ymin, ymax])
# plt.savefig(save_fig_dir)
# plt.show()
def plot_entropy_comparison1(pred, actual, approx, save_fig_dir):
# Set the limits for the zoomed-in region
zoom_xlim = (600, 700)
zoom_ylim = (1.91, 1.98)
fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(actual)
ax.plot(pred)
ax.plot(approx)
ax.legend(["von Neumann entropy", "Model predictions", "Approximate entropy"])
ax.set_ylim([ymin, ymax])
# Create zoomed-in inset axes
axins = zoomed_inset_axes(ax, zoom=7, loc='lower right', bbox_to_anchor=(0.6,0.05,.3,.3), bbox_transform=ax.transAxes)
axins.plot(actual)
axins.plot(pred)
axins.plot(approx)
# Set the limits for the zoomed-in region
axins.set_xlim(*zoom_xlim)
axins.set_ylim(*zoom_ylim)
# Mark the region of the inset in the main plot
mark_inset(ax, axins, loc1=1, loc2=2, fc="none", ec="0.5")
plt.savefig(save_fig_dir)
plt.show()
def plot_entropy_comparison2(pred, actual, approx, save_fig_dir):
# Set the limits for the zoomed-in region
zoom_xlim = (6000, 7000)
zoom_ylim = (2.22, 2.26)
fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(actual)
ax.plot(pred)
ax.plot(approx)
ax.legend(["von Neumann entropy", "Model predictions", "Approximate entropy"])
ax.set_ylim([ymin, ymax])
# Create zoomed-in inset axes
axins = zoomed_inset_axes(ax, zoom=7, loc='lower right', bbox_to_anchor=(0.6,0.1,.3,.3), bbox_transform=ax.transAxes)
axins.plot(actual)
axins.plot(pred)
axins.plot(approx)
# Set the limits for the zoomed-in region
axins.set_xlim(*zoom_xlim)
axins.set_ylim(*zoom_ylim)
# Mark the region of the inset in the main plot
mark_inset(ax, axins, loc1=1, loc2=2, fc="none", ec="0.5")
plt.savefig(save_fig_dir)
plt.show()
model = load_model(save_model_path+'/top_'+str(i)+'_times_'+str(j))
# plot loss and metric
# Load the model_history_retrain
with open(os.path.join(save_model_path, "model_history_retrain.json"), "r") as f:
model_history_retrain = json.load(f)
# fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, figsize=(20, 16))
fig1, ax1 = plt.subplots(figsize=(15, 5))
# fig2, ax2 = plt.subplots(figsize=(15, 12))
y_loss = model_history_retrain[str(i)+str(j)]['loss']
y_metrics = model_history_retrain[str(i)+str(j)]["mae"]
x = range(1,len(y_loss)+1)
ax1.plot(x, y_loss, '--', alpha=1.0, color=(1,0,0))
# ax2.plot(x, y_metrics, '--', alpha=1.0, color=(1,0,0))
ax1.set_title("Loss Function")
ax1.set_xlabel("Epochs")
ax1.set_ylabel("MSE")
ax1.set_xlim([1, len(y_loss)-retrain_patience])
xticks = list(range(50,len(y_loss)-retrain_patience,50))
xticks.append(len(y_loss)-retrain_patience)
ax1.set_xticks(xticks)
#ax1.set_xticks(range(50,len(y_loss)-retrain_patience,50))
ax1.set_yscale('log')
plt.savefig(os.path.join(save_fig_dir, 'Loss.jpg'))
# ax2.set_title("Metric")
# ax2.set_xlabel("Epochs")
# ax2.set_ylabel("MAE")
# ax2.set_xlim([1, len(y_loss)-retrain_patience])
# ax2.set_xticks(xticks)
# ax2.set_yscale('log')
# fig.tight_layout()
# plt.savefig(os.path.join(save_fig_dir, 'Ensem_Retrain.png'))
# plot test dataset
train_dataloader = DataLoader(train_data_path)
X_test = train_dataloader.X_test
y_test = train_dataloader.y_test
train_pred = compute_model_prediction(X_test, y_test, model)
plot_entropy_comparison(*train_pred, save_fig_dir+"/entropy_compare1.jpg")
# plot unseen dataset
df = pd.read_csv(test_data_path, encoding='utf-8')
df_shuffle = df.sample(frac=1., axis=0, random_state = 42)
X_test = df_shuffle.drop(['Correct Entropy', 'Approx Entropy'], axis = 1)
y_test = df_shuffle['Correct Entropy']
test_pred = compute_model_prediction(X_test, y_test, model)
plot_entropy_comparison(*test_pred, save_fig_dir+"/entropy_compare2.jpg")
# relative error
diff = train_pred[0]-train_pred[1]
train_error = (np.abs(diff)/train_pred[1])*100.
diff = test_pred[0]-test_pred[1]
test_error = (np.abs(diff)/test_pred[1])*100.
fig_error, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
ax1.plot(train_error, '.')
ax2.plot(test_error, '.')
ax1.set_title('Relative Errors (%) for Test Data')
ax2.set_title("Relative Errors (%) for Unseen Data")
plt.savefig(save_fig_dir+"/relative_error.jpg")
plt.show()
# dist plot
fig_dist, ax3 = plt.subplots(1,1,figsize=(10,5))
sns.distplot(train_error)
sns.distplot(test_error)
ax3.set_title('Density Plot of Relative Errors for Test Data')
ax3.set_xlabel('Relative Errors (%)')
ax3.set_ylabel('Density')
plt.savefig(save_fig_dir+"/relative_error_density.jpg")
def Ensembel_Tables_Generation(path, path_val, df_store_test_final, df_store_val, pred_df, pred_val_df, save_path):
df_store_test_final
dataloader = DataLoader(path)
dataloader_val = DataLoader(path_val)
X_full, y_full = dataloader_val.shuffle_dataset(path_val)
df_test_all = df_store_test_final[str(0)]
df_val_all = df_store_val[str(0)]
# for i in range(1, top_n):
# df_test_all = pd.concat([df_test_all, df_store_test_final[str(i)]], axis=1)
# df_val_all = pd.concat([df_val_all, df_store_val[str(i)]], axis=1)
# df_test_all_mean = df_test_all.mean(axis=1)
# df_compare = pd.concat([pred_df, df_test_all_mean, df_test_all], axis = 1)
df_compare = pd.concat([pred_df, df_test_all], axis = 1)
# Renaming the columns
old_column_names = df_compare.columns.tolist()
column_mapping = {old_column_names[0]: 'Correct Entropy', old_column_names[1]: 'Model Predictions'}
df_compare = df_compare.rename(columns=column_mapping)
df_rel_error = (abs(df_compare['Correct Entropy']-df_compare['Model Predictions'])/df_compare['Correct Entropy'])*100
df_compare.insert(2, 'Relative Errors (%) for Models', df_rel_error)
df_compare = df_compare.sort_values(by=['Correct Entropy']) # reorder the values
print(df_compare)
# df_val_all_mean = df_val_all.mean(axis=1)
# df_compare_val = pd.concat([pred_val_df, df_val_all_mean, df_val_all], axis = 1)
df_compare_val = pd.concat([pred_val_df, df_val_all], axis = 1)
# Renaming the columns
old_column_names = df_compare_val.columns.tolist()
column_mapping = {old_column_names[0]: 'Correct Entropy', old_column_names[1]: 'Model Predictions'}
df_compare_val = df_compare_val.rename(columns=column_mapping)
df_rel_error_val = (abs(df_compare_val['Correct Entropy']-df_compare_val['Model Predictions'])/df_compare_val['Correct Entropy'])*100
df_compare_val.insert(2, 'Relative Errors (%) for Models', df_rel_error_val)
df_compare_val = df_compare_val.sort_values(by=['Correct Entropy']) # reorder the values
print(df_compare_val)
fig_error, (ax5, ax6) = plt.subplots(1, 2, figsize=(10,5))
ax5.plot(np.arange(0, len(dataloader.X_test)), df_compare['Relative Errors (%) for Models'], '.')
ax5.set_title("Relative Errors (%) for Test Data")
ax6.plot(np.arange(0, len(X_full)), df_compare_val['Relative Errors (%) for Models'], '.')
ax6.set_title("Relative Errors (%) for Unseen Data")
fig_error.tight_layout()
plt.savefig(os.path.join(save_path, 'Ensemble_Table_Gen.png'))
return df_compare, df_compare_val
def Test_Set_Plot(path, df_compare, df_compare_val, save_path):
# The plot will automatically determine the lower and upper ylim based on the smallest and largest values of the Test and PredVal Sets.
# We need to input both df_compare and df_compare_val
df = pd.read_csv(path, encoding='utf-8')
X = df.drop(['Correct Entropy'], axis = 1)
y = df['Correct Entropy']
seed = 42
ratio=(0.8,0.1,0.1)
assert sum(ratio) == 1
X_train_full, X_test, y_train_full, y_test = train_test_split(X, y, test_size=ratio[2], random_state = seed)
X_train, X_val, y_train, y_val = train_test_split(X_train_full, y_train_full,
test_size=round(ratio[1]/(ratio[0]+ratio[1]), 16),
random_state=seed)
X_test = X_test.reset_index(drop=True)
df_compare_1 = pd.concat([df_compare, X_test], axis = 1)
df_compare_2 = df_compare_1.sort_values(by='Correct Entropy', ascending=True).reset_index(drop=True)
# Determine the ylim
ylim=(pd.concat([df_compare, df_compare_val], axis = 1)[['Correct Entropy','Correct Entropy']].min().min()*0.95, pd.concat([df_compare, df_compare_val], axis = 1)[['Correct Entropy','Correct Entropy']].max().max()*1.05)
# We expand slightly the ylim.
df_compare_2.plot(y=['Correct Entropy', 'Model Predictions', 'Approx Entropy'], use_index=True, figsize=(10, 10), ylim=ylim)
plt.legend(["von Neumann Entropy", "Model Predictions", "Approximate Entropy"])
plt.savefig(os.path.join(save_path, 'Test_Set_Plot.png'))
return df_compare_2, ylim
def Pred_Val_Plot(path, df_compare_val, ylim, save_path):
# The plot will have the same ylim as the Test_Set_Plot
df = pd.read_csv(path, encoding='utf-8')
df_shuffle = df.sample(frac=1., axis=0, random_state = 42).reset_index(drop=True)
X = df_shuffle.drop(['Correct Entropy'], axis = 1)
df_compare_1 = pd.concat([df_compare_val, X], axis = 1)
df_compare_2 = df_compare_1.sort_values(by='Correct Entropy', ascending=True).reset_index(drop=True)
df_compare_2.plot(y=['Correct Entropy', 'Model Predictions', 'Approx Entropy'], use_index=True, figsize=(10, 10), ylim=ylim)
plt.legend(["von Neumann Entropy", "Model Predictions", "Approximate Entropy"])
plt.savefig(os.path.join(save_path, 'Pred_Val_Plot.png'))
return df_compare_2
# In[ ]:
# Please put the directories of the datasets and the save paths below
train_data_path = ''
test_data_path = ''
save_hp_dir = ''
save_hp_proj = ''
save_model_path = ''
save_fig_dir = ''
# this is to assure the path name is correct
import os
assert(os.path.exists(train_data_path))
assert(os.path.exists(test_data_path))
assert(os.path.exists(save_hp_dir))
assert(os.path.exists(save_model_path))
assert(os.path.exists(save_fig_dir))
# In[ ]:
# One could run the following line by line for each example considered in section 3 of arXiv:2305.00997
# The following initialize the KerasTuner with the specified hyperparameters range
tuner = train_with_tuner_ensemble_models(train_data_path, hypermodel_base, save_hp_dir, save_hp_proj)
# The following load the best configurations found by KerasTuner and retrain the models by also including the validation data
best_hps = load_best_hyperparam(hypermodel_base, save_hp_dir, save_hp_proj, top_n)
df_store_test_final, df_store_val, pred_df, pred_val_df, df_compare = train_with_tuner_ensemble_models_retrain(train_data_path, test_data_path, hypermodel_base, best_hps, retrain_max_epochs, save_model_path)
# The following generates the figures for the loss function, predictions, and the relative errors.
generate_figures(train_data_path, test_data_path, save_model_path, save_fig_dir, 2, 10)
# ### The following provides the source code for reproducing results in section 4 of arXiv: 2305.00997 of using treating the Renyi entropies as sequential deep learning. Again based on TensorFlow-Keras.
# In[74]:
from tensorflow.python import metrics
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# import scienceplots
import tensorflow as tf
import re
import os
import json
from sklearn.model_selection import train_test_split
from tensorflow import keras
from tensorflow.keras import layers
import keras_tuner as kt
from keras.models import load_model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras import regularizers
get_ipython().run_line_magic('matplotlib', 'inline')
import warnings
warnings.filterwarnings('ignore')
# plt.style.reload_library()
# plt.style.use(['science','no-latex'])
plt.rcParams['figure.dpi'] = 500
"Hyperparameters"
# Please adjust the hyperparameters and the parameters in hyper_RNN_model below.
# The following are hyperparameters for the datasets
MIN = 5 # the length of each vector
k = 1000 # how many datasets we want to use out of the full 10000 sets
ratio_original = (0.6, 0.2, 0.2)
ratio = (0.8, 0.0, 0.2)
# the following are hyperparameters for the KerasTuner (Due to small learning rate, we should increase search_epochs)
max_trials = 300
executions_per_trial = 2 # The final output will be the average of this.
patience = 8
search_epochs = 500
# the following are hyperparameters for finding the best epoch
best_epoch_patience = 15 # We use a large patience value
best_epoch_training_epochs = 300
best_epoch_batch_size = 2048
# We train the best model training_times, and select the best_N out of the training_times.
Best_training_epochs = 1500
retrain_patience = 10
training_times = 30
best_N = 7
# the following are hyperparameters for models
batch_size = 2048
def hyper_RNN_model(hp):
'''We should only consider stacking RNN layers if there are bottlencks in the performance.
If we want to stack layers, use hp.Boolean in the block of each layer.'''
# note return_sequences = True only when stacking multiple RNNs, the final layer cannot have it.
units = hp.Int(name="units", min_value=64, max_value=256, step=16)
units2 = hp.Int(name="units", min_value=32, max_value=128, step=8)
#units3 = hp.Int(name="units", min_value=8, max_value=32, step=8)
DenseUnits = hp.Int(name="units", min_value=16, max_value=32, step=8)
activation = hp.Fixed("activation", "relu")
#learning_rate = hp.Fixed("learning_rate", 5e-5)
learning_rate = hp.Float("learning_rate", min_value=1e-5, max_value=1e-4, sampling="log")
dropout_rate = hp.Float("dropout_rate", min_value=0.2, max_value=0.5, sampling="log")
recurrent_dropout = hp.Float(name="recurrent_dropout", min_value=0.1, max_value=0.3, sampling="log")
#initializer = tf.keras.initializers.GlorotUniform(seed=42) # GlorotNormal or GlorotUniform, we add a seed
model = keras.Sequential()
#model.add(Masking(mask_value=0.0, input_shape=(None, 1)))
#layers = hp.Choice(name="layers", values=["One-RNN", "Two-RNN"])
#recurrent_dropout = recurrent_dropout,
# if layers == "One-RNN":
# model.add(SimpleRNN(units, activation = activation, input_shape=(None, 1)))
# else:
# model.add(SimpleRNN(units, return_sequences = True,
# activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
# model.add(SimpleRNN(units2, activation = activation, input_shape=(None, 1)))
layers = hp.Choice(name="layers", values=["One-RNN with Dropout", "One-RNN without Dropout", "Two-RNN with Dropout", "Two-RNN without Dropout"])
if layers == "One-RNN with Dropout":
model.add(SimpleRNN(units, activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
if hp.Boolean("LayerNormalization"):
model.add(LayerNormalization())
elif layers == "One-RNN without Dropout":
model.add(SimpleRNN(units, activation = activation, input_shape=(None, 1)))
if hp.Boolean("LayerNormalization"):
model.add(LayerNormalization())
elif layers == "Two-RNN with Dropout":
model.add(SimpleRNN(units, return_sequences = True,
activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
if hp.Boolean("LayerNormalization"):
model.add(LayerNormalization())
model.add(SimpleRNN(units2, activation = activation, input_shape=(None, 1)))
else:
model.add(SimpleRNN(units, return_sequences = True,
activation = activation, input_shape=(None, 1)))
if hp.Boolean("LayerNormalization"):
model.add(LayerNormalization())
model.add(SimpleRNN(units2, activation = activation, input_shape=(None, 1)))
# layers = hp.Choice(name="layers", values=["Two-RNN with Dropout", "Two-RNN without Dropout", "Three-RNN with Dropout", "Three-RNN without Dropout"])
# if layers == "Two-RNN with Dropout":
# model.add(SimpleRNN(units, return_sequences = True,
# activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
# model.add(SimpleRNN(units2, activation = activation, input_shape=(None, 1)))
# elif layers == "Two-RNN without Dropout":
# model.add(SimpleRNN(units, return_sequences = True,
# activation = activation, input_shape=(None, 1)))
# model.add(SimpleRNN(units2, activation = activation, input_shape=(None, 1)))
# elif layers == "Three-RNN with Dropout":
# model.add(SimpleRNN(units, return_sequences = True,
# activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
# model.add(SimpleRNN(units2, return_sequences = True,
# activation = activation, recurrent_dropout = recurrent_dropout, input_shape=(None, 1)))
# model.add(SimpleRNN(units3, activation = activation, input_shape=(None, 1)))
# else:
# model.add(SimpleRNN(units, return_sequences = True,
# activation = activation, input_shape=(None, 1)))
# model.add(SimpleRNN(units2, return_sequences = True,
# activation = activation, input_shape=(None, 1)))
# model.add(SimpleRNN(units3, activation = activation, input_shape=(None, 1)))
if hp.Boolean("Dense"):
model.add(Dense(DenseUnits))
if hp.Boolean("dropout"):
model.add(Dropout(rate=dropout_rate))
model.add(Dense(1))
optimizer = tf.keras.optimizers.Adam(
learning_rate=learning_rate,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
amsgrad=hp.Boolean("amsgrad"))
model.compile(optimizer=optimizer, loss="mse",
metrics=["mae"])
return model
class DataLoader_Sequence(object):
def __init__(self, path):
df_shuffle = self.load_dataset_sequence(path)
def load_dataset_sequence(self, path):
seed = 42
df = pd.read_csv(path, encoding='utf-8').drop(['Correct Entropy','Approx Entropy'], axis = 1)
df_shuffle = df.sample(frac=1., axis=0, random_state = 42).reset_index(drop=True)
return df_shuffle
def split_dataset_sequence_CNN(self, df_shuffle, MIN, k, ratio): # no zero padding
MIN = MIN # the crucial difference with RNN, we only take the past MIN steps, this will also be the legth of vector
k = k # how many datasets we want to use
ratio = ratio # the ratio of train-val-test split, the split is in "timesteps"
full_data_transposed = df_shuffle.T
num_train_samples = int(ratio[0] * len(full_data_transposed))
num_val_samples = int(ratio[1] * len(full_data_transposed))
num_test_samples = len(full_data_transposed) - num_val_samples - num_train_samples
X_train_store = {}
y_train_store = {}
for j in range(1, k+1):
train_data = full_data_transposed.iloc[range(0, num_train_samples), range(j-1, j)]
X_train = np.zeros((num_train_samples-MIN, MIN, 1)) # length is MIN
y_train = np.zeros((num_train_samples-MIN, 1))
for i in range(0, num_train_samples-MIN):
X_train[i, -(MIN):, :] = train_data[i:i+MIN] # the second argument means we take the last (i+MIN) values
y_train[i, :] = train_data[i+MIN:i+MIN+1]
X_train_store["group" + str(j)] = X_train
y_train_store["group" + str(j)] = y_train
X_train_full = X_train_store['group' + str(1)]
y_train_full = y_train_store['group' + str(1)]
for j in range(2, k+1):
X_train_full = np.append(X_train_full, X_train_store['group' + str(j)], axis=0)
y_train_full = np.append(y_train_full, y_train_store['group' + str(j)], axis=0)
X_val_store = {}
y_val_store = {}
for j in range(1, k+1):
val_data = full_data_transposed.iloc[range(num_train_samples, num_train_samples+num_val_samples), range(j-1, j)]
X_val = np.zeros((num_val_samples-MIN, MIN, 1))
y_val = np.zeros((num_val_samples-MIN, 1))
for i in range(0, num_val_samples-MIN):
X_val[i, -(MIN):, :] = val_data[i:i+MIN]
y_val[i, :] = val_data[i+MIN:i+MIN+1]
X_val_store["group" + str(j)] = X_val
y_val_store["group" + str(j)] = y_val
X_val_full = X_val_store['group' + str(1)]
y_val_full = y_val_store['group' + str(1)]
for j in range(2, k+1):
X_val_full = np.append(X_val_full, X_val_store['group' + str(j)], axis=0)
y_val_full = np.append(y_val_full, y_val_store['group' + str(j)], axis=0)
X_test_store = {}
y_test_store = {}
for j in range(1, k+1):
test_data = full_data_transposed.iloc[range(num_train_samples + num_val_samples, len(full_data_transposed)), range(j-1, j)]
X_test = np.zeros((num_test_samples-MIN, MIN, 1))
y_test = np.zeros((num_test_samples-MIN, 1))
for i in range(0, num_test_samples-MIN):
X_test[i, -(MIN):, :] = test_data[i:i+MIN]
y_test[i, :] = test_data[i+MIN:i+MIN+1]
X_test_store["group" + str(j)] = X_test
y_test_store["group" + str(j)] = y_test
X_test_full = X_test_store['group' + str(1)]
y_test_full = y_test_store['group' + str(1)]
for j in range(2, k+1):
X_test_full = np.append(X_test_full, X_test_store['group' + str(j)], axis=0)
y_test_full = np.append(y_test_full, y_test_store['group' + str(j)], axis=0)
return full_data_transposed, X_train_full, y_train_full, X_val_full, y_val_full, X_test_full, y_test_full
def split_dataset_sequence_CNN_retrain(self, df_shuffle, MIN, k, ratio): # no zero padding
MIN = MIN # the crucial difference with RNN, we only take the past MIN steps, this will also be the legth of vector
k = k # how many datasets we want to use
ratio = ratio # the ratio of train-val-test split, the split is in "timesteps"
full_data_transposed = df_shuffle.T
num_train_samples = int(ratio[0] * len(full_data_transposed))
num_val_samples = int(ratio[1] * len(full_data_transposed))
num_test_samples = len(full_data_transposed) - num_val_samples - num_train_samples
X_train_store = {}
y_train_store = {}
for j in range(1, k+1):
train_data = full_data_transposed.iloc[range(0, num_train_samples), range(j-1, j)]
X_train = np.zeros((num_train_samples-MIN, MIN, 1)) # length is MIN
y_train = np.zeros((num_train_samples-MIN, 1))
for i in range(0, num_train_samples-MIN):
X_train[i, -(MIN):, :] = train_data[i:i+MIN] # the second argument means we take the last (i+MIN) values
y_train[i, :] = train_data[i+MIN:i+MIN+1]
X_train_store["group" + str(j)] = X_train
y_train_store["group" + str(j)] = y_train
X_train_full = X_train_store['group' + str(1)]
y_train_full = y_train_store['group' + str(1)]
for j in range(2, k+1):
X_train_full = np.append(X_train_full, X_train_store['group' + str(j)], axis=0)
y_train_full = np.append(y_train_full, y_train_store['group' + str(j)], axis=0)
X_test_store = {}
y_test_store = {}
for j in range(1, k+1):
test_data = full_data_transposed.iloc[range(num_train_samples + num_val_samples, len(full_data_transposed)), range(j-1, j)]
X_test = np.zeros((num_test_samples-MIN, MIN, 1))
y_test = np.zeros((num_test_samples-MIN, 1))
for i in range(0, num_test_samples-MIN):
X_test[i, -(MIN):, :] = test_data[i:i+MIN]
y_test[i, :] = test_data[i+MIN:i+MIN+1]
X_test_store["group" + str(j)] = X_test
y_test_store["group" + str(j)] = y_test
X_test_full = X_test_store['group' + str(1)]
y_test_full = y_test_store['group' + str(1)]
for j in range(2, k+1):
X_test_full = np.append(X_test_full, X_test_store['group' + str(j)], axis=0)
y_test_full = np.append(y_test_full, y_test_store['group' + str(j)], axis=0)
return full_data_transposed, X_train_full, y_train_full, X_test_full, y_test_full
def train_with_tuner_sequence_RNN_findepoch(path, hypermodel, save_path, model_name):
dataloader = DataLoader_Sequence(path)
df_shuffle = dataloader.load_dataset_sequence(path)
full_data_transposed, X_train, y_train, X_val, y_val, X_test, y_test = dataloader.split_dataset_sequence_CNN(df_shuffle, MIN, k, ratio_original)
# note that the num_test_samples-MIN cannot be zero or below
tuner = kt.BayesianOptimization(hypermodel,
objective="val_loss",
max_trials=max_trials,
executions_per_trial=executions_per_trial,
directory=save_path,
overwrite=True,
)
callbacks = [keras.callbacks.EarlyStopping(monitor="val_loss", patience=patience),
keras.callbacks.ModelCheckpoint(model_name, save_best_only=True)]
tuner.search(x = X_train, y = y_train,
batch_size=batch_size, epochs=search_epochs,
validation_data=(X_val, y_val),
callbacks=callbacks, verbose=1,)
tuner.results_summary()
# Now we find the best epoch of the model by moitoring val_loss with EarlyStopping
best_hps = tuner.get_best_hyperparameters(max_trials) # we pick the best set of hyperparameters