{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"raw","source":"Transfer learning model - VGG19","metadata":{}},{"cell_type":"code","source":"pip install plot-keras-history","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:23:55.640881Z","iopub.execute_input":"2023-06-26T11:23:55.641373Z","iopub.status.idle":"2023-06-26T11:24:11.687522Z","shell.execute_reply.started":"2023-06-26T11:23:55.641317Z","shell.execute_reply":"2023-06-26T11:24:11.686344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow.keras as keras\nfrom collections import defaultdict\nimport warnings\nfrom plot_keras_history import show_history, plot_history\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:24:33.065724Z","iopub.execute_input":"2023-06-26T11:24:33.066115Z","iopub.status.idle":"2023-06-26T11:24:33.544703Z","shell.execute_reply.started":"2023-06-26T11:24:33.066075Z","shell.execute_reply":"2023-06-26T11:24:33.543752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-binary/data/train')","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:24:35.394586Z","iopub.execute_input":"2023-06-26T11:24:35.394937Z","iopub.status.idle":"2023-06-26T11:27:02.726523Z","shell.execute_reply.started":"2023-06-26T11:24:35.394904Z","shell.execute_reply":"2023-06-26T11:27:02.72553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-binary/data/valid')","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:27:02.728255Z","iopub.execute_input":"2023-06-26T11:27:02.72861Z","iopub.status.idle":"2023-06-26T11:35:10.891018Z","shell.execute_reply.started":"2023-06-26T11:27:02.728572Z","shell.execute_reply":"2023-06-26T11:35:10.89007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-binary/data/test', shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:35:10.892413Z","iopub.execute_input":"2023-06-26T11:35:10.892766Z","iopub.status.idle":"2023-06-26T11:43:22.537283Z","shell.execute_reply.started":"2023-06-26T11:35:10.892728Z","shell.execute_reply":"2023-06-26T11:43:22.536469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Instanciamos el modelo","metadata":{}},{"cell_type":"code","source":"models = defaultdict(None)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:43:55.730181Z","iopub.execute_input":"2023-06-26T11:43:55.730541Z","iopub.status.idle":"2023-06-26T11:43:55.735865Z","shell.execute_reply.started":"2023-06-26T11:43:55.73051Z","shell.execute_reply":"2023-06-26T11:43:55.734948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\n\nweights = \"imagenet\"  # TPesos que de la red\ninclude_top = False  # Si queremos incluir las capas al principio de la red\ninput_shape=(256, 256, 3)\narguments = {\"weights\": weights, \"include_top\": include_top, \"input_shape\": input_shape}\nmodels[\"Transfer learning\"] = tf.keras.applications.VGG19(**arguments)\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:46:45.26387Z","iopub.execute_input":"2023-06-26T11:46:45.264284Z","iopub.status.idle":"2023-06-26T11:46:46.105091Z","shell.execute_reply.started":"2023-06-26T11:46:45.26425Z","shell.execute_reply":"2023-06-26T11:46:46.104056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Congelar las capas del modelo base para evitar que se actualicen durante el entrenamiento","metadata":{}},{"cell_type":"code","source":"models[\"Transfer learning\"].trainable = False","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:46:48.730666Z","iopub.execute_input":"2023-06-26T11:46:48.731052Z","iopub.status.idle":"2023-06-26T11:46:48.736607Z","shell.execute_reply.started":"2023-06-26T11:46:48.731012Z","shell.execute_reply":"2023-06-26T11:46:48.735654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Extraemos el vector de características profundas aplanando la salida.","metadata":{}},{"cell_type":"code","source":"x = models[\"Transfer learning\"].output\narguments = {\"data_format\": \"channels_last\"}\nx = keras.layers.Flatten(**arguments)(x)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:46:53.177193Z","iopub.execute_input":"2023-06-26T11:46:53.177549Z","iopub.status.idle":"2023-06-26T11:46:53.186296Z","shell.execute_reply.started":"2023-06-26T11:46:53.177511Z","shell.execute_reply":"2023-06-26T11:46:53.184837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Añadimos la capa completamente conectada y la capa de salida.","metadata":{}},{"cell_type":"markdown","source":"Cuando utilizas la activación sigmoid y estableces units en 1, la capa de salida generará una única unidad de salida con un valor en el rango [0, 1]. Este valor representa la probabilidad de que la muestra pertenezca a la clase positiva (en tu caso, \"Embolia\"). Un valor cercano a 0 indica una baja probabilidad de pertenencia a la clase positiva, mientras que un valor cercano a 1 indica una alta probabilidad.\n\nEn cambio, cuando utilizas la activación softmax y estableces units en 2, la capa de salida generará dos unidades de salida, una para cada clase (\"Embolia\" y \"No embolia\"). La activación softmax aplica una función exponencial a los valores de salida, normalizándolos para que sumen 1 y generen una distribución de probabilidad. Cada valor de salida representará la probabilidad de que la muestra pertenezca a la clase correspondiente. La clase con la probabilidad más alta será la clase asignada a la muestra.","metadata":{}},{"cell_type":"code","source":"units = 128\nactivation = \"relu\"\narguments = {\"units\": units, \"activation\": activation} \nx = keras.layers.Dense(**arguments)(x)\n\nunits = 1\nactivation = \"sigmoid\"\narguments = {\"units\": units, \"activation\": activation} \noutputs = keras.layers.Dense(**arguments)(x)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:46:55.862879Z","iopub.execute_input":"2023-06-26T11:46:55.863299Z","iopub.status.idle":"2023-06-26T11:46:55.887591Z","shell.execute_reply.started":"2023-06-26T11:46:55.863264Z","shell.execute_reply":"2023-06-26T11:46:55.886735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Agurpamos todo","metadata":{}},{"cell_type":"code","source":"inputs = models[\"Transfer learning\"].input\narguments = {\"inputs\": inputs, \"outputs\": outputs}\nmodels[\"Transfer learning\"] = keras.Model(**arguments)\nmodels[\"Transfer learning\"].summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:46:59.231556Z","iopub.execute_input":"2023-06-26T11:46:59.231914Z","iopub.status.idle":"2023-06-26T11:46:59.257841Z","shell.execute_reply.started":"2023-06-26T11:46:59.231881Z","shell.execute_reply":"2023-06-26T11:46:59.256315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Compilamos","metadata":{}},{"cell_type":"code","source":"histories = defaultdict(None)  # Dictionary with the histories","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:47:04.053946Z","iopub.execute_input":"2023-06-26T11:47:04.054373Z","iopub.status.idle":"2023-06-26T11:47:04.059165Z","shell.execute_reply.started":"2023-06-26T11:47:04.054333Z","shell.execute_reply":"2023-06-26T11:47:04.057887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss = keras.losses.BinaryCrossentropy()\n\nmodels[\"Transfer learning\"].compile(loss=loss,\n              optimizer=keras.optimizers.Adam(1e-3),\n              metrics=[keras.metrics.AUC(),keras.metrics.Precision(),\n                       keras.metrics.Recall(), keras.metrics.BinaryAccuracy()])","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:47:09.407721Z","iopub.execute_input":"2023-06-26T11:47:09.408086Z","iopub.status.idle":"2023-06-26T11:47:09.451612Z","shell.execute_reply.started":"2023-06-26T11:47:09.40805Z","shell.execute_reply":"2023-06-26T11:47:09.450764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories['Transfer learning'] = models['Transfer learning'].fit(training, epochs=7, validation_data=validation, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T11:47:11.493825Z","iopub.execute_input":"2023-06-26T11:47:11.494322Z","iopub.status.idle":"2023-06-26T16:46:26.407886Z","shell.execute_reply.started":"2023-06-26T11:47:11.49427Z","shell.execute_reply":"2023-06-26T16:46:26.40684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" models['Transfer learning'].save('/kaggle/working/model-VGG19-TransferLearning.h5')","metadata":{"execution":{"iopub.status.busy":"2023-06-26T17:01:34.994972Z","iopub.execute_input":"2023-06-26T17:01:34.995395Z","iopub.status.idle":"2023-06-26T17:01:35.344217Z","shell.execute_reply.started":"2023-06-26T17:01:34.995359Z","shell.execute_reply":"2023-06-26T17:01:35.343315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for model in histories:\n    # Plot the model training history\n    history = histories[model]\n    plot_history(history)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T17:01:37.911132Z","iopub.execute_input":"2023-06-26T17:01:37.911494Z","iopub.status.idle":"2023-06-26T17:01:39.587468Z","shell.execute_reply.started":"2023-06-26T17:01:37.91146Z","shell.execute_reply":"2023-06-26T17:01:39.5864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Evaluamos el modelo","metadata":{}},{"cell_type":"code","source":"results = models[\"Transfer learning\"].evaluate(test, batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T17:02:49.464471Z","iopub.execute_input":"2023-06-26T17:02:49.464892Z","iopub.status.idle":"2023-06-26T18:16:35.148143Z","shell.execute_reply.started":"2023-06-26T17:02:49.464852Z","shell.execute_reply":"2023-06-26T18:16:35.14727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"test loss, test auc, test precision, test recall:\", results)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T18:16:35.151793Z","iopub.execute_input":"2023-06-26T18:16:35.15209Z","iopub.status.idle":"2023-06-26T18:16:35.162584Z","shell.execute_reply.started":"2023-06-26T18:16:35.152061Z","shell.execute_reply":"2023-06-26T18:16:35.158539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = models[\"Transfer learning\"].predict(test)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T18:37:25.776702Z","iopub.execute_input":"2023-06-26T18:37:25.777097Z","iopub.status.idle":"2023-06-26T19:05:58.634161Z","shell.execute_reply.started":"2023-06-26T18:37:25.777061Z","shell.execute_reply":"2023-06-26T19:05:58.633107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n\ny_pred_binary = np.squeeze(np.round(y_pred)).astype(int)\ny_pred_binary","metadata":{"execution":{"iopub.status.busy":"2023-06-26T19:05:58.636403Z","iopub.execute_input":"2023-06-26T19:05:58.636772Z","iopub.status.idle":"2023-06-26T19:05:58.646525Z","shell.execute_reply.started":"2023-06-26T19:05:58.636736Z","shell.execute_reply":"2023-06-26T19:05:58.645697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_proba = models[\"Transfer learning\"].predict_proba(test)","metadata":{"execution":{"iopub.status.busy":"2023-06-26T19:05:58.648086Z","iopub.execute_input":"2023-06-26T19:05:58.648651Z","iopub.status.idle":"2023-06-26T19:05:58.702364Z","shell.execute_reply.started":"2023-06-26T19:05:58.648611Z","shell.execute_reply":"2023-06-26T19:05:58.701124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_proba[:,0]","metadata":{"execution":{"iopub.status.busy":"2023-06-26T19:05:58.703484Z","iopub.status.idle":"2023-06-26T19:05:58.704269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}