autoencoder_train_old.py 22.8 KB
Newer Older
Perez Visaires, Jon's avatar
Perez Visaires, Jon committed
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
##### -------------------------------------------------- Librerías -------------------------------------------------- #####

import os
import sys
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

sys.path.append("../tools")  # Herramientas propias de MantaFlow.
import uniio  # Lectura de ficheros .uni

from tensorflow.keras.layers import Input, Dropout, Conv2D, Conv2DTranspose, BatchNormalization, Flatten, Activation, Reshape
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.callbacks import ModelCheckpoint

import h5py

##### -------------------------------------------------- Selección GPU ---------------------------------------------- #####

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"

os.environ["CUDA_VISIBLE_DEVICES"] = "0"

##### -------------------------------------------------- Hiperparámetros -------------------------------------------- #####

num_sims = 2000  # Índice máximo escenas. 
num_scenes = num_sims - 1000  # Número de escenas.
frames = 200  # Frames por escena.

ae_epochs = 5  # Epochs para entrenamiento normal.
ae_epochs_list = 50  # Epochs para cada batch size de la lista.
pre_epochs = 1  # Epochs de preentrenamiento.

ae_batch_multiple = False  # Probar distintos batch sizes, comparar diferencias.
pre_training = True  # Realizar preentrenamiento.

ae_batch_list = [1024, 512, 256, 128, 64, 32]  # Posibles batch sizes de prueba.
ae_batch_size = 64  # Batch size oficial.
pre_batch_size = 128  # Bacth size para preentrenamiento.

##### -------------------------------------------------- Carga de datos --------------------------------------------- #####

np.random.seed(13) 

base_path = "../data"

print("Cargamos {} escenas, con {} frames cada una.".format(num_scenes, frames))
print("Trabajamos con un total de {} frames.".format((num_scenes) * frames))

# ------------------------------------------------------------------------------------------------------------------- #

base_path = "../data"

densities = []

for sim in range(1000, num_sims):
    
    if os.path.exists("%s/simSimple_%04d" % (base_path, sim)):  # Comprueba la existencia de las carpetas (cada una 200 frames de datos).
        
        for i in range(0, frames):
            
            filename = "%s/simSimple_%04d/density_%04d.uni"  # Nombre de cada frame (densidad).
            uni_path = filename % (base_path, sim, i)  # 200 frames por sim, rellena parametros de la ruta.
            header, content = uniio.readUni(uni_path)  # Devuelve un array Numpy [Z, Y, X, C].
            
            h = header["dimX"]
            w = header["dimY"]
            
            arr = content[:, ::-1, :, :]  # Cambia el orden del eje Y.
            arr = np.reshape(arr, [w, h, 1])  # Deshecha el eje Z.
            
            densities.append(arr)

# ------------------------------------------------------------------------------------------------------------------- #

load_num = len(densities)

if load_num < 2 * frames:
    
    print("Error - Usa al menos dos simulaciones completas")
    
    exit(True)

densities = np.reshape(densities, (len(densities), 64, 64, 1))  # Reconvierte la lista en array de Numpy.

print("Forma del array: {}".format(densities.shape))
print("Dimensiones del array: {}".format(densities.ndim))
print("Número de pixels en total: {}".format(densities.size))

# ------------------------------------------------------------------------------------------------------------------- #

vali_set_size = max(200, int(load_num * 0.1))  # Al menos una sim completa o el 10% de los datos.

vali_data = densities[load_num - vali_set_size : load_num, :]  # "load_num" datos del final de "densities".
train_data = densities[0 : load_num - vali_set_size, :]  # El resto de datos de "densities".

print("Separamos en {} frames de entrenamiento y {} frames de validación.".format(train_data.shape[0], vali_data.shape[0]))

# ------------------------------------------------------------------------------------------------------------------- #

train_data = np.reshape(train_data, (len(train_data), 64, 64, 1))  # Reconvertimos a arrays de Numpy.
vali_data = np.reshape(vali_data, (len(vali_data), 64, 64, 1))

print("Forma del set de entrenamiento: {}".format(train_data.shape))
print("Forma del set de validación: {}".format(vali_data.shape))

##### -------------------------------------------------- Funciones -------------------------------------------------- #####

def training_plot(network_train, epochs, batch_size, dropout, identification, loss, metric):
    
    plot_epochs = range(epochs)
    plot_loss = network_train.history["loss"]
    plot_val_loss = network_train.history["val_loss"]
    plot_metric = network_train.history[metric]
    plot_val_metric = network_train.history["val_" + metric]

    plt.figure(figsize = (15, 5))

    ax = plt.subplot(1, 2, 1)
    plt.plot(plot_epochs, plot_loss, label = loss.upper())
    plt.plot(plot_epochs, plot_val_loss, label = "Validation " + loss.upper())
    plt.legend()
    plt.xlabel("Epoch")
    plt.ylabel(loss.upper())

    ax = plt.subplot(1, 2, 2)
    plt.plot(plot_epochs, plot_metric, label = metric.upper())
    plt.plot(plot_epochs, plot_val_metric, label = "Validation " + metric.upper())
    plt.legend()
    plt.xlabel("Epoch")
    plt.ylabel(metric.upper())

    if dropout > 0.0:

        plt.savefig("../plots/model_ae_" + identification + "_DO-" + str(dropout * 100) + "_BS-" + str(batch_size) + ".png")

    else:

        plt.savefig("../plots/model_ae_" + identification + "_BS-" + str(batch_size) + ".png")

##### -------------------------------------------------- Autoencoder 2D --------------------------------------------- #####

feature_multiplier = 8  # Controla la cantidad de filtros de convolución utilizados por el autoencoder, y la dimension del espacio latente de la red. 
surface_kernel_size = 4  # Matriz 4x4
kernel_size = 2  # Matriz 2x2
dropout = 0.0  # Porcentaje de nodos que apagar mediante dropout.
init_func = "glorot_normal"  # Función de inicialización de los pesos de la red neuronal.

input_shape = (train_data.shape[1], 
               train_data.shape[2], 
               train_data.shape[3])

# ------------------------------------------------------------------------------------------------------------------- #

layer_conv = []

### Conv 1 ###

# Input #

conv1_input_shape = input_shape

conv1_input = Input(shape = conv1_input_shape)

x = conv1_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 1, 
            kernel_size = surface_kernel_size,
            strides = 1,
            padding = "same",
            kernel_initializer = init_func)(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2D(filters = feature_multiplier * 1, 
            kernel_size = surface_kernel_size,
            strides = 1,
            kernel_initializer = init_func,
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 2 #

x = Conv2D(filters = feature_multiplier * 1, 
            kernel_size = surface_kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv1_output = x

convolution_1 = Model(conv1_input, conv1_output)
layer_conv.append(convolution_1)

conv1_output_shape = (convolution_1.output_shape[1],
                      convolution_1.output_shape[2],
                      convolution_1.output_shape[3])

### Conv 2 ###

# Input #

conv2_input_shape = conv1_output_shape

conv2_input = Input(shape = conv2_input_shape)

x = conv2_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 2, 
            kernel_size = kernel_size,
            strides = 1,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2D(filters = feature_multiplier * 2, 
            kernel_size = kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv2_output = x

convolution_2 = Model(conv2_input, conv2_output)
layer_conv.append(convolution_2)

conv2_output_shape = (convolution_2.output_shape[1],
                      convolution_2.output_shape[2],
                      convolution_2.output_shape[3])

### Conv 3 ###

# Input #

conv3_input_shape = conv2_output_shape

conv3_input = Input(shape = conv3_input_shape)

x = conv3_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 4, 
            kernel_size = kernel_size,
            strides = 1,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2D(filters = feature_multiplier * 4, 
            kernel_size = kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv3_output = x

convolution_3 = Model(conv3_input, conv3_output)
layer_conv.append(convolution_3)

conv3_output_shape = (convolution_3.output_shape[1],
                      convolution_3.output_shape[2],
                      convolution_3.output_shape[3])

### Conv 4 ###

# Input #

conv4_input_shape = conv3_output_shape

conv4_input = Input(shape = conv4_input_shape)

x = conv4_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 8, 
            kernel_size = kernel_size,
            strides = 1,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2D(filters = feature_multiplier * 8, 
            kernel_size = kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv4_output = x

convolution_4 = Model(conv4_input, conv4_output)
layer_conv.append(convolution_4)

conv4_output_shape = (convolution_4.output_shape[1],
                      convolution_4.output_shape[2],
                      convolution_4.output_shape[3])

### Conv 5 ###

# Input #

conv5_input_shape = conv4_output_shape

conv5_input = Input(shape = conv5_input_shape)

x = conv5_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 16, 
            kernel_size = kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv5_output = x

convolution_5 = Model(conv5_input, conv5_output)
layer_conv.append(convolution_5)

conv5_output_shape = (convolution_5.output_shape[1],
                      convolution_5.output_shape[2],
                      convolution_5.output_shape[3])

### Conv 6 ###

# Input #

conv6_input_shape = conv5_output_shape

conv6_input = Input(shape = conv6_input_shape)

x = conv6_input

# Layer 0 #

x = Conv2D(filters = feature_multiplier * 32, 
            kernel_size = kernel_size,
            strides = 2,
            kernel_initializer = init_func, 
            padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

conv6_output = x

convolution_6 = Model(conv6_input, conv6_output)
layer_conv.append(convolution_6)

conv6_output_shape = (convolution_6.output_shape[1],
                      convolution_6.output_shape[2],
                      convolution_6.output_shape[3])

# ------------------------------------------------------------------------------------------------------------------- #

layer_deconv = []

### Deconv 6 ###

# Input #

deconv6_input_shape = conv6_output_shape

deconv6_input = Input(shape = deconv6_input_shape)

x = deconv6_input

# Layer 0 #

x = Conv2DTranspose(filters = feature_multiplier * 16, 
                    kernel_size = kernel_size,
                    strides = 2,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

deconv6_output = x

deconvolution_6 = Model(deconv6_input, deconv6_output)
layer_deconv.append(deconvolution_6)

### Deconv 5 ###

# Input # 

deconv5_input_shape = conv5_output_shape

deconv5_input = Input(shape = deconv5_input_shape)

x = deconv5_input

# Layer 0 #

x = Conv2DTranspose(filters = feature_multiplier * 8, 
                    kernel_size = kernel_size,
                    strides = 2,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2DTranspose(filters = feature_multiplier * 8, 
                    kernel_size = kernel_size,
                    strides = 1,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

deconv5_output = x

deconvolution_5 = Model(deconv5_input, deconv5_output)
layer_deconv.append(deconvolution_5)

### Deconv 4 ###

# Input #

deconv4_input_shape = conv4_output_shape

deconv4_input = Input(shape = deconv4_input_shape)

x = deconv4_input

# Layer 0 #

x = Conv2DTranspose(filters = feature_multiplier * 4, 
                    kernel_size = kernel_size,
                    strides = 2,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2DTranspose(filters = feature_multiplier * 4, 
                    kernel_size = kernel_size,
                    strides = 1,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0  else x

# Output #

deconv4_output = x

deconvolution_4 = Model(deconv4_input, deconv4_output)
layer_deconv.append(deconvolution_4)

### Deconv 3 ###

# Input #

deconv3_input_shape = conv3_output_shape

deconv3_input = Input(shape = deconv3_input_shape)

x = deconv3_input

# Layer 0 #

x = Conv2DTranspose(filters = feature_multiplier * 2, 
                    kernel_size = kernel_size,
                    strides = 2,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)

# Layer 1 #

x = Conv2DTranspose(filters = feature_multiplier * 2, 
                    kernel_size = kernel_size,
                    strides = 1,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output #

deconv3_output = x

deconvolution_3 = Model(deconv3_input, deconv3_output)
layer_deconv.append(deconvolution_3)

### Deconv 2 ###

# Input #

deconv2_input_shape = conv2_output_shape

deconv2_input = Input(shape = deconv2_input_shape)

x = deconv2_input

# Layer 0 #

x = Conv2DTranspose(filters = feature_multiplier * 1, 
                    kernel_size = kernel_size,
                    strides = 2,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x) 

# Layer 1 #

x = Conv2DTranspose(filters = feature_multiplier * 1, 
                    kernel_size = kernel_size,
                    strides = 1,
                    kernel_initializer = init_func,
                    padding = "same")(x)
x = LeakyReLU(alpha = 0.2)(x)
x = BatchNormalization()(x)
x = Dropout(dropout)(x) if dropout > 0.0 else x

# Output # 

deconv2_output = x

deconvolution_2 = Model(deconv2_input, deconv2_output)
layer_deconv.append(deconvolution_2)

### Deconv 1 ###

# Input #

deconv1_input_shape = conv1_output_shape

deconv1_input = Input(shape = deconv1_input_shape)

x = deconv1_input

# Layer 0 #

x = Conv2DTranspose(input_shape[-1],
                    kernel_size = surface_kernel_size,
                    strides = 2,
                    padding = "same",
                    kernel_initializer = init_func)(x)
x = Activation("linear")(x)

# Output #

deconv1_output = x

deconvolution_1 = Model(deconv1_input, deconv1_output)
layer_deconv.append(deconvolution_1)

layer_deconv.reverse()

##### -------------------------------------------------- Autoencoder Entrenamiento ---------------------------------- #####

adam_learning_rate = 0.00015  # El learning rate de Adam (tamaño step)
adam_epsilon = 1e-8  # Previene problemas de división por 0.
adam_lr_decay = 1e-05  # Learning rate decay

optimizer = Adam(lr = adam_learning_rate, 
                 epsilon = adam_epsilon, 
                 decay = adam_lr_decay)

# ------------------------------------------------------------------------------------------------------------------- #

stages = []

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)

x = layer_deconv[0](x)

stage_output = x

stage_1 = Model(inputs = stage_input, outputs = stage_output)
stage_1.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_1)

# ------------------------------------------------------------------------------------------------------------------- #

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)
x = layer_conv[1](x)

x = layer_deconv[1](x)
x = layer_deconv[0](x)

stage_output = x

stage_2 = Model(inputs = stage_input, outputs = stage_output)
stage_2.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_2)

# ------------------------------------------------------------------------------------------------------------------- #

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)
x = layer_conv[1](x)
x = layer_conv[2](x)

x = layer_deconv[2](x)
x = layer_deconv[1](x)
x = layer_deconv[0](x)

stage_output = x

stage_3 = Model(inputs = stage_input, outputs = stage_output)
stage_3.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_3)

# ------------------------------------------------------------------------------------------------------------------- #

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)
x = layer_conv[1](x)
x = layer_conv[2](x)
x = layer_conv[3](x)

x = layer_deconv[3](x)
x = layer_deconv[2](x)
x = layer_deconv[1](x)
x = layer_deconv[0](x)

stage_output = x

stage_4 = Model(inputs = stage_input, outputs = stage_output)
stage_4.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_4)

# ------------------------------------------------------------------------------------------------------------------- #

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)
x = layer_conv[1](x)
x = layer_conv[2](x)
x = layer_conv[3](x)
x = layer_conv[4](x)

x = layer_deconv[4](x)
x = layer_deconv[3](x)
x = layer_deconv[2](x)
x = layer_deconv[1](x)
x = layer_deconv[0](x)

stage_output = x

stage_5 = Model(inputs = stage_input, outputs = stage_output)
stage_5.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_5)

# ------------------------------------------------------------------------------------------------------------------- #

stage_input = Input(shape = input_shape)

x = stage_input

x = layer_conv[0](x)
x = layer_conv[1](x)
x = layer_conv[2](x)
x = layer_conv[3](x)
x = layer_conv[4](x)
x = layer_conv[5](x)

x = layer_deconv[5](x)
x = layer_deconv[4](x)
x = layer_deconv[3](x)
x = layer_deconv[2](x)
x = layer_deconv[1](x)
x = layer_deconv[0](x)

stage_output = x

stage_6 = Model(inputs = stage_input, outputs = stage_output)
stage_6.compile(optimizer = optimizer, loss = "mse", metrics = ["mae"])
stages.append(stage_6)

autoencoder = stage_6
autoencoder_clean_weights = autoencoder.get_weights()

# ------------------------------------------------------------------------------------------------------------------- #
   
epochs = pre_epochs
batch_size = pre_batch_size

if pre_training:
    
    for stage in stages:
        
        autoencoder_pre_train = stage.fit(train_data, train_data,
                                          epochs = epochs,
                                          batch_size = batch_size,
                                          validation_data = (vali_data, vali_data),
                                          shuffle = True)

    autoencoder.save("../modelos/autoencoder_true_pretraining.h5")
    autoencoder_pre_weights = autoencoder.get_weights()

# ------------------------------------------------------------------------------------------------------------------- #

epochs_list = ae_epochs_list
batch_list = ae_batch_list  # Distintas batch size para comparación

epochs = ae_epochs  # Número de vueltas completas al set de entrenamiento.
batch_size = ae_batch_size  # Número de ejemplos antes de calcular el error de la función de coste.

mc = ModelCheckpoint(filepath = "../modelos/autoencoder_true.h5", 
                     monitor = "val_loss", 
                     mode = "min", 
                     save_best_only = True,
                     verbose = 1)

if ae_batch_multiple:

    for batch_size in batch_list:
        
        autoencoder.set_weights(autoencoder_pre_weights)

        autoencoder_train = autoencoder.fit(train_data, train_data, 
                                            epochs = epochs_list,
                                            batch_size = batch_size,
                                            verbose = 1,
                                            validation_data = (vali_data, vali_data),
                                            shuffle = True,
                                            callbacks = [mc])
        
        training_plot(network_train = autoencoder_train, epochs = epochs_list, batch_size = batch_size, dropout = dropout, loss = "mse", metric = "mae", identification = "true_list")

else:
    
    autoencoder.set_weights(autoencoder_pre_weights)
    
    autoencoder_train = autoencoder.fit(train_data, train_data, 
                                        epochs = epochs,
                                        batch_size = batch_size,
                                        verbose = 1,
                                        validation_data = (vali_data, vali_data),
                                        shuffle = True,
                                        callbacks = [mc])
    
    training_plot(network_train = autoencoder_train, epochs = epochs, batch_size = batch_size, dropout = dropout, loss = "mse", metric = "mae", identification = "true_single")