-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel.py
1136 lines (945 loc) · 32.6 KB
/
model.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
"""A module to manage the model."""
import os
import pickle
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from utils.custom_layers import flatten
from utils.metric_eval import plot_roc_curve, get_all_roc_coordinates, \
roc_auc_score, calculate_tpr_fpr
from sklearn.metrics import roc_curve, auc, precision_recall_curve
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.metrics import f1_score, recall_score, precision_score,\
accuracy_score, classification_report
from sklearn.preprocessing import label_binarize
class Model(object):
"""A class to manage the model."""
created = False
compiled = False
trained = False
predicted_train = False
predicted_val = False
predicted_test = False
def __init__(self,
train_ds,
val_ds,
test_ds,
commands):
"""
Initialize the class.
Parameters
----------
train_ds : tf.data.Dataset
The training dataset.
val_ds : tf.data.Dataset
The validation dataset.
test_ds : tf.data.Dataset
The test dataset.
commands : list
The list of commands.
"""
# Get the train, val and test datasets.
self.train_ds = train_ds
self.val_ds = val_ds
self.test_ds = test_ds
# Get the commands.
self.commands = commands
# Get the batch size.
self.batch_size = train_ds._input_dataset._batch_size.numpy()
# Get the shape of the input as the dimensions of the spectrogram.
print ("input shape:", train_ds.take(1))
for spectrogram,_ in train_ds.take(1).as_numpy_iterator():
self.input_shape = spectrogram.shape[1:]
# Get the number of classes.
self.num_classes = len(self.commands)
self.norm_layer = self._norm_layer()
def _norm_layer(self):
"""
Normalization layer.
Returns
-------
tf.keras.layers.Normalization
The normalization layer.
"""
# Create a normalization layer.
norm_layer = tf.keras.layers.Normalization(axis = None)
# Fit the state of the layer to the spectrograms with `Normalization.adapt`.
norm_layer.adapt(
data = self.train_ds.map(
map_func = lambda spec, label: spec
)
)
return norm_layer
def print_input_shape(self):
"""
Print the input shape.
"""
print('Input shape:', self.input_shape)
print('Output shape:', self.num_classes)
def create_model(self):
"""
Create the model.
"""
self.define_model()
self.created = True
def define_model(self):
"""
Parent method to define the model.
"""
pass
def summary(self):
"""
Print a summary of the model.
"""
print(self.model.summary())
def compile(self,
loss:str,
optimizer:str,
metrics:list):
"""
Compile the model.
Parameters
----------
loss : str
The loss function.
optimizer : str
The optimizer.
metrics : list
The metrics to use.
"""
if not self.created:
raise Exception('The model has not been created yet.')
# Set the attributes.
self.loss = loss
self.optimizer = optimizer
self.metrics = metrics
self.model.compile(
loss = self.loss,
optimizer = self.optimizer,
metrics = self.metrics
)
self.compiled = True
def fit(self,
epochs:int,
callbacks:list=None,
verbose:int = 1,
return_history:bool = False):
"""
Train the model.
Parameters
----------
epochs : int
The number of epochs.
callbacks : list
The callbacks to use.
Default is None.
verbose : int
The verbosity mode.
Default is 1.
return_history : bool
Whether to return the history.
Returns
-------
tf.keras.callbacks.History
The history of the training.
Raises
------
Exception
If the model has not been compiled yet.
"""
# Check if the model has been compiled.
if not self.compiled:
raise Exception('The model has not been compiled yet.')
self.history = self.model.fit(self.train_ds,
epochs = epochs,
callbacks = callbacks,
validation_data = self.val_ds,
verbose = verbose)
self.trained = True
if return_history:
return self.history
def save_fit(self,
path:str):
"""
Save the fit history.
Parameters
----------
path : str
The path to save the history.
"""
with open(path, 'wb') as file:
pickle.dump(self.history.history, file)
def load_fit(self,
path:str,
return_history:bool=False):
"""
Load the fit history.
Parameters
----------
path : str
The path to load the history.
"""
with open(path, 'rb') as file:
self.history = pickle.load(file)
if return_history:
return self.history
def _predict(self,
ds:tf.data.Dataset):
"""
Compute the predictions on a dataset.
Parameters
----------
ds : tf.data.Dataset
The dataset to predict.
"""
if not self.trained:
raise Exception('The model has not been trained yet.')
preds = self.model.predict(ds)
batch_size = self.batch_size
len_data = len(list(ds))*batch_size
for i, (spectrogram, label) in enumerate(ds.take(1)):
shape_x = spectrogram.shape
X = np.zeros(shape = flatten([len_data, list(shape_x[1:])]))
y_true = np.zeros(shape = (len_data), dtype = np.int32)
y_pred = np.zeros(shape = (len_data), dtype = np.int32)
y_prob = np.zeros(shape = (len_data, self.num_classes), dtype = np.float32)
last_batch_size = batch_size
for i, (spectrogram, label) in enumerate(ds):
start = i * batch_size
end = (i + 1)*batch_size
try:
X[start : end] = spectrogram.numpy()
y_true[start : end] = label.numpy()
y_prob[start : end] = self.model.predict(spectrogram)
y_pred[start : end] = np.argmax(y_prob[start : end], axis = 1)
except ValueError:
last_batch_size = label.numpy().shape[0]
X[start : start + last_batch_size] = spectrogram.numpy()
y_true[start : start + last_batch_size] = label.numpy()
y_prob[start : start + last_batch_size] = self.model.predict(spectrogram)
y_pred[start : start + last_batch_size] = np.argmax(y_prob[start : start + last_batch_size], axis = 1)
break
return X[:-(batch_size - last_batch_size)],\
y_true[:-(batch_size - last_batch_size)],\
y_pred[:-(batch_size - last_batch_size)],\
y_prob[:-(batch_size - last_batch_size)]
def predict_train(self):
"""
Predict the model on the train set.
"""
self.x_train, self.true_train, self.predictions_train, self.probabilities_train=self._predict(self.train_ds)
self.predicted_train = True
def predict_val(self):
"""
Predict the model on the validation set.
"""
self.x_val, self.true_val, self.predictions_val, self.probabilities_val=self._predict(self.val_ds)
self.predicted_val = True
def predict_test(self):
"""
Predict the model on the test set.
"""
self.x_test, self.true_test, self.predictions_test, self.probabilities_test=self._predict(self.test_ds)
self.predicted_test = True
def evaluate_train(self):
"""Evaluate the model on the train set."""
self.results_train=self.model.evaluate(self.train_ds)
print(self.results_train)
def evaluate_val(self):
"""Evaluate the model on the validation set."""
self.results_val=self.model.evaluate(self.val_ds)
print(self.results_val)
def evaluate_test(self):
"""Evaluate the model on the test set."""
#y_pred, y_true=self.predict_test()
#test_acc=sum(y_pred == y_true) / len(y_true)
#print(f'Test set accuracy: {test_acc:.0%}')
self.results_test=self.model.evaluate(self.test_ds)
def _accuracy(self,
y_true:np.ndarray,
y_pred:np.ndarray,
**kwargs):
"""
Compute the accuracy.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
**kwargs : dict
The arguments to pass to the accuracy object.
Returns
-------
accuracy : float
The accuracy.
"""
return accuracy_score(
y_true,
y_pred,
**kwargs
)
def _precision(self,
y_true:np.ndarray,
y_pred:np.ndarray,
average:str='macro',
**kwargs):
"""
Compute the precision.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
average : str
The averaging method.
**kwargs : dict
The arguments to pass to the precision object.
Returns
-------
precision : float
The precision.
"""
return precision_score(
y_true,
y_pred,
average=average,
**kwargs
)
def _recall(self,
y_true:np.ndarray,
y_pred:np.ndarray,
average:str='macro',
**kwargs):
"""
Compute the recall.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
average : str
The averaging method.
**kwargs : dict
The arguments to pass to the recall object.
Returns
-------
recall : float
The recall.
"""
return recall_score(
y_true,
y_pred,
average=average,
**kwargs
)
def _f1(self,
y_true:np.ndarray,
y_pred:np.ndarray,
average:str='macro',
**kwargs):
"""
Compute the F1 score.
Parameters
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
**kwargs : dict
The arguments to pass to the F1 score object.
Returns
-------
f1 : float
The F1 score.
"""
return f1_score(
y_true,
y_pred,
average=average,
**kwargs
)
def _auc(self,
y_true:np.ndarray,
y_pred:np.ndarray,
**kwargs):
"""
Compute the AUC.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
**kwargs : dict
The arguments to pass to the AUC object.
Returns
-------
auc : float
The AUC.
"""
return roc_auc_score(
y_true,
y_pred,
**kwargs
)
def _classification_report(self,
y_true:np.ndarray,
y_pred:np.ndarray,
target_names:list=None,
**kwargs):
"""
Compute the classification report.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
target_names : list
The names of the classes.
**kwargs : dict
The arguments to pass to the classification report object.
Returns
-------
classification_report : str
The classification report.
"""
return classification_report(
y_true,
y_pred,
target_names=target_names,
**kwargs
)
def _confusion_matrix(self,
y_true:np.ndarray,
y_pred:np.ndarray,
return_cm:bool=True,
display:bool=False,
save:bool=True,
dir:str=None,
name:str=None,
**kwargs) -> np.ndarray:
"""
Compute the confusion matrix.
Parameters
----------
y_true : np.ndarray
The true labels.
y_pred : np.ndarray
The predicted labels.
**kwargs : dict
The arguments to pass to the confusion matrix object.
Returns
-------
confusion_matrix : np.ndarray
The confusion matrix.
"""
cm=confusion_matrix(
y_true,
y_pred,
**kwargs
)
if display or save:
fig, ax = plt.subplots(figsize=(10, 10))
disp = ConfusionMatrixDisplay.from_predictions(y_true, y_pred, ax=ax)
plt.tight_layout()
if display:
plt.show()
if save:
if dir is None:
dir='figures'
if name is None:
name='confusion_matrix.png'
fig.savefig(
os.path.join(
dir,
name
)
)
if return_cm:
return cm
def _roc_curve(self,
y_pred_prob:np.ndarray,
y_true:np.ndarray,
return_roc:bool=True,
display:bool=True,
save:bool=True,
dir:str=None,
name:str=None,
**kwargs):
"""
Compute the ROC curve of the model.
Parameters
----------
y_pred_prob: np.array
Predicted label probabilities.
Default: None
y_true: np.array
True labels.
Default: None
return_roc: bool
Whether to return the ROC curve or not.
Default: True
display: bool
Whether to display the figure or not.
Default: True
save: bool
Whether to save the figure or not.
Default: True
dir: str
Directory to save the figure.
Default: None
name: str
Name of the figure.
Default: None
**kwargs:
Parameters for the ROC curve method.
"""
if not self.trained:
raise ValueError('Model not trained')
# Binarize the labels
y_binarized = label_binarize(y_true, classes=range(self.num_classes))
# Compute the ROC curve and AUC for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(self.num_classes):
fpr[i], tpr[i], _ = roc_curve(y_binarized[:, i], y_pred_prob[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and AUC
fpr_micro, tpr_micro, _ = roc_curve(y_binarized.ravel(), y_pred_prob.ravel())
roc_auc_micro = auc(fpr_micro, tpr_micro)
if display or save:
# Plot the ROC curves for each class
plt.figure(figsize=(10, 10))
for i in range(self.num_classes):
plt.plot(fpr[i], tpr[i], label='Class {0} (AUC = {1:.2f})'.format(i, roc_auc[i]))
plt.plot(fpr_micro, tpr_micro, label='Micro-average (AUC = {0:.2f})'.format(roc_auc_micro))
plt.plot([0, 1], [0, 1], 'k--') # Plot diagonal line
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - Multiclass Classification')
#plt.legend(loc='lower right')
if display:
plt.show()
if save:
if dir is None:
dir='figures'
if name is None:
name='roc_curve.png'
plt.savefig(
os.path.join(
dir,
name
)
)
if return_roc:
return fpr, tpr, roc_auc
def _pr_curve(self,
y_pred_prob:np.ndarray,
y_true:np.ndarray,
return_pr:bool=True,
display:bool=True,
save:bool=True,
dir:str=None,
name:str=None,
**kwargs):
"""
Compute the PR curve of the model.
Parameters
----------
y_pred_prob: np.array
Predicted label probabilities.
Default: None
y_true: np.array
True labels.
Default: None
return_pr: bool
Whether to return the PR curve or not.
Default: True
display: bool
Whether to display the figure or not.
Default: True
save: bool
Whether to save the figure or not.
Default: True
dir: str
Directory to save the figure.
Default: None
name: str
Name of the figure.
Default: None
**kwargs:
Parameters for the PR curve method.
Returns
-------
precision : np.ndarray
Precision values.
"""
if not self.trained:
raise ValueError('Model not trained')
# Binarize the labels
y_binarized = label_binarize(y_true, classes=range(self.num_classes))
# Compute the PR curve and AUC for each class
precision = dict()
recall = dict()
pr_auc = dict()
for i in range(self.num_classes):
precision[i], recall[i], _ = precision_recall_curve(y_binarized[:, i], y_pred_prob[:, i])
pr_auc[i] = auc(recall[i], precision[i])
# Compute micro-average PR curve and AUC
precision_micro, recall_micro, _ = precision_recall_curve(y_binarized.ravel(), y_pred_prob.ravel())
pr_auc_micro = auc(recall_micro, precision_micro)
if display or save:
fig, ax = plt.subplots(figsize=(10, 10))
for i in range(self.num_classes):
ax.plot(recall[i], precision[i], label='Class {0} (AUC = {1:.2f})'.format(i, pr_auc[i]))
ax.plot(recall_micro, precision_micro, label='Micro-average (AUC = {0:.2f})'.format(pr_auc_micro))
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.set_title('PR Curve - Multiclass Classification')
#ax.legend(loc='lower right')
if display:
plt.show()
if save:
if dir is None:
dir='figures'
if name is None:
name='pr_curve.png'
plt.savefig(
os.path.join(
dir,
name
)
)
if return_pr:
return precision, recall, pr_auc
def evaluate(self,
set:str='test',
method:str='roc',
model_name:str=None,
**kwargs):
"""
Evaluate the model, using the specified method,
on the specified set.
Parameters
----------
set : str
The set to evaluate on.
Possible values: 'train', 'val', 'test'.
Default: 'test'
method : str
The evaluation method.
Possible values: 'accuracy', 'precision', 'recall', 'f1', 'roc', 'pr', 'confusion_matrix'.
Default: 'roc'
**kwargs : dict
The arguments to pass to the evaluation method.
"""
assert set in [
'train',
'val',
'test'], 'Invalid set'
assert method in [
'accuracy',
'precision',
'recall',
'f1',
'roc',
'pr',
'confusion_matrix',
'classification_report'], 'Invalid method'
if not self.trained:
raise ValueError('Model not trained')
method_dict = {
'accuracy': self._accuracy,
'precision': self._precision,
'recall': self._recall,
'f1': self._f1,
'roc': self._roc_curve,
'pr': self._pr_curve,
'confusion_matrix': self._confusion_matrix,
'classification_report': self._classification_report
}
if set == 'train':
if not self.predicted_train:
self.predict_train()
x, y_true, y_pred, y_prob = self.x_train, self.true_train, self.predictions_train, self.probabilities_train
elif set == 'val':
if not self.predicted_val:
self.predict_val()
x, y_true, y_pred, y_prob = self.x_val, self.true_val, self.predictions_val, self.probabilities_val
else:
if not self.predicted_test:
self.predict_test()
x, y_true, y_pred, y_prob = self.x_test, self.true_test, self.predictions_test, self.probabilities_test
if method in ['accuracy', 'precision', 'recall', 'f1', 'confusion_matrix']:
return method_dict[method](y_true, y_pred, **kwargs)
elif method == 'classification_report':
return method_dict[method](y_true, y_pred, target_names=self.commands, **kwargs)
else:
return method_dict[method](y_prob, y_true, **kwargs)
def save_model(
self,
filepath: str,
overwrite:bool=True,
save_format:str=None,
**kwargs
):
"""
Save the model, weights and optimizer state.
Parameters
----------
filepath : str
The path to save the model.
overwrite : bool
Whether to overwrite existing models or not.
Default: True
save_format : str
The format to save the model.
Possible values: 'tf', 'h5'.
Default: None
**kwargs : dict
The arguments to pass to the save method.
"""
self.model.save(
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs
)
def save_weights(
self,
filepath:str,
overwrite:bool=True,
save_format:str=None,
options=None
):
"""
Save the weights of the model.
Parameters
----------
filepath : str
The path to save the weights.
overwrite : bool
Whether to overwrite existing weights or not.
Default: True
save_format : str
The format to save the weights.
Possible values: 'tf', 'h5'.
Default: None
options : tf.train.CheckpointOptions
The options to pass to the checkpoint.
Default: None
"""
self.model.save_weights(
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options
)
from utils.custom_layers import LowRankDense
def load(
self,
filepath:str,
custom_objects={'LowRankDense': LowRankDense},
compile:bool=True,
safe_mode:bool=True,
**kwargs
):
"""
Load the model.
Parameters
----------
path : str
The path to load the model.
"""
self.model=tf.keras.models.load_model(
filepath=filepath,
custom_objects=custom_objects,
compile=compile,
safe_mode=safe_mode,
**kwargs
)
def load_weights(
self,
filepath:str,
skip_mismatch:bool=False,
by_name:bool=False,
options=None
):
"""
Load the weights of the model.
Parameters
----------
filepath : str
The path to load the weights.
skip_mismatch : bool
Whether to skip loading of layers where there is a mismatch in the number of weights,
or a mismatch in the shape of the weight (only valid when by_name=True).
Default: False
by_name : bool
Whether to load weights by name or by topological order.
Default: False
options : tf.train.CheckpointOptions
The options to pass to the checkpoint.
Default: None
"""
self.trained =True
self.model.load_weights(
filepath=filepath,
skip_mismatch=skip_mismatch,
by_name=by_name,
options=options
)
def plot_model(self,
path:str,
**kwargs):
"""
Plot the model.
Parameters
----------
path : str
The path to save the model.
**kwargs : dict
The arguments to pass to the plot_model method.
"""
tf.keras.utils.plot_model(
model=self.model,
to_file=path,
#show_shapes=True,
#show_layer_names=True,
#expand_nested=True,
#dpi=96,
**kwargs)
def plot_training(self, path=None):
"""
Plot the training history.
Parameters
----------
path : str
The path to save the plot.
"""
fig, (ax1, ax2)=plt.subplots(2, 1, figsize=(10, 10))
# Plot accuracy
train_acc=self.history.history['accuracy']
val_acc=self.history.history['val_accuracy']
epochs=range(1, len(train_acc) + 1)
ax1.plot(epochs, train_acc, '-o', label='Training Accuracy')
ax1.plot(epochs, val_acc, '-o', label='Validation Accuracy')
ax1.set_title('Accuracy')
ax1.set_xlabel('Epochs')
ax1.set_ylabel('Accuracy')
ax1.legend()
y1=np.array(train_acc)
y2=np.array(val_acc)