-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1588 lines (1181 loc) · 50.8 KB
/
utils.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
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from astropy.table import Table
from astropy.io import fits
from scipy.interpolate import splrep, splev
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.model_selection import train_test_split
import itertools
import keras
from keras import optimizers, initializers
from keras.models import Sequential, Model
from keras.layers import SimpleRNN, GRU, LSTM, \
Dense, Bidirectional, Dropout, \
Flatten, BatchNormalization, \
Input, concatenate, Add
from keras.callbacks import EarlyStopping
from keras.metrics import BinaryAccuracy
import pickle
import pyhopper
import multiprocessing as mp
import sncosmo as snc
import scipy.integrate as integrate
from scipy import optimize
import emcee
import corner
from numba import njit
from IPython.display import display, Math
seed = 42
keras.utils.set_random_seed(seed)
c = 299_792.458 # km/s
color_plot = {'u': 'purple', 'g': 'green', 'r': 'red',
'i': (150/255, 0, 0), 'z': (60/255, 0, 0)}
def fitter_Bspline(curve, t_ev, order=5, w_power=1, normalize=True):
"""
Function that interpolate data using B-splines and then
evaluates it at a specific time
Input
=====
curve: pd.dataFrame
light curve data Frame
t_ev: np.array
time at which the B-spline is evaluated
order: int (optional, default=5)
order of the spline (only values between 1 to 5)
w_power: int (optional, default=1)
power of the weight applicated to the incerteinty related to the fluxes
"""
time = curve.days
flux = curve.FLUXCAL
fluxerr = curve.FLUXCALERR
spl = splrep(time, flux, w=1/(fluxerr ** w_power), k=order)
flux_fit = splev(t_ev, spl)
if np.isnan(flux_fit).any():
flux_fit = np.zeros(t_ev.shape)
if normalize:
flux_fit /= np.max(np.abs(flux_fit))
return flux_fit
class SN_data:
"""
Class for handling supernova data from FITS files. This class provides
methods to read, summarize, preprocess, and plot light curves data.
Attributes
==========
phot_file: str
path to the photometry file
head_file: str
path to the head file
lc_df: pd.DataFrame
light curve data frame
obs_info: pd.DataFrame
observation information data frame
bands: list
list of bands used in the light curves
lc_fitted: pd.DataFrame
fitted light curve data frame
obs_discarded: list
list of observations discarded in the preprocessing
len_seq: int
number of points in the interpolation process
Methods
=======
reader(fits_header=False, band_col='BAND')
Function that reads fits files and return a light-curves
data frame
obs_summary()
Function that reads the head file containing supernova
data and sumarizes the SNTYPE column
mjd_to_days()
Function that transforms MJD dates to days considering
initial observation as day 0
peakmjd_to_days()
Function that transforms MJD dates to days, where day 0 corresponds to
the moment of the peak. Head file with peak information should be given
as attribute
preprocess(min_obs=5, w_power=1, len_seq=100, z_host=True, normalize=True)
Function that interpolates light curves, discarding curves that contain
less than a certain amount of observation.
plotter(obs, days=True, fitted=False)
Function that plots supernova light curve
"""
def __init__(self, phot_file, head_file=None):
self.phot_file = phot_file
self.head_file = head_file
def reader(self, fits_header=False, band_col='BAND'):
"""
Function that reads fits files and return a light-curves
data frame
Input
=====
fits_header: bool
if it is True, the header will be printed
band_col: str (optional)
name of the column related to the filter used for observation
"""
if fits_header:
header = fits.getheader(self.phot_file)
print(repr(header))
light_curves = Table.read(self.phot_file, format='fits').to_pandas()
index_obs_separator = light_curves[light_curves['MJD'] == -777].index
obs = np.cumsum(light_curves['MJD'] == -777)
light_curves.insert(0, 'obs', obs)
light_curves.drop(index_obs_separator, inplace=True)
light_curves.set_index('obs', inplace=True)
light_curves['BAND'] = (light_curves[band_col]
.str.decode('utf-8')
.str.strip()
)
light_curves.name = self.phot_file.split('/')[-1]
self.lc_df = light_curves
self.bands = light_curves.BAND.unique()
def obs_summary(self):
"""
Function that reads the head file containing supernova
data and sumarizes the SNTYPE column
"""
if np.equal(self.head_file, None):
print("This function only works if a Head file is provided")
return None
obs_info = Table.read(self.head_file, format='fits').to_pandas()
obs_info['obs'] = obs_info.index
obs_info.set_index('obs', inplace=True)
type_map = {101: 'Ia',
20: 'II+IIP', 120: 'II+IIP',
21: 'IIn+IIN', 121: 'IIn+IIN',
22: 'IIL', 122: 'IIL',
32: 'Ib', 132: 'Ib',
33: 'Ic+Ibc', 133: 'Ic+Ibc'}
obs_info['SNTYPE'] = obs_info['SNTYPE'].replace(type_map)
self.obs_info = obs_info
self.lc_df = pd.merge(self.lc_df, obs_info, on='obs')
def mjd_to_days(self):
"""
Function that transforms MJD dates to days considering
initial observation as day 0
"""
min_MJD = self.lc_df.groupby('obs').MJD.transform('min')
days = self.lc_df.MJD - min_MJD
self.lc_df['days'] = days
def peakmjd_to_days(self):
"""
Function that transforms MJD dates to days, where day 0 corresponds to
the moment of the peak. Head file with peak information should be given
as attribute
"""
if np.equal(self.head_file, None):
print("This function only works if a Head file is provided")
return None
try:
self.obs_info
except:
self.obs_summary()
days = self.lc_df.MJD - self.lc_df.PEAKMJD
self.lc_df['days'] = days
def preprocess(self, min_obs=5, w_power=1, len_seq=100, z_host=True,
normalize=True):
"""
Function that interpolates light curves, discarding curves that contain
less than a certain amount of observation.
Input
=====
min_obs: int (default=5)
quantity of minimum observation for discarding light curve bands
w_power: int (default=1)
power weights to inverse error value, i.e., w=1/yerr^w
(lower error implies a greater weight)
len_seq: int (default=100)
number of points in interpolation process
z_host: bool (default: True)
if it is True the Host redshift data will be added as a new column
"""
if not np.equal(self.head_file, None):
self.obs_summary()
self.peakmjd_to_days()
else:
self.mjd_to_days()
curves_group = self.lc_df.groupby('obs')
dict_curves_fitted = {}
zero_array = np.zeros(len_seq)
obs_discarded = []
for obs, curve in curves_group:
day_min = np.nanmax([curve[curve.BAND == band].days.min()
for band in self.bands])
day_max = np.nanmin([curve[curve.BAND == band].days.max()
for band in self.bands])
t_ev = np.linspace(day_min, day_max, len_seq)
dict_curve_fitted = {"days": t_ev}
if ('SIM_REDSHIFT_HOST' in curve.columns) and z_host:
z_host_obs = curve.SIM_REDSHIFT_HOST.unique()[0]
dict_curve_fitted['z_host'] = np.repeat(z_host_obs,
len_seq)
if not np.equal(self.head_file, None):
sn_type = curve.SNTYPE.unique()[0]
hot_encoder = (1 if sn_type == 'Ia' else 0)
dict_curve_fitted['sn_type'] = hot_encoder
for band in self.bands:
band_data = curve[curve.BAND == band]
if band_data.empty or (band_data.shape[0] <= min_obs):
flux_fitted = zero_array
else:
flux_fitted = fitter_Bspline(band_data, t_ev,
order=min_obs,
w_power=w_power,
normalize=normalize)
if pd.isna(flux_fitted).any():
flux_fitted = zero_array
dict_curve_fitted[band] = flux_fitted
if not np.all([np.equal(dict_curve_fitted[band], zero_array)
for band in self.bands]):
dict_curves_fitted[obs] = dict_curve_fitted
else:
obs_discarded.append(obs)
curves_fitted = pd.DataFrame.from_dict(dict_curves_fitted,
orient='index')
self.lc_fitted = curves_fitted
self.obs_discarded = obs_discarded
self.len_seq = len_seq
def plotter(self, obs, days=True, fitted=False, ls='--'):
"""
Function that plots supernova light curve
Input
=====
obs: int
observation number
days (optional): bool
if it's True, x label will be expressed as days
if it's False, x label will be expressed as MJD
"""
if days:
try:
self.lc_df.days
except:
if not np.equal(self.head_file, None):
self.peakmjd_to_days()
else:
self.mjd_to_days()
if fitted:
try:
self.lc_fitted
except:
self.preprocess()
data_obs = self.lc_fitted[self.lc_fitted.index == obs]
if data_obs.empty:
if obs in self.obs_discarded:
print(f"Obs: {obs} was discarded because was not possible "
"to fit it")
else:
print(f"Obs: {obs} was not found, try with another one")
return None
fig, ax = plt.subplots(figsize=(14, 8))
data_obs = self.lc_fitted[self.lc_fitted.index == obs]
for band in self.bands:
ax.plot(*data_obs.days.values, *data_obs[band].values,
color=color_plot[band], label=band)
ax.set_xlabel('Days', fontsize=18)
else:
data_obs = self.lc_df[self.lc_df.index == obs]
if data_obs.empty:
print(f"Obs: {obs} was not found, try with another one")
return None
fig, ax = plt.subplots(figsize=(14, 8))
for band in np.unique(data_obs['BAND']):
data_to_plot = data_obs[data_obs['BAND'] == band]
xaxis_plot = data_to_plot.days if days else data_to_plot.MJD
xlabel = 'Days' if days else 'MJD'
ax.errorbar(xaxis_plot, data_to_plot.FLUXCAL,
yerr=data_to_plot.FLUXCALERR, marker='o',
ls=ls, capsize=2, color=color_plot[band],
label=band)
ax.set_xlabel(xlabel, fontsize=18)
ax.set_ylabel('Flux (ADU)', fontsize=18)
ax.grid(ls=':', alpha=0.3)
ax.legend()
return fig, ax
class NN_classifier:
"""
Class for handling Neural Network classifier for supernova data. This class
provides methods to preprocess, split data, train, evaluate, and plot the
classifier performance.
Attributes
==========
sn_classes: list
list of SN_data classes
name: str
name of the classifier
data: pd.DataFrame
data frame with all the light curves
X_train, X_val, X_test: pd.DataFrame
data frame with the features for training, validation and test data
y_train, y_val, y_test: pd.DataFrame
data frame with the labels for training, validation and test data
X_train_nn, X_val_nn, X_test_nn: np.array
numpy array with the features for training, validation and test data
with the shape (n_obs, n_seq, n_features)
y_train_nn, y_val_nn, y_test_nn: np.array
numpy array with the labels for training, validation and test data
with the shape (n_obs, 1)
model: keras.Model
Neural Network model
fit_hist: list
list with the history of the training process
train_stats, val_stats, test_stats: list
list with the mean and standard deviation of the predictions
train_preds, val_preds, test_preds: np.array
numpy array with the predictions for training, validation and test data
Methods
=======
data_sample(frac, seed=42)
Function that samples the data
train_test_split(train_size=0.7, val_size=0.15, rand_state=42)
Function that splits the data into training, validation and test data
NN_reshape(data_ext=None)
Function that reshape the data in a way that the Neural Network can
work with those
model_nl_creator(n=None, rnns_i=[1, 1, 1], neurons=[8, 8, 8],
activations_i=[1, 1, 1], init_weights_i=[0, 0, 0],
dropout=0.2, optimizer=optimizers.Adam, lr=1e-3,
plot_model=False)
Function that creates a Neural Network model with the given
hyperparameters using the Functional API of Keras
model_fit(epochs=200, batch_size=8, plot=True, verbose=1, patience=15)
Function that fits the Neural Network model
best_hyp_pyhopper(search_params, model_creator, time=None, steps=None,
patience=15, plot_loss=False, plot_bf=True, verbose=0,
epochs=250, nwrap=5, pruner=0.75, n_jobs=1, save=False,
load=False)
Function that uses Pyhopper to find the best hyperparameters for the
Neural Network model
model_statistics(num_it=10, batch_size=8, epochs=250, verbose_fit=0,
patience=15, load=False)
Function that evaluates the Neural Network model in a certain number
of iterations and returns the mean and standard deviation of the
predictions
training_loss_plot()
Function that plots the training history of the Neural Network model
plot_roc_curve()
Function that plots the ROC curve for train, validation and test data
plot_confusion_matrix(normalize=False)
Function that plots the Confusion Matrix for train, validation and
test data
"""
def __init__(self, sn_classes, name=None):
data = pd.concat([sn_class.lc_fitted for sn_class in sn_classes])
data = pd.concat([data, pd.DataFrame(columns=['g', 'r', 'i', 'z'])])
data['obs'] = data.index
data.reset_index(inplace=True, drop=True)
self.data = data
self.name = name
def data_sample(self, frac, seed=42):
self.data = self.data.sample(frac=frac, random_state=seed)
def train_test_split(self, train_size=0.7, val_size=0.15, rand_state=42):
data_wo_types = self.data.drop(columns=['sn_type', 'obs'])
if data_wo_types.isna().any().any():
len_seq = self.data.days[0].shape[0]
array = np.zeros(len_seq)
data_wo_types = data_wo_types.map(lambda x: array
if np.array(pd.isnull(x)).any()
else x)
train_test = train_test_split(data_wo_types,
self.data.sn_type,
train_size=train_size,
random_state=rand_state)
X_train, X_test, y_train, y_test = train_test
test_size = 1 - train_size - val_size
test_size = test_size / (test_size + val_size)
val_test = train_test_split(X_test, y_test,
test_size=test_size,
random_state=rand_state)
X_val, X_test, y_val, y_test = val_test
self.X_train, self.y_train = X_train, y_train
self.X_val, self.y_val = X_val, y_val
self.X_test, self.y_test = X_test, y_test
self.X_train, self.X_test = X_train, X_test
self.y_train, self.y_test = y_train, y_test
def NN_reshape(self, data_ext=None):
"""
Function that reshape the data in a way that the Neural Network can
work with those
data_ext: optional (default: None)
external data to be reshaped
"""
def func(data):
shape = np.array(data.shape)
if shape.size == 1:
return data.values.reshape((-1, 1))
else:
n_obs, n_features = shape
n_seq = data.values[0, 0].shape[0]
data_RNN = data.to_numpy().tolist()
return np.reshape(data_RNN, (n_obs, n_seq, n_features))
if np.all(np.equal(data_ext, None)):
self.X_train_nn, self.y_train_nn = (func(self.X_train),
func(self.y_train))
self.X_val_nn, self.y_val_nn = func(self.X_val), func(self.y_val)
self.X_test_nn, self.y_test_nn = (func(self.X_test),
func(self.y_test))
else:
return func(data_ext)
def model_nl_creator(self, n=None, rnns_i=[1, 1, 1], neurons=[8, 8, 8],
activations_i=[1, 1, 1],
init_weights_i=[0, 0, 0],
dropout=0.2,
optimizer=optimizers.Adam, lr=1e-3,
plot_model=False):
"""
Function that creates a Neural Network model with the given
hyperparameters using the Functional API of Keras
Input
=====
n: int (optional, default=None)
number of layers of the Neural Network
rnns_i: list (optional, default=[1, 1, 1])
list with the index of the RNNs to be used in the model.
0: SimpleRNN, 1: LSTM, 2: GRU
neurons: list (optional, default=[8, 8, 8])
list with the number of neurons for each layer
activations_i: list (optional, default=[1, 1, 1])
list with the index of the activation functions to be used in
the model.
0: linear, 1: tanh, 2: relu, 3: sigmoid, 4: softmax
init_weights_i: list (optional, default=[0, 0, 0])
list with the index of the initializers to be used in the model.
0: he_uniform, 1: RandomUniform, 2: GlorotUniform
dropout: float (optional, default=0.2)
dropout rate
optimizer: keras.optimizers (optional, default=optimizers.Adam)
optimizer to be used in the model
lr: float (optional, default=1e-3)
learning rate
plot_model: bool (optional, default=False)
if it is True, the model will be plotted
"""
n = len(rnns_i) if n is None else n
rnn_var = [SimpleRNN, LSTM, GRU]
activation_var = ['linear', 'tanh', 'relu', 'sigmoid', 'softmax']
init_weight_var = [initializers.he_uniform(seed=seed),
initializers.RandomUniform(seed=seed),
initializers.GlorotUniform(seed=seed)]
inputs = Input(shape=self.X_train_nn.shape[1:])
layers = inputs
for i in np.arange(n):
rnn = rnn_var[rnns_i[i]]
units = int(neurons[i])
activation = activation_var[activations_i[i]]
kernel_init = init_weight_var[init_weights_i[i]]
ret_seq = False if i + 1 == n else True
layers = rnn(units=units, activation=activation,
kernel_initializer=kernel_init,
return_sequences=ret_seq)(layers)
layers = BatchNormalization()(layers)
layers = Dropout(dropout)(layers)
layers = Flatten()(layers)
layers = Dense(self.y_train_nn.shape[1],
activation='sigmoid')(layers)
model = Model(inputs, layers, name=f'{n}_layer')
model.compile(optimizer=optimizer(learning_rate=lr),
loss='binary_crossentropy',
metrics=[BinaryAccuracy()])
self.model = model
self.fit_hist = []
if plot_model:
folder = f"data_folder/images/model_{self.name}.pdf"
keras.utils.plot_model(self.model, to_file=folder,
show_shapes=True)
return model
def model_fit(self, epochs=200, batch_size=8, plot=True,
verbose=1, patience=15):
"""
Function that fits the Neural Network model with the given
hyperparameters
Input
=====
epochs: int (optional, default=200)
number of epochs
batch_size: int (optional, default=8)
batch size
plot: bool (optional, default=True)
if it is True, the training history will be plotted
verbose: int (optional, default=1)
verbose level
patience: int (optional, default=15)
patience for the early stopping
"""
early_stopping = EarlyStopping(monitor='val_loss', patience=patience)
hist = self.model.fit(self.X_train_nn, self.y_train_nn,
validation_data=(self.X_val_nn, self.y_val_nn),
epochs=epochs, batch_size=batch_size,
callbacks=[early_stopping], verbose=verbose)
self.fit_hist.append(hist)
if plot:
self.training_loss_plot()
def best_hyp_pyhopper(self, model_creator, search_params=None,
time=None, steps=None, patience=15,
plot_loss=False, plot_bf=True, verbose=0,
epochs=250, nwrap=5, pruner=0.75,
n_jobs=1, save=False, load=True):
"""
Function that uses Pyhopper to find the best hyperparameters for the
Neural Network model
Input
=====
model_creator: function
function that creates the Neural Network model
search_params: pyhopper.Search (if load is False this parameter must be
provided)
search parameters for the Pyhopper
time: int (optional, default=None)
time in pyhopper format for the optimization
steps: int (optional, default=None)
number of steps for the optimization
patience: int (optional, default=15)
patience for the early stopping
plot_loss: bool (optional, default=False)
if it is True, the loss will be plotted
plot_bf: bool (optional, default=True)
if it is True, the best so far will be plotted
verbose: int (optional, default=0)
verbose level
epochs: int (optional, default=250)
number of epochs
nwrap: int (optional, default=5)
number of times the model will be wrapped
pruner: float (optional, default=0.75)
pruner for the Pyhopper
n_jobs: int (optional, default=1)
number of jobs for parallelization
save: bool (optional, default=False)
if it is True, the search parameters will be saved
load: bool (optional, default=True)
if it is True, the search parameters will be loaded
Output
=====
best_params: dict
best hyperparameters for the Neural Network model
batch_size: int
best batch size for the Neural Network model
"""
if not load and search_params is None:
print("If load is False, search_params must be provided")
return None
def model_to_pyhopper(param_grid):
model_creator(**{key: value for key, value in param_grid.items()
if key != 'batch_size'})
self.model_fit(plot=plot_loss, verbose=verbose,
epochs=epochs, batch_size=param_grid['batch_size'],
patience=patience)
return self.model.evaluate(self.X_val_nn, self.y_val_nn,
verbose=verbose)[1]
obj_func = pyhopper.wrap_n_times(model_to_pyhopper, n=nwrap)
pruner = pyhopper.pruners.QuantilePruner(pruner)
folder = f"./data_folder/checkpoints/classifier_{self.name}.ckpt"
if load:
search_params = pyhopper.Search()
search_params.load(folder)
best_params = search_params.best
else:
cktp_file = folder if save else None
best_params = search_params.run(obj_func, 'max',
steps=steps, runtime=time,
pruner=pruner, n_jobs=n_jobs,
checkpoint_path=cktp_file)
print(f"Best params: {best_params}")
if 'batch_size' in best_params:
batch_size = best_params['batch_size']
del best_params['batch_size']
if plot_bf:
fig, ax = plt.subplots(figsize=(8, 5))
steps = np.array(search_params.history.steps) + 1
fs = search_params.history.fs
print(f"Steps: {max(steps)} - Best fs: {max(fs):0.3}")
ax.scatter(x=steps, y=fs, label="Sampled")
ax.plot(steps, search_params.history.best_fs,
ls='--', color="red",
label="Best so far", zorder=0)
ax.grid(ls=':', alpha=0.4, zorder=0)
ax.set(xlim=[0.5, len(search_params.history) + 0.5],
xlabel='Step',
ylabel='Validation Accuracy')
ax.legend()
folder = ("data_folder/images/"
f"pyhopper_opt_classifier_{self.name}.svg")
fig.savefig(folder, transparent=True, bbox_inches='tight')
return best_params, batch_size
def model_statistics(self, num_it=10, batch_size=8, epochs=250,
verbose_fit=0, patience=15, load=False):
"""
Function that evaluates the Neural Network model in a certain number
of iterations and returns the mean and standard deviation of the
predictions
Input
=====
num_it: int (optional, default=10)
number of iterations
batch_size: int (optional, default=8)
batch size
epochs: int (optional, default=250)
number of epochs
verbose_fit: int (optional, default=0)
verbose level
patience: int (optional, default=15)
patience for the early stopping
load: bool (optional, default=False)
if it is True, the weights will be loaded
"""
train_preds = []
val_preds = []
test_preds = []
file = f"./data_folder/weights/classifier_weights_{self.name}.pkl"
if load:
file_weights = open(file, "rb")
weights, fit_hist = pickle.load(file_weights)
self.fit_hist = fit_hist
num_it = len(weights)
file_weights.close()
else:
initial_weights = self.model.get_weights()
weights = []
for i in range(num_it):
if i == 0:
print(f"{i}/{num_it}", end="\r")
if load:
self.model.set_weights(weights[i])
else:
self.model.set_weights(initial_weights)
self.model_fit(epochs=epochs, batch_size=batch_size,
plot=False, verbose=verbose_fit,
patience=patience)
weights.append(self.model.get_weights())
verbose_pred = 1 if i == num_it - 1 else 0
pred_train = self.model.predict(self.X_train_nn,
verbose=verbose_pred)
pred_val = self.model.predict(self.X_val_nn,
verbose=verbose_pred)
pred_test = self.model.predict(self.X_test_nn,
verbose=verbose_pred)
train_preds.append(pred_train)
val_preds.append(pred_val)
test_preds.append(pred_test)
print(f"{i + 1}/{num_it}", end="\r")
file_weights = open(file, "wb")
pickle.dump([weights, self.fit_hist], file_weights)
file_weights.close()
means_preds_train = np.mean(train_preds, axis=0)
stds_preds_train = np.std(train_preds, axis=0)
means_preds_val = np.mean(val_preds, axis=0)[0]
stds_preds_val = np.std(val_preds, axis=0)[0]
means_preds_test = np.mean(test_preds, axis=0)
stds_preds_test = np.std(test_preds, axis=0)
self.train_stats = [means_preds_train, stds_preds_train]
self.val_stats = [means_preds_val, stds_preds_val]
self.test_stats = [means_preds_test, stds_preds_test]
self.train_preds = np.array(train_preds)
self.val_preds = np.array(val_preds)
self.test_preds = np.array(test_preds)
def training_loss_plot(self):
"""
Function that plots the training history of the Neural Network model
"""
keys = self.fit_hist[0].history.keys()
ncols = len(keys) // 2
fig, ax = plt.subplots(nrows=1, ncols=ncols, sharey=True,
figsize=(10, 5))
for i, key in enumerate(keys):
values = [hist.history[key] for hist in self.fit_hist]
values = pd.DataFrame(values)
index = i // ncols
x = range(values.shape[1])
y = values.mean(axis=0)
yerr = values.std(axis=0, ddof=0)
ax[index].plot(x, y, marker='.', ls='-',
label=f"Mean\n{key[0:10]}")
ax[index].fill_between(x, y-yerr, y+yerr, alpha=0.25,
label=rf"$\pm 1 \sigma$")
if i % 2 == 1:
ax[index].set_xlabel('Epochs')
if i < 2:
ax[index].legend(ncol=1, loc='right')
ax[index].grid(ls=':', alpha=0.4, zorder=0)
if ncols > 1:
title = 'Validation set' if 'val' in key else 'Train set'
ax[index].set_title(title)
ax[0].set_ylim(-0, 1)
ax[0].set_ylabel('Accuracy / Loss')
fig.suptitle(f"Train History")
fig.subplots_adjust(wspace=0.05)
folder = f"data_folder/images/train_loss_classifier_{self.name}.svg"
fig.savefig(folder, transparent=True, bbox_inches='tight')
return fig, ax
def plot_roc_curve(self):
"""
Function that plots the ROC curve for train, validation
and test data
"""
X_data = [self.train_preds, self.val_preds, self.test_preds]
y_data = [self.y_train_nn, self.y_val_nn, self.y_test_nn]
data_label = ['Train data', 'Validation data', 'Test data']
fig, ax = plt.subplots(nrows=1, ncols=3, sharey=True,
figsize=(12, 4))
for i, (X, y) in enumerate(zip(X_data, y_data)):
roc_curves = [roc_curve(y_true=y, y_score=y_pred)
for y_pred in X]
fpr_interp = np.linspace(0, 1, 100)
tprs = []
aucs = []
for single_roc in roc_curves:
fpr, tpr, threshold = single_roc
aucs.append(auc(fpr, tpr))
tpr_interp = np.interp(fpr_interp, fpr, tpr)
tpr_interp[0] = 0
tprs.append(tpr_interp)
ax[i].plot([0, 1], [0, 1], 'r--')
ax[i].plot(fpr, tpr, 'b--', alpha=0.1)
mean_tpr = np.mean(tprs, axis=0)
std_tpr = np.std(tprs, axis=0, ddof=0)
ax[i].plot(fpr_interp, mean_tpr, 'b', label='Mean ROC')
ax[i].fill_between(x=fpr_interp,
y1=mean_tpr - std_tpr,
y2=mean_tpr + std_tpr,
color='grey', alpha=0.5,
label=r'$\pm 1 \sigma$',
zorder=0)
ax[i].set(xlabel='False Positive rate', title=data_label[i])
ax[i].grid(ls=':', alpha=0.3)
mean_auc = np.mean(aucs, axis=0)
std_auc = np.std(aucs, axis=0, ddof=0)