{"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 - Sobel Filter","metadata":{}},{"cell_type":"code","source":"pip install plot-keras-history","metadata":{"execution":{"iopub.status.busy":"2023-07-06T18:17:33.513743Z","iopub.execute_input":"2023-07-06T18:17:33.514033Z","iopub.status.idle":"2023-07-06T18:17:49.641493Z","shell.execute_reply.started":"2023-07-06T18:17:33.514004Z","shell.execute_reply":"2023-07-06T18:17:49.639826Z"},"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-07-06T18:17:49.644129Z","iopub.execute_input":"2023-07-06T18:17:49.644838Z","iopub.status.idle":"2023-07-06T18:17:54.775111Z","shell.execute_reply.started":"2023-07-06T18:17:49.644796Z","shell.execute_reply":"2023-07-06T18:17:54.774092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-filtro-sobel/data_filtro_Sobel/train')","metadata":{"execution":{"iopub.status.busy":"2023-07-06T18:17:54.776815Z","iopub.execute_input":"2023-07-06T18:17:54.777234Z","iopub.status.idle":"2023-07-06T18:19:11.464785Z","shell.execute_reply.started":"2023-07-06T18:17:54.777195Z","shell.execute_reply":"2023-07-06T18:19:11.463784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-filtro-sobel/data_filtro_Sobel/valid')","metadata":{"execution":{"iopub.status.busy":"2023-07-06T18:19:11.466057Z","iopub.execute_input":"2023-07-06T18:19:11.466422Z","iopub.status.idle":"2023-07-06T18:21:29.460541Z","shell.execute_reply.started":"2023-07-06T18:19:11.46638Z","shell.execute_reply":"2023-07-06T18:21:29.459638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = keras.preprocessing.image_dataset_from_directory(directory = '/kaggle/input/data-filtro-sobel/data_filtro_Sobel/test', shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-07-06T18:21:29.464033Z","iopub.execute_input":"2023-07-06T18:21:29.464392Z","iopub.status.idle":"2023-07-06T18:25:58.862381Z","shell.execute_reply.started":"2023-07-06T18:21:29.464357Z","shell.execute_reply":"2023-07-06T18:25:58.861573Z"},"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-07-06T18:25:58.864729Z","iopub.execute_input":"2023-07-06T18:25:58.865015Z","iopub.status.idle":"2023-07-06T18:25:58.869652Z","shell.execute_reply.started":"2023-07-06T18:25:58.864987Z","shell.execute_reply":"2023-07-06T18:25:58.868709Z"},"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-07-06T18:25:58.870957Z","iopub.execute_input":"2023-07-06T18:25:58.871534Z","iopub.status.idle":"2023-07-06T18:26:03.581491Z","shell.execute_reply.started":"2023-07-06T18:25:58.871486Z","shell.execute_reply":"2023-07-06T18:26:03.580502Z"},"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-07-06T18:26:03.582952Z","iopub.execute_input":"2023-07-06T18:26:03.58332Z","iopub.status.idle":"2023-07-06T18:26:03.597358Z","shell.execute_reply.started":"2023-07-06T18:26:03.583282Z","shell.execute_reply":"2023-07-06T18:26:03.596647Z"},"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-07-06T18:26:03.598525Z","iopub.execute_input":"2023-07-06T18:26:03.599046Z","iopub.status.idle":"2023-07-06T18:26:03.609313Z","shell.execute_reply.started":"2023-07-06T18:26:03.599004Z","shell.execute_reply":"2023-07-06T18:26:03.608341Z"},"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-07-06T18:26:03.610541Z","iopub.execute_input":"2023-07-06T18:26:03.610928Z","iopub.status.idle":"2023-07-06T18:26:03.633476Z","shell.execute_reply.started":"2023-07-06T18:26:03.610889Z","shell.execute_reply":"2023-07-06T18:26:03.632834Z"},"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-07-06T18:26:03.634584Z","iopub.execute_input":"2023-07-06T18:26:03.634949Z","iopub.status.idle":"2023-07-06T18:26:03.718942Z","shell.execute_reply.started":"2023-07-06T18:26:03.634907Z","shell.execute_reply":"2023-07-06T18:26:03.71822Z"},"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-07-06T18:26:03.722987Z","iopub.execute_input":"2023-07-06T18:26:03.723254Z","iopub.status.idle":"2023-07-06T18:26:03.7321Z","shell.execute_reply.started":"2023-07-06T18:26:03.723228Z","shell.execute_reply":"2023-07-06T18:26:03.731043Z"},"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-07-06T18:26:03.73314Z","iopub.execute_input":"2023-07-06T18:26:03.733513Z","iopub.status.idle":"2023-07-06T18:26:03.790482Z","shell.execute_reply.started":"2023-07-06T18:26:03.733469Z","shell.execute_reply":"2023-07-06T18:26:03.789792Z"},"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-07-06T18:26:03.794505Z","iopub.execute_input":"2023-07-06T18:26:03.794798Z","iopub.status.idle":"2023-07-06T21:33:47.963773Z","shell.execute_reply.started":"2023-07-06T18:26:03.794773Z","shell.execute_reply":"2023-07-06T21:33:47.962894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" models['Transfer learning'].save('/kaggle/working/model-ResNet50-Sobel-TransferLearning.h5')","metadata":{"execution":{"iopub.status.busy":"2023-07-06T21:33:47.965896Z","iopub.execute_input":"2023-07-06T21:33:47.9662Z","iopub.status.idle":"2023-07-06T21:33:48.8259Z","shell.execute_reply.started":"2023-07-06T21:33:47.966169Z","shell.execute_reply":"2023-07-06T21:33:48.824848Z"},"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-07-06T21:33:48.830834Z","iopub.execute_input":"2023-07-06T21:33:48.831202Z","iopub.status.idle":"2023-07-06T21:33:50.638301Z","shell.execute_reply.started":"2023-07-06T21:33:48.83116Z","shell.execute_reply":"2023-07-06T21:33:50.63729Z"},"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-07-06T21:33:50.639473Z","iopub.execute_input":"2023-07-06T21:33:50.639855Z","iopub.status.idle":"2023-07-06T22:21:55.465424Z","shell.execute_reply.started":"2023-07-06T21:33:50.639815Z","shell.execute_reply":"2023-07-06T22:21:55.464629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"test loss, test auc, test precision, test recall:, test binary accuracy:\", results)","metadata":{"execution":{"iopub.status.busy":"2023-07-06T22:44:58.752473Z","iopub.execute_input":"2023-07-06T22:44:58.752877Z","iopub.status.idle":"2023-07-06T22:44:58.757936Z","shell.execute_reply.started":"2023-07-06T22:44:58.752843Z","shell.execute_reply":"2023-07-06T22:44:58.756552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = models[\"Transfer learning\"].predict(test)","metadata":{"execution":{"iopub.status.busy":"2023-07-06T22:21:55.474085Z","iopub.execute_input":"2023-07-06T22:21:55.474864Z","iopub.status.idle":"2023-07-06T22:40:59.851068Z","shell.execute_reply.started":"2023-07-06T22:21:55.474826Z","shell.execute_reply":"2023-07-06T22:40:59.850053Z"},"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-07-06T22:40:59.853666Z","iopub.execute_input":"2023-07-06T22:40:59.85421Z","iopub.status.idle":"2023-07-06T22:40:59.862695Z","shell.execute_reply.started":"2023-07-06T22:40:59.854167Z","shell.execute_reply":"2023-07-06T22:40:59.861778Z"},"trusted":true},"execution_count":null,"outputs":[]}]}