-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scatter_Correction_CXR_CFE.py
1139 lines (846 loc) · 42.1 KB
/
Scatter_Correction_CXR_CFE.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
# -*- coding: utf-8 -*-
"""SCATTER_CORRECTION_CXR_CFE.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Fo-vymkfDNaGpqPMCuxvLmxyfLBYhJFn
# SCATTER ESTIMATION AND CORRECTION - CXR (Projections of COVID-19 CTs)
# Connect to Google Drive account
"""
from google.colab import drive
drive.mount('/content/drive',force_remount=True)
"""# Install required libraries"""
!pip install -q opencv-python
!pip install -q keras-unet
"""# Load Libraries"""
import tensorflow as tf
tf.version.VERSION
import numpy as np
import os
import time
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from IPython.display import clear_output
import cv2
import sklearn.model_selection as sk
import pandas as pd
import glob
from scipy.ndimage import gaussian_filter
from sklearn.metrics import mean_absolute_percentage_error
from skimage.metrics import structural_similarity as ssim
from sklearn.metrics import mean_squared_error
from pylab import array, plot, show, axis, arange, figure, uint8
from scipy.io import loadmat
from skimage import measure
import math
from skimage.morphology import convex_hull_image
import scipy.ndimage as nd
from scipy import stats
"""# Check GPU"""
tf.config.list_physical_devices('GPU')
!nvidia-smi
"""# Load Images from Drive
## Image Parameters
"""
# Images are expected as float32 values (Little Endian)
Nx = 2050 # Number of pixels in x
Ny = 2050 # Number of pixels in y
Nz = 130 # Total Number of images
"""## Option 1: Load images saved in .raw format"""
def load_raw(folder):
filelist = glob.glob(folder)
PROJ = np.zeros((Nz,Nx,Ny),dtype='float32')
i = 0
for filename in np.sort(filelist):
PROJ_single = np.fromfile(filename,dtype='float32')
PROJ_single = np.reshape(PROJ_single,(2050,2050))
print(filename)
PROJ[i,:,:] = PROJ_single
i = i+1
# Change image size to 128x128 (to avoid memory troubles in Colab)
PROJ = np.expand_dims(PROJ,axis=-1)
PROJ = tf.convert_to_tensor(PROJ, tf.float32)
Nx2 = 128
Ny2 = 128
PROJ = tf.image.resize(PROJ,[Nx2,Ny2],method='bilinear')
return PROJ
"""### Low Energy
No Scatter
"""
PROJ_LE_NS = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/BAJA_ENERGIA_5e9/NO_SCATTER/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_LE_NS_np = np.squeeze(PROJ_LE_NS.numpy()).reshape(-1,128)
PROJ_LE_NS_pd = pd.DataFrame(PROJ_LE_NS_np)
PROJ_LE_NS_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_NS_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_LE_NS
"""Total"""
PROJ_LE_T = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/BAJA_ENERGIA_5e9/TOTAL/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_LE_T_np = np.squeeze(PROJ_LE_T.numpy()).reshape(-1,128)
PROJ_LE_T_pd = pd.DataFrame(PROJ_LE_T_np)
PROJ_LE_T_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_T_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_LE_T
"""Scatter"""
PROJ_LE_S = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/BAJA_ENERGIA_5e9/SCATTER/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_LE_S_np = np.squeeze(PROJ_LE_S.numpy()).reshape(-1,128)
PROJ_LE_S_pd = pd.DataFrame(PROJ_LE_S_np)
PROJ_LE_S_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_S_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_LE_S
"""### High Energy
No Scatter
"""
PROJ_HE_NS = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/ALTA_ENERGIA_5e9/NO_SCATTER/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_HE_NS_np = np.squeeze(PROJ_HE_NS.numpy()).reshape(-1,128)
PROJ_HE_NS_pd = pd.DataFrame(PROJ_HE_NS_np)
PROJ_HE_NS_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_NS_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_HE_NS
"""Total"""
PROJ_HE_T = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/ALTA_ENERGIA_5e9/TOTAL/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_HE_T_np = np.squeeze(PROJ_HE_T.numpy()).reshape(-1,128)
PROJ_HE_T_pd = pd.DataFrame(PROJ_HE_T_np)
PROJ_HE_T_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_T_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_HE_T
"""Scatter"""
PROJ_HE_S = load_raw('drive/My Drive/ENERGIA_DUAL_IMAGENES/PROYECCIONES_BIEN/ALTA_ENERGIA_5e9/SCATTER/*.raw')
# Save images in .csv to for a quicker load next times
PROJ_HE_S_np = np.squeeze(PROJ_HE_S.numpy()).reshape(-1,128)
PROJ_HE_S_pd = pd.DataFrame(PROJ_HE_S_np)
PROJ_HE_S_pd.to_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_S_5e9.csv')
# Delete the images saved as tensor to release memory
del PROJ_HE_S
"""## Option 2: Load images saved in .csv format
The input images of the NN will be the CXRs affected by the scatter contribution (referred to as "total"), while the output of the NN will be the scatter fraction (scatter/total).
"""
Nx2 = 128
Ny2 = 128
def load_csv(csv_file):
image_set = pd.read_csv(csv_file) #Pandas DataFrame
image_set = image_set.to_numpy() #Pandas DataFrame --> Numpy Array
image_set = image_set[:,1:129] #Remove extra column
image_set = image_set.reshape((130,128,128)) #Reshape first dimension
image_set = np.expand_dims(image_set,axis=-1) #Add extra dimension
image_set = tf.convert_to_tensor(image_set, tf.float32) #Convert to tensor
image_set = tf.image.resize(image_set,[Nx2,Ny2],method='bilinear')
image_set = image_set.numpy()
print(image_set.shape)
return image_set
inp_np_HE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_T_5e9.csv')
out_np_HE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_S_5e9.csv')
inp_np_LE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_T_5e9.csv')
out_np_LE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_S_5e9.csv')
"""# Crop images to remove the air region surrounding the body"""
inp_np_HE_cut = inp_np_HE[:,:,16:112,:]
out_np_HE_cut = out_np_HE[:,:,16:112,:]
inp_np_LE_cut = inp_np_LE[:,:,16:112,:]
out_np_LE_cut = out_np_LE[:,:,16:112,:]
print(inp_np_LE_cut.shape)
plt.figure(figsize=(20,20))
for i in range(0,len(inp_np_HE_cut)):
plt.subplot(12,12,i+1)
plt.imshow(np.squeeze(inp_np_HE_cut[i,0:128,:,:]),cmap=plt.cm.bone,vmin=0,vmax=1.075)
print(type(inp_np_HE))
print(type(inp_np_HE_cut))
"""# Remove small object images"""
inp_np_HE_cut = np.delete(inp_np_HE_cut,[2,23,48,72,103,111,115,119],axis=0)
inp_np_LE_cut = np.delete(inp_np_LE_cut,[2,23,48,72,103,111,115,119],axis=0)
print(inp_np_HE_cut.shape)
out_np_HE_cut = np.delete(out_np_HE_cut,[2,23,48,72,103,111,115,119],axis=0)
out_np_LE_cut = np.delete(out_np_LE_cut,[2,23,48,72,103,111,115,119],axis=0)
print(out_np_HE_cut.shape)
"""# Create input images with 2 channels (low and high energy CXRs) for dual-energy NN models"""
inp_np_cut_dual = np.zeros([len(inp_np_HE_cut),128,96,2])
inp_np_cut_dual[:,:,:,0] = inp_np_LE_cut[:,:,:,0] #[:,0:128,:,0]
inp_np_cut_dual[:,:,:,1] = inp_np_HE_cut[:,:,:,0] #[:,128:256,:,0]
"""# Visualize all images
Total CXR (with scatter contribution)
"""
plt.figure(figsize=(20,20))
for i in range(0,len(inp_np_HE_cut)):
plt.subplot(12,12,i+1)
plt.imshow(np.squeeze(inp_np_HE_cut[i,0:128,:,:]),cmap=plt.cm.bone,vmin=0,vmax=1.075)
"""Scatter images"""
plt.figure(figsize=(20,20))
for i in range(0,len(out_np_HE_cut)):
plt.subplot(12,12,i+1)
plt.imshow(np.squeeze(out_np_HE_cut[i,0:128,:,:]),cmap=plt.cm.bone) #,vmin=0,vmax=1.075)
"""# Output Normalization: Calculate Scatter Fraction as Scatter/Total"""
out_np_LE_norm = np.zeros_like(out_np_LE_cut)
out_np_HE_norm = np.zeros_like(out_np_HE_cut)
for i in range(0,len(out_np_LE_cut)):
out_np_LE_norm[i,:,:,:] = out_np_LE_cut[i,:,:,:]/(inp_np_LE_cut[i,:,:,:]) #+0.01*inp_np[i,0:128,:,:].max())
out_np_HE_norm[i,:,:,:] = out_np_HE_cut[i,:,:,:]/(inp_np_HE_cut[i,:,:,:]) #+0.01*inp_np[i,128:256,:,:].max())
print(out_np_HE_norm.shape)
"""## Figure: Example of scatter fraction"""
plt.figure()
plt.imshow(np.rot90(np.squeeze(out_np_HE_norm[0,:,:,0])),cmap=plt.cm.bone)
plt.axis('off')
"""# Split Data into Train and Validation Sets
We could split data by making a shuffle, but this way it is easier to identify the validation data, which will be used afterwards to assess the accuracy of the models.
"""
# High Energy
x_train_HE = inp_np_HE_cut[0:70,:,:,:]
x_val_HE = inp_np_HE_cut[70:100,:,:,:]
y_train_HE = out_np_HE_norm[0:70,:,:,:]
y_val_HE = out_np_HE_norm[70:100,:,:,:]
# Low Energy
x_train_LE = inp_np_LE_cut[0:70,:,:,:]
x_val_LE = inp_np_LE_cut[70:100,:,:,:]
y_train_LE = out_np_LE_norm[0:70,:,:,:]
y_val_LE = out_np_LE_norm[70:100,:,:,:]
"""## Convert Numpy arrays to Tensor
This is to employ the data as input and output in the training process
"""
# High Energy
x_train_tf_HE = tf.convert_to_tensor(x_train_HE, tf.float32)
x_val_tf_HE = tf.convert_to_tensor(x_val_HE, tf.float32)
y_train_tf_HE = tf.convert_to_tensor(y_train_HE, tf.float32)
y_val_tf_HE = tf.convert_to_tensor(y_val_HE, tf.float32)
# Low Energy
x_train_tf_LE = tf.convert_to_tensor(x_train_LE, tf.float32)
x_val_tf_LE = tf.convert_to_tensor(x_val_LE, tf.float32)
y_train_tf_LE = tf.convert_to_tensor(y_train_LE, tf.float32)
y_val_tf_LE = tf.convert_to_tensor(y_val_LE, tf.float32)
x_train_tf_HE.shape
"""# NEURAL NETWORK: MultiResUnet - High Energy
## Load Keras Modules
"""
from keras_unet.models import custom_unet
from keras_unet.utils import get_augmented
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
"""## MultiResUnet Architecture"""
from keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Activation, add
from keras.models import Model, model_from_json
def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), activation='relu', name=None):
'''
2D Convolutional layers
Arguments:
x {keras layer} -- input layer
filters {int} -- number of filters
num_row {int} -- number of rows in filters
num_col {int} -- number of columns in filters
Keyword Arguments:
padding {str} -- mode of padding (default: {'same'})
strides {tuple} -- stride of convolution operation (default: {(1, 1)})
activation {str} -- activation function (default: {'relu'})
name {str} -- name of the layer (default: {None})
Returns:
[keras layer] -- [output layer]
'''
x = Conv2D(filters, (num_row, num_col), strides=strides, padding=padding,use_bias=False,kernel_initializer="he_normal")(x)
x = BatchNormalization(axis=3, scale=False)(x)
if(activation == None):
return x
x = Activation(activation, name=name)(x)
return x
def trans_conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(2, 2), name=None):
'''
2D Transposed Convolutional layers
Arguments:
x {keras layer} -- input layer
filters {int} -- number of filters
num_row {int} -- number of rows in filters
num_col {int} -- number of columns in filters
Keyword Arguments:
padding {str} -- mode of padding (default: {'same'})
strides {tuple} -- stride of convolution operation (default: {(2, 2)})
name {str} -- name of the layer (default: {None})
Returns:
[keras layer] -- [output layer]
'''
x = Conv2DTranspose(filters, (num_row, num_col), strides=strides, padding=padding)(x)
x = BatchNormalization(axis=3, scale=False)(x)
return x
def MultiResBlock(U, inp, alpha = 1.67):
'''
MultiRes Block
Arguments:
U {int} -- Number of filters in a corresponding UNet stage
inp {keras layer} -- input layer
Returns:
[keras layer] -- [output layer]
'''
W = alpha * U
shortcut = inp
shortcut = conv2d_bn(shortcut, int(W*0.167) + int(W*0.333) +
int(W*0.5), 1, 1, activation=None, padding='same')
conv3x3 = conv2d_bn(inp, int(W*0.167), 3, 3,
activation='relu', padding='same')
conv5x5 = conv2d_bn(conv3x3, int(W*0.333), 3, 3,
activation='relu', padding='same')
conv7x7 = conv2d_bn(conv5x5, int(W*0.5), 3, 3,
activation='relu', padding='same')
out = concatenate([conv3x3, conv5x5, conv7x7], axis=3)
out = BatchNormalization(axis=3)(out)
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
return out
def ResPath(filters, length, inp):
'''
ResPath
Arguments:
filters {int} -- [description]
length {int} -- length of ResPath
inp {keras layer} -- input layer
Returns:
[keras layer] -- [output layer]
'''
shortcut = inp
shortcut = conv2d_bn(shortcut, filters, 1, 1,
activation=None, padding='same')
out = conv2d_bn(inp, filters, 3, 3, activation='relu', padding='same')
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
for i in range(length-1):
shortcut = out
shortcut = conv2d_bn(shortcut, filters, 1, 1,
activation=None, padding='same')
out = conv2d_bn(out, filters, 3, 3, activation='relu', padding='same')
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
return out
def MultiResUnet(height, width, n_channels,filters):
'''
MultiResUNet
Arguments:
height {int} -- height of image
width {int} -- width of image
n_channels {int} -- number of channels in image
Returns:
[keras model] -- MultiResUNet model
'''
inputs = Input((height, width, n_channels))
#inputs_SF = Input((height, width, n_channels)) #CFE: test to put the loss function inside the model
mresblock1 = MultiResBlock(filters, inputs)
pool1 = MaxPooling2D(pool_size=(2, 2))(mresblock1)
mresblock1 = ResPath(filters, 4, mresblock1)
mresblock2 = MultiResBlock(filters*2, pool1)
pool2 = MaxPooling2D(pool_size=(2, 2))(mresblock2)
mresblock2 = ResPath(filters*2, 3, mresblock2)
mresblock3 = MultiResBlock(filters*4, pool2)
pool3 = MaxPooling2D(pool_size=(2, 2))(mresblock3)
mresblock3 = ResPath(filters*4, 2, mresblock3)
mresblock4 = MultiResBlock(filters*8, pool3)
pool4 = MaxPooling2D(pool_size=(2, 2))(mresblock4)
mresblock4 = ResPath(filters*8, 1, mresblock4)
mresblock5 = MultiResBlock(filters*16, pool4)
print(inputs.shape)
print(mresblock1.shape)
print(mresblock2.shape)
print(mresblock3.shape)
print(mresblock4.shape)
print(mresblock5.shape)
up6 = concatenate([Conv2DTranspose(
filters*8, (2, 2), strides=(2, 2), padding='same')(mresblock5), mresblock4], axis=3)
mresblock6 = MultiResBlock(filters*8, up6)
up7 = concatenate([Conv2DTranspose(
filters*4, (2, 2), strides=(2, 2), padding='same')(mresblock6), mresblock3], axis=3)
mresblock7 = MultiResBlock(filters*4, up7)
up8 = concatenate([Conv2DTranspose(
filters*2, (2, 2), strides=(2, 2), padding='same')(mresblock7), mresblock2], axis=3)
mresblock8 = MultiResBlock(filters*2, up8)
up9 = concatenate([Conv2DTranspose(filters, (2, 2), strides=(
2, 2), padding='same')(mresblock8), mresblock1], axis=3)
mresblock9 = MultiResBlock(filters, up9)
conv10 = conv2d_bn(mresblock9, 1, 1, 1, activation='relu')
model = Model(inputs=[inputs], outputs=[conv10])
# # Construct your custom loss as a tensor And Compile without specifying a loss
# loss = K.mean(K.square(inputs_SF*inputs_T - outputs*input_T), axis=-1)
# ## Add loss to model
# model.add_loss(loss)
return model
"""## Model Definition"""
#Run this for MultiResUnet Network
filters=64
channels=1
mresunet=MultiResUnet(x_train_tf_HE.shape[1],x_train_tf_HE.shape[2],channels,filters) #MultiResUnet(Ny,Nx,channels,filters)
opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name='Adam')
mresunet.compile(optimizer=opt, loss='MeanSquaredError') #l1 NORM #MeanSquaredError #MeanAbsoluteError #mean_squared_logarithmic_error #root_mean_squared_error
#mresunet.compile(optimizer=opt) #If loss function is inside the model
"""## Data Augmentation"""
# Train data, provide the same seed and keyword arguments to the fit and flow methods
def get_augmented_mod(
X_train, Y_train, batch_size=32, seed=0,
data_gen_args=dict(rotation_range=0.0, width_shift_range=0.,
height_shift_range=0.0, shear_range=0, zoom_range=[0.5,1],
horizontal_flip=True, vertical_flip=True, fill_mode="nearest")):
X_datagen = ImageDataGenerator(**data_gen_args)
Y_datagen = ImageDataGenerator(**data_gen_args)
X_datagen.fit(X_train, augment=True, seed=seed)
Y_datagen.fit(Y_train, augment=True, seed=seed)
X_train_augmented = X_datagen.flow(X_train, batch_size=batch_size, shuffle=True, seed=seed)
Y_train_augmented = Y_datagen.flow(Y_train, batch_size=batch_size, shuffle=True, seed=seed)
train_generator = zip(X_train_augmented, Y_train_augmented)
return train_generator
#return train_generator, X_train_augmented, Y_train_augmented
train_gen = get_augmented_mod(x_train_tf_HE, y_train_tf_HE, batch_size=24,
data_gen_args = dict(width_shift_range=0.0,height_shift_range=0.0,rotation_range=0.0,
horizontal_flip=True,vertical_flip=True,fill_mode='nearest', zoom_range=[0.5,1]))
"""## Run Training"""
#history6 = mresunet.fit(x_train_tf_HE, y_train_tf_HE,batch_size=32, steps_per_epoch=10, epochs=400,validation_data=(x_val_tf_HE,y_val_tf_HE)) #,steps_per_epoch=10, epochs=400, validation_data=(x_val_tf_HE,y_val_tf_HE)) #,callbacks=[checkpoint6])
history6 = mresunet.fit(train_gen, steps_per_epoch=10, epochs=600, validation_data=(x_val_tf_HE, y_val_tf_HE)) #,callbacks=[checkpoint6])
"""## Plot Training and Validation Loss Functions"""
fig, ax = plt.subplots(figsize=(20,5))
loss = np.array(history6.history['loss'])
var_loss = np.array(history6.history['val_loss'])
ax.plot(20*np.log(1+loss), 'orange', label='Training Loss')
ax.plot(20*np.log(1+var_loss), 'green', label='Validation loss')
ax.set_ylim([0, 0.5])
ax.legend()
fig.show()
"""## Plot the Scatter Fraction Estimation (1 case)"""
img_index = 15 #54
test = tf.concat([x_val_tf_HE,y_val_tf_HE,x_val_tf_HE*y_val_tf_HE],-1)
test = np.expand_dims(test[img_index,:,:,:],axis=0)
estim = mresunet.predict(test)
TOT_img = np.squeeze(test[0,:,:,0]) #CT_img = np.squeeze(test)
ESTIM_img = np.squeeze(estim)
SCAT_img = np.squeeze(y_val_tf_HE[img_index,:,:,0]) #DOSE_img = np.squeeze(y_val_tf[img_index,:,:,:])
plt.figure(figsize=(20, 10))
plt.subplot(1,3,1)
plt.imshow(TOT_img,cmap=plt.cm.bone) #plt.imshow(np.concatenate((TOT_img[:,:,0],TOT_img[:,:,1]),axis=0),cmap=plt.cm.bone) #plt.imshow(CT_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('TOTAL (input)') #plt.title('CT (Input)')
plt.subplot(1,3,2)
plt.imshow(ESTIM_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('Estimated SCATTER Fraction with SCATTER_HE-MResUnet') #plt.title('Estimated DOSE with CT2DOSE')
plt.subplot(1,3,3)
plt.imshow(SCAT_img,cmap=plt.cm.bone) #plt.imshow(DOSE_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('SCATTER Fraction (Reference)') #plt.title('DOSE (Reference)')
"""## Saved Trained Model"""
loss = np.array(history6.history['loss'])
var_loss = np.array(history6.history['val_loss'])
loss_info = np.transpose(100*np.array([loss,var_loss]))
np.savetxt( "drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/LOSSINFO_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.csv", loss_info, fmt='%.3f', delimiter='\t')
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/loss_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.csv',loss)
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/Varloss_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.csv',var_loss)
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/MSE_val_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.csv',MAE_train)
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/MSE_val_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.csv',MAE_val)
# Save the entire model as a HDF5 file.
mresunet.save('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/SCATTER_HE600Cut_MRU_FracScatterTotal_NoRot_addloss_lambda03.h5')
"""# NEURAL NETWORK: MultiResUnet - Dual Energy
## Select Dual Energy Data
"""
x_train_dual = np.zeros((70,128,96,2))
x_val_dual = np.zeros((30,128,96,2))
x_train_dual[:,:,:,0] = x_train_LE[:,:,:,0]
x_train_dual[:,:,:,1] = x_train_HE[:,:,:,0]
x_val_dual[:,:,:,0] = x_val_LE[:,:,:,0]
x_val_dual[:,:,:,1] = x_val_HE[:,:,:,0]
x_train_tf_dual = tf.convert_to_tensor(x_train_dual, tf.float32)
x_val_tf_dual = tf.convert_to_tensor(x_val_dual, tf.float32)
y_train_dual = np.zeros((70,128,96,2))
y_val_dual = np.zeros((30,128,96,2))
y_train_dual[:,:,:,0] = y_train_LE[:,:,:,0]
y_train_dual[:,:,:,1] = y_train_HE[:,:,:,0]
y_val_dual[:,:,:,0] = y_val_LE[:,:,:,0]
y_val_dual[:,:,:,1] = y_val_HE[:,:,:,0]
y_train_tf_dual = tf.convert_to_tensor(y_train_dual, tf.float32)
y_val_tf_dual = tf.convert_to_tensor(y_val_dual, tf.float32)
"""## Load Keras Modules"""
from keras_unet.models import custom_unet
from keras_unet.utils import get_augmented
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
"""## MultiResUnet Architecture"""
from keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Activation, add
from keras.models import Model, model_from_json
#from keras.optimizers import Adam
#from keras.layers.advanced_activations import ELU, LeakyReLU
def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), activation='relu', name=None):
'''
2D Convolutional layers
Arguments:
x {keras layer} -- input layer
filters {int} -- number of filters
num_row {int} -- number of rows in filters
num_col {int} -- number of columns in filters
Keyword Arguments:
padding {str} -- mode of padding (default: {'same'})
strides {tuple} -- stride of convolution operation (default: {(1, 1)})
activation {str} -- activation function (default: {'relu'})
name {str} -- name of the layer (default: {None})
Returns:
[keras layer] -- [output layer]
'''
x = Conv2D(filters, (num_row, num_col), strides=strides, padding=padding, use_bias=False,kernel_initializer="he_normal")(x)
x = BatchNormalization(axis=3, scale=False)(x)
if(activation == None):
return x
x = Activation(activation, name=name)(x)
return x
def trans_conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(2, 2), name=None):
'''
2D Transposed Convolutional layers
Arguments:
x {keras layer} -- input layer
filters {int} -- number of filters
num_row {int} -- number of rows in filters
num_col {int} -- number of columns in filters
Keyword Arguments:
padding {str} -- mode of padding (default: {'same'})
strides {tuple} -- stride of convolution operation (default: {(2, 2)})
name {str} -- name of the layer (default: {None})
Returns:
[keras layer] -- [output layer]
'''
x = Conv2DTranspose(filters, (num_row, num_col), strides=strides, padding=padding)(x)
x = BatchNormalization(axis=3, scale=False)(x)
return x
def MultiResBlock(U, inp, alpha = 1.67):
'''
MultiRes Block
Arguments:
U {int} -- Number of filters in a corresponding UNet stage
inp {keras layer} -- input layer
Returns:
[keras layer] -- [output layer]
'''
W = alpha * U
shortcut = inp
shortcut = conv2d_bn(shortcut, int(W*0.167) + int(W*0.333) +
int(W*0.5), 1, 1, activation=None, padding='same')
conv3x3 = conv2d_bn(inp, int(W*0.167), 3, 3,
activation='relu', padding='same')
conv5x5 = conv2d_bn(conv3x3, int(W*0.333), 3, 3,
activation='relu', padding='same')
conv7x7 = conv2d_bn(conv5x5, int(W*0.5), 3, 3,
activation='relu', padding='same')
out = concatenate([conv3x3, conv5x5, conv7x7], axis=3)
out = BatchNormalization(axis=3)(out)
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
return out
def ResPath(filters, length, inp):
'''
ResPath
Arguments:
filters {int} -- [description]
length {int} -- length of ResPath
inp {keras layer} -- input layer
Returns:
[keras layer] -- [output layer]
'''
shortcut = inp
shortcut = conv2d_bn(shortcut, filters, 1, 1,
activation=None, padding='same')
out = conv2d_bn(inp, filters, 3, 3, activation='relu', padding='same')
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
for i in range(length-1):
shortcut = out
shortcut = conv2d_bn(shortcut, filters, 1, 1,
activation=None, padding='same')
out = conv2d_bn(out, filters, 3, 3, activation='relu', padding='same')
out = add([shortcut, out])
out = Activation('relu')(out)
out = BatchNormalization(axis=3)(out)
return out
def MultiResUnet(height, width, n_channels,filters):
'''
MultiResUNet
Arguments:
height {int} -- height of image
width {int} -- width of image
n_channels {int} -- number of channels in image
Returns:
[keras model] -- MultiResUNet model
'''
inputs = Input((height, width, n_channels))
mresblock1 = MultiResBlock(filters, inputs)
pool1 = MaxPooling2D(pool_size=(2, 2))(mresblock1)
mresblock1 = ResPath(filters, 4, mresblock1)
mresblock2 = MultiResBlock(filters*2, pool1)
pool2 = MaxPooling2D(pool_size=(2, 2))(mresblock2)
mresblock2 = ResPath(filters*2, 3, mresblock2)
mresblock3 = MultiResBlock(filters*4, pool2)
pool3 = MaxPooling2D(pool_size=(2, 2))(mresblock3)
mresblock3 = ResPath(filters*4, 2, mresblock3)
mresblock4 = MultiResBlock(filters*8, pool3)
pool4 = MaxPooling2D(pool_size=(2, 2))(mresblock4)
mresblock4 = ResPath(filters*8, 1, mresblock4)
mresblock5 = MultiResBlock(filters*16, pool4)
up6 = concatenate([Conv2DTranspose(
filters*8, (2, 2), strides=(2, 2), padding='same')(mresblock5), mresblock4], axis=3)
mresblock6 = MultiResBlock(filters*8, up6)
up7 = concatenate([Conv2DTranspose(
filters*4, (2, 2), strides=(2, 2), padding='same')(mresblock6), mresblock3], axis=3)
mresblock7 = MultiResBlock(filters*4, up7)
up8 = concatenate([Conv2DTranspose(
filters*2, (2, 2), strides=(2, 2), padding='same')(mresblock7), mresblock2], axis=3)
mresblock8 = MultiResBlock(filters*2, up8)
up9 = concatenate([Conv2DTranspose(filters, (2, 2), strides=(
2, 2), padding='same')(mresblock8), mresblock1], axis=3)
mresblock9 = MultiResBlock(filters, up9)
conv10 = conv2d_bn(mresblock9, 2, 1, 1, activation='relu') #filters=2 in order to have 2 channels in the output (second parameter of the input of conv2d_bn)
model = Model(inputs=[inputs], outputs=[conv10])
return model
"""## Model Definition"""
#Run this for MultiResUnet Network
filters=64
channels=2
mresunet=MultiResUnet(x_train_tf_dual.shape[1],x_train_tf_dual.shape[2],channels,filters) #MultiResUnet(Ny,Nx,channels,filters)
opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name='Adam')
mresunet.compile(optimizer=opt, loss='MeanSquaredError') #l1 NORM #MeanSquaredError #MeanAbsoluteError #mean_squared_logarithmic_error #root_mean_squared_error
"""## Data Augmentation"""
# Train data, provide the same seed and keyword arguments to the fit and flow methods
def get_augmented_mod(
X_train, Y_train, batch_size=32, seed=0,
data_gen_args=dict(rotation_range=0.0, width_shift_range=0.,
height_shift_range=0.0, shear_range=0, zoom_range=[0.5,1],
horizontal_flip=True, vertical_flip=True, fill_mode="nearest")):
X_datagen = ImageDataGenerator(**data_gen_args)
Y_datagen = ImageDataGenerator(**data_gen_args)
X_datagen.fit(X_train, augment=True, seed=seed)
Y_datagen.fit(Y_train, augment=True, seed=seed)
X_train_augmented = X_datagen.flow(X_train, batch_size=batch_size, shuffle=True, seed=seed)
Y_train_augmented = Y_datagen.flow(Y_train, batch_size=batch_size, shuffle=True, seed=seed)
train_generator = zip(X_train_augmented, Y_train_augmented)
return train_generator
#return train_generator, X_train_augmented, Y_train_augmented
train_gen = get_augmented(x_train_tf_dual[:,:,:,:], y_train_tf_dual[:,:,:,:], batch_size=24,
data_gen_args = dict(width_shift_range=0.0,height_shift_range=0.0,rotation_range=0.0,
horizontal_flip=True,vertical_flip=True,fill_mode='nearest', zoom_range=[0.5,1]))
"""## Run Training"""
history6 = mresunet.fit(train_gen,steps_per_epoch=10, epochs=600, validation_data=(x_val_tf_dual, y_val_tf_dual)) #,callbacks=[checkpoint6])
#history6 = mresunet.fit(train_gen,y=None, epochs=600, validation_data=([yy],[])) #,steps_per_epoch=10, epochs=400,) #,callbacks=[checkpoint6])
"""## Plot Training and Validation Loss Functions"""
fig, ax = plt.subplots(figsize=(20,5))
loss = np.array(history6.history['loss'])
var_loss = np.array(history6.history['val_loss'])
ax.plot(20*np.log(1+loss), 'orange', label='Training Loss')
ax.plot(20*np.log(1+var_loss), 'green', label='Validation loss')
ax.set_ylim([0, 0.5])
ax.legend()
fig.show()
"""## Plot the Scatter Fraction Estimation (1 case)"""
img_index = 15 #54
# test = tf.concat([x_val_tf_LE,x_val_tf_HE,y_val_tf_HE],-1)
# test = np.expand_dims(test[img_index,:,:,:],axis=0)
test = np.expand_dims(x_val_tf_dual[img_index,:,:,:],axis=0)
estim = mresunet.predict(test)
TOT_img_LE = np.squeeze(test[0,:,:,0]) #CT_img = np.squeeze(test)
TOT_img_HE = np.squeeze(test[0,:,:,1])
ESTIM_img_LE = np.squeeze(estim[0,:,:,0])
ESTIM_img_HE = np.squeeze(estim[0,:,:,1])
SCAT_img_LE = np.squeeze(y_val_tf_dual[img_index,:,:,0]) #DOSE_img = np.squeeze(y_val_tf[img_index,:,:,:])
SCAT_img_HE = np.squeeze(y_val_tf_dual[img_index,:,:,1])
plt.figure(figsize=(20, 10))
plt.subplot(2,3,1)
plt.imshow(TOT_img_LE,cmap=plt.cm.bone) #plt.imshow(np.concatenate((TOT_img[:,:,0],TOT_img[:,:,1]),axis=0),cmap=plt.cm.bone) #plt.imshow(CT_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('TOTAL LE (input)') #plt.title('CT (Input)')
plt.subplot(2,3,2)
plt.imshow(ESTIM_img_LE, cmap=plt.cm.bone)
plt.axis('off')
plt.title('Estimated SCATTER FRACTION LE') #plt.title('Estimated DOSE with CT2DOSE')
plt.subplot(2,3,3)
plt.imshow(SCAT_img_LE,cmap=plt.cm.bone) #plt.imshow(DOSE_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('SCATTER FRACTION LE (Reference)') #plt.title('DOSE (Reference)')
plt.subplot(2,3,4)
plt.imshow(TOT_img_HE,cmap=plt.cm.bone) #plt.imshow(np.concatenate((TOT_img[:,:,0],TOT_img[:,:,1]),axis=0),cmap=plt.cm.bone) #plt.imshow(CT_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('TOTAL HE (input)') #plt.title('CT (Input)')
plt.subplot(2,3,5)
plt.imshow(ESTIM_img_HE, cmap=plt.cm.bone)
plt.axis('off')
plt.title('Estimated SCATTER FRACTION HE') #plt.title('Estimated DOSE with CT2DOSE')
plt.subplot(2,3,6)
plt.imshow(SCAT_img_HE,cmap=plt.cm.bone) #plt.imshow(DOSE_img, cmap=plt.cm.bone)
plt.axis('off')
plt.title('SCATTER FRACTION HE (Reference)') #plt.title('DOSE (Reference)')
"""## Save Trained Model"""
loss = np.array(history6.history['loss'])
var_loss = np.array(history6.history['val_loss'])
loss_info = np.transpose(100*np.array([loss,var_loss]))
np.savetxt( "drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/LOSSINFO_DUAL600Cut_MRU22ch_FracScatterTotal_NoRot_Original.csv", loss_info, fmt='%.3f', delimiter='\t')
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/loss_DUAL600Cut_MRU22ch_FracScatterTotal_NoRot_Original.csv',loss)
np.savetxt('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/Varloss_DUAL600Cut_MRU22ch_FracScatterTotal_NoRot_Original.csv',var_loss)
# Save the entire model as a HDF5 file.
mresunet.save('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/SCATTER_DUAL600Cut_MRU22ch_FracScatterTotal_NoRot_Original.h5')
"""# ANALYSIS OF ESTIMATED AND CORRECTED SCATTER
## Load Trained Models
"""
model_HE = tf.keras.models.load_model('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/SCATTER_HE600Cut_MRU_FracScatterTotal_NoRot_Original_DetScat.h5',compile=False)
model_DUAL_HELE = tf.keras.models.load_model('drive/My Drive/ENERGIA_DUAL_IMAGENES/MODELS_BIEN_5e9/SCATTER_DUAL600Cut_MRU22ch_FracScatterTotal_NoRot_Original.h5',compile=False)
"""## Load Reference Scatter, No-Scatter & Total Projection
"""
total_HE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_T_5e9.csv')
scat_ref_HE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_S_5e9.csv')
noscat_ref_HE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_HE_NS_5e9.csv')
total_LE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_T_5e9.csv')
scat_ref_LE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_S_5e9.csv')
noscat_ref_LE = load_csv('drive/My Drive/ENERGIA_DUAL_IMAGENES/TRAINING_DATA_BIEN/PROJ_LE_NS_5e9.csv')
"""## Crop Images"""
scat_ref_HE = scat_ref_HE[:,:,16:112,:]
total_HE = total_HE[:,:,16:112,:]
noscat_ref_HE = noscat_ref_HE[:,:,16:112,:]
scat_ref_LE = scat_ref_LE[:,:,16:112,:]
total_LE = total_LE[:,:,16:112,:]
noscat_ref_LE = noscat_ref_LE[:,:,16:112,:]
print(scat_ref_HE.shape)
# Remove small objects
scat_ref_HE = np.delete(scat_ref_HE,[2,23,48,72,103,111,115,119],axis=0)
total_HE = np.delete(total_HE,[2,23,48,72,103,111,115,119],axis=0)
noscat_ref_HE = np.delete(noscat_ref_HE,[2,23,48,72,103,111,115,119],axis=0)
scat_ref_LE = np.delete(scat_ref_LE,[2,23,48,72,103,111,115,119],axis=0)
total_LE = np.delete(total_LE,[2,23,48,72,103,111,115,119],axis=0)
noscat_ref_LE = np.delete(noscat_ref_LE,[2,23,48,72,103,111,115,119],axis=0)
print(scat_ref_HE.shape)
total_dual = np.zeros((122,128,96,2))
total_dual[:,:,:,0] = total_LE[:,:,:,0]
total_dual[:,:,:,1] = total_HE[:,:,:,0]
"""## Neural Network Estimations & Metrics"""
S_REF_HE = np.zeros((122,128,96))
NS_REF_HE = np.zeros((122,128,96))
S_REF_LE = np.zeros((122,128,96))
NS_REF_LE = np.zeros((122,128,96))
ST_ESTIM_HE = np.zeros((122,128,96))
ST_ESTIM_DUAL_DUALHE = np.zeros((122,128,96))
ST_ESTIM_DUAL_DUALLE = np.zeros((122,128,96))
S_ESTIM_HE = np.zeros((122,128,96))
S_ESTIM_DUAL_DUALHE = np.zeros((122,128,96))
S_ESTIM_DUAL_DUALLE = np.zeros((122,128,96))
NS_ESTIM_HE = np.zeros((122,128,96))
NS_ESTIM_DUAL_DUALHE = np.zeros((122,128,96))
NS_ESTIM_DUAL_DUALLE = np.zeros((122,128,96))
DIF_HE_rel = np.zeros((122,128,96))
DIF_DUAL_DUALHE_rel = np.zeros((122,128,96))
DIF_DUAL_DUALLE_rel = np.zeros((122,128,96))
DIF_HE_NSrel = np.zeros((122,128,96))
DIF_DUAL_DUALHE_NSrel = np.zeros((122,128,96))
DIF_DUAL_DUALLE_NSrel = np.zeros((122,128,96))
MAPE_NS_HE = np.zeros((122,1))
MAPE_NS_LE = np.zeros((122,1))
MAPE_NS_DUAL_DUALLE = np.zeros((122,1))