{"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":"markdown","source":"##### Transfer learning model - ResNet50","metadata":{}},{"cell_type":"code","source":"pip install plot-keras-history","metadata":{"execution":{"iopub.status.busy":"2023-06-27T09:56:32.106631Z","iopub.execute_input":"2023-06-27T09:56:32.106984Z","iopub.status.idle":"2023-06-27T09:56:49.758617Z","shell.execute_reply.started":"2023-06-27T09:56:32.106949Z","shell.execute_reply":"2023-06-27T09:56:49.757119Z"},"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-27T09:57:04.705323Z","iopub.execute_input":"2023-06-27T09:57:04.705671Z","iopub.status.idle":"2023-06-27T09:57:10.244527Z","shell.execute_reply.started":"2023-06-27T09:57:04.705636Z","shell.execute_reply":"2023-06-27T09:57:10.243638Z"},"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-27T09:57:13.870271Z","iopub.execute_input":"2023-06-27T09:57:13.870724Z","iopub.status.idle":"2023-06-27T09:59:31.750269Z","shell.execute_reply.started":"2023-06-27T09:57:13.870687Z","shell.execute_reply":"2023-06-27T09:59:31.749368Z"},"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-27T09:59:31.752163Z","iopub.execute_input":"2023-06-27T09:59:31.752629Z","iopub.status.idle":"2023-06-27T10:05:51.737743Z","shell.execute_reply.started":"2023-06-27T09:59:31.752593Z","shell.execute_reply":"2023-06-27T10:05:51.736676Z"},"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-27T10:05:51.739211Z","iopub.execute_input":"2023-06-27T10:05:51.739605Z","iopub.status.idle":"2023-06-27T10:14:15.999307Z","shell.execute_reply.started":"2023-06-27T10:05:51.739562Z","shell.execute_reply":"2023-06-27T10:14:15.998438Z"},"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-27T10:14:16.000862Z","iopub.execute_input":"2023-06-27T10:14:16.001372Z","iopub.status.idle":"2023-06-27T10:14:16.007082Z","shell.execute_reply.started":"2023-06-27T10:14:16.001309Z","shell.execute_reply":"2023-06-27T10:14:16.006022Z"},"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.ResNet50(**arguments)\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2023-06-27T10:14:21.816502Z","iopub.execute_input":"2023-06-27T10:14:21.81688Z","iopub.status.idle":"2023-06-27T10:14:24.668151Z","shell.execute_reply.started":"2023-06-27T10:14:21.816842Z","shell.execute_reply":"2023-06-27T10:14:24.666997Z"},"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-27T10:14:31.646504Z","iopub.execute_input":"2023-06-27T10:14:31.646943Z","iopub.status.idle":"2023-06-27T10:14:31.65898Z","shell.execute_reply.started":"2023-06-27T10:14:31.646907Z","shell.execute_reply":"2023-06-27T10:14:31.658044Z"},"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-27T10:14:34.065956Z","iopub.execute_input":"2023-06-27T10:14:34.066357Z","iopub.status.idle":"2023-06-27T10:14:34.075526Z","shell.execute_reply.started":"2023-06-27T10:14:34.066319Z","shell.execute_reply":"2023-06-27T10:14:34.074461Z"},"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-27T10:14:36.363057Z","iopub.execute_input":"2023-06-27T10:14:36.365897Z","iopub.status.idle":"2023-06-27T10:14:36.39705Z","shell.execute_reply.started":"2023-06-27T10:14:36.365843Z","shell.execute_reply":"2023-06-27T10:14:36.39598Z"},"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-27T10:14:39.071465Z","iopub.execute_input":"2023-06-27T10:14:39.071856Z","iopub.status.idle":"2023-06-27T10:14:39.176274Z","shell.execute_reply.started":"2023-06-27T10:14:39.071818Z","shell.execute_reply":"2023-06-27T10:14:39.175492Z"},"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-27T10:14:49.14325Z","iopub.execute_input":"2023-06-27T10:14:49.143686Z","iopub.status.idle":"2023-06-27T10:14:49.148634Z","shell.execute_reply.started":"2023-06-27T10:14:49.14365Z","shell.execute_reply":"2023-06-27T10:14:49.14741Z"},"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-27T10:15:05.660711Z","iopub.execute_input":"2023-06-27T10:15:05.661095Z","iopub.status.idle":"2023-06-27T10:15:05.713644Z","shell.execute_reply.started":"2023-06-27T10:15:05.661061Z","shell.execute_reply":"2023-06-27T10:15:05.712642Z"},"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-27T10:15:14.135146Z","iopub.execute_input":"2023-06-27T10:15:14.135584Z","iopub.status.idle":"2023-06-27T14:48:54.101514Z","shell.execute_reply.started":"2023-06-27T10:15:14.135531Z","shell.execute_reply":"2023-06-27T14:48:54.100543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" models['Transfer learning'].save('/kaggle/working/model-ResNet50-TransferLearning.h5')","metadata":{"execution":{"iopub.status.busy":"2023-06-27T14:48:54.104694Z","iopub.execute_input":"2023-06-27T14:48:54.105151Z","iopub.status.idle":"2023-06-27T14:48:55.05847Z","shell.execute_reply.started":"2023-06-27T14:48:54.105106Z","shell.execute_reply":"2023-06-27T14:48:55.057297Z"},"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-27T14:55:30.017699Z","iopub.execute_input":"2023-06-27T14:55:30.018149Z","iopub.status.idle":"2023-06-27T14:55:32.113962Z","shell.execute_reply.started":"2023-06-27T14:55:30.018107Z","shell.execute_reply":"2023-06-27T14:55:32.112711Z"},"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-27T14:55:46.598338Z","iopub.execute_input":"2023-06-27T14:55:46.598733Z","iopub.status.idle":"2023-06-27T16:05:03.352416Z","shell.execute_reply.started":"2023-06-27T14:55:46.598695Z","shell.execute_reply":"2023-06-27T16:05:03.351541Z"},"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-27T16:05:03.354904Z","iopub.execute_input":"2023-06-27T16:05:03.355565Z","iopub.status.idle":"2023-06-27T16:05:03.362168Z","shell.execute_reply.started":"2023-06-27T16:05:03.355516Z","shell.execute_reply":"2023-06-27T16:05:03.360767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = models[\"Transfer learning\"].predict(test)","metadata":{"execution":{"iopub.status.busy":"2023-06-27T16:12:36.227969Z","iopub.execute_input":"2023-06-27T16:12:36.228419Z","iopub.status.idle":"2023-06-27T16:42:09.880233Z","shell.execute_reply.started":"2023-06-27T16:12:36.228377Z","shell.execute_reply":"2023-06-27T16:42:09.879089Z"},"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-27T16:42:09.882436Z","iopub.execute_input":"2023-06-27T16:42:09.882868Z","iopub.status.idle":"2023-06-27T16:42:09.894342Z","shell.execute_reply.started":"2023-06-27T16:42:09.882829Z","shell.execute_reply":"2023-06-27T16:42:09.8932Z"},"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":[]}]}