{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n#import os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n    #for filename in filenames:\n        #print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-08-09T14:47:43.150840Z","iopub.execute_input":"2021-08-09T14:47:43.151244Z","iopub.status.idle":"2021-08-09T14:47:43.157021Z","shell.execute_reply.started":"2021-08-09T14:47:43.151207Z","shell.execute_reply":"2021-08-09T14:47:43.155806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pwd","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:47:45.703481Z","iopub.execute_input":"2021-08-09T14:47:45.703847Z","iopub.status.idle":"2021-08-09T14:47:46.483553Z","shell.execute_reply.started":"2021-08-09T14:47:45.703812Z","shell.execute_reply":"2021-08-09T14:47:46.482368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 1.Importar Librerías necesarias","metadata":{}},{"cell_type":"code","source":"from tensorflow import keras\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom glob import glob\nfrom tqdm.notebook import tqdm\nfrom ast import literal_eval\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rcParams.update({'font.size': 22})\nfrom sklearn.metrics import accuracy_score\nfrom skimage import exposure\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import plot_model\nimport cv2\nfrom matplotlib.patches import Rectangle\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50, DenseNet121\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import models\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\nimport tensorflow.keras.backend as K\nfrom tensorflow.math import confusion_matrix\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\nimport os\nimport glob\nimport shutil\nimport sys\nimport numpy as np\nfrom skimage.io import imread\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\nfrom keras.applications import Xception\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:47:51.917700Z","iopub.execute_input":"2021-08-09T14:47:51.918054Z","iopub.status.idle":"2021-08-09T14:47:56.954063Z","shell.execute_reply.started":"2021-08-09T14:47:51.918018Z","shell.execute_reply":"2021-08-09T14:47:56.953222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pwd","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:01.410929Z","iopub.execute_input":"2021-08-09T14:48:01.411268Z","iopub.status.idle":"2021-08-09T14:48:01.418778Z","shell.execute_reply.started":"2021-08-09T14:48:01.411238Z","shell.execute_reply":"2021-08-09T14:48:01.417848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import os\n#import glob\n\n#files = glob.glob('/kaggle/working/*')\n#for f in files:\n    #os.remove(f)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T15:29:19.896606Z","iopub.execute_input":"2021-08-08T15:29:19.896936Z","iopub.status.idle":"2021-08-08T15:29:21.44799Z","shell.execute_reply.started":"2021-08-08T15:29:19.896888Z","shell.execute_reply":"2021-08-08T15:29:21.447076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Cargar los datos (Ficheros csv, y carpetas ficheros de imágenes) Exploración y preparación de datos","metadata":{}},{"cell_type":"code","source":"df_image = pd.read_csv('../input/siim-covid19-detection/train_image_level.csv')\ndisplay(df_image.head(3))\nprint(df_image.shape)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:15.621669Z","iopub.execute_input":"2021-08-09T14:48:15.621996Z","iopub.status.idle":"2021-08-09T14:48:15.684044Z","shell.execute_reply.started":"2021-08-09T14:48:15.621966Z","shell.execute_reply":"2021-08-09T14:48:15.683126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study = pd.read_csv('../input/siim-covid19-detection/train_study_level.csv')\ndisplay(df_study.head(3))\nprint(df_study.shape)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:18.457273Z","iopub.execute_input":"2021-08-09T14:48:18.457591Z","iopub.status.idle":"2021-08-09T14:48:18.479690Z","shell.execute_reply.started":"2021-08-09T14:48:18.457562Z","shell.execute_reply":"2021-08-09T14:48:18.478650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sampleSub = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\ndisplay(df_sampleSub.head(3))\nprint(df_sampleSub.shape)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:21.472759Z","iopub.execute_input":"2021-08-09T14:48:21.473080Z","iopub.status.idle":"2021-08-09T14:48:21.491821Z","shell.execute_reply.started":"2021-08-09T14:48:21.473048Z","shell.execute_reply":"2021-08-09T14:48:21.491077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study['id'] = df_study['id'].str.replace('_study',\"\")\ndf_study.rename({'id': 'StudyInstanceUID'},axis=1, inplace=True)\ndf_study.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:24.217484Z","iopub.execute_input":"2021-08-09T14:48:24.217823Z","iopub.status.idle":"2021-08-09T14:48:24.239837Z","shell.execute_reply.started":"2021-08-09T14:48:24.217791Z","shell.execute_reply":"2021-08-09T14:48:24.238998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_image.merge(df_study, on='StudyInstanceUID')\ndf_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:27.060564Z","iopub.execute_input":"2021-08-09T14:48:27.060891Z","iopub.status.idle":"2021-08-09T14:48:27.087684Z","shell.execute_reply.started":"2021-08-09T14:48:27.060861Z","shell.execute_reply":"2021-08-09T14:48:27.086990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.loc[df_train['Negative for Pneumonia']==1, 'study_label'] = 'negative'\ndf_train.loc[df_train['Typical Appearance']==1, 'study_label'] = 'typical'\ndf_train.loc[df_train['Indeterminate Appearance']==1, 'study_label'] = 'indeterminate'\ndf_train.loc[df_train['Atypical Appearance']==1, 'study_label'] = 'atypical'\ndf_train.drop(['Negative for Pneumonia','Typical Appearance', 'Indeterminate Appearance', 'Atypical Appearance'], axis=1, inplace=True)\ndf_train['id'] = df_train['id'].str.replace('_image', '.jpg')\ndf_train['image_label'] = df_train['label'].str.split().apply(lambda x : x[0])\ndf_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:30.096752Z","iopub.execute_input":"2021-08-09T14:48:30.097069Z","iopub.status.idle":"2021-08-09T14:48:30.303883Z","shell.execute_reply.started":"2021-08-09T14:48:30.097039Z","shell.execute_reply":"2021-08-09T14:48:30.303105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:33.624428Z","iopub.execute_input":"2021-08-09T14:48:33.624792Z","iopub.status.idle":"2021-08-09T14:48:33.630303Z","shell.execute_reply.started":"2021-08-09T14:48:33.624760Z","shell.execute_reply":"2021-08-09T14:48:33.629235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_size = pd.read_csv('/kaggle/input/covid-jpg-512/size.csv')\ndf_size.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:37.285407Z","iopub.execute_input":"2021-08-09T14:48:37.285734Z","iopub.status.idle":"2021-08-09T14:48:37.316043Z","shell.execute_reply.started":"2021-08-09T14:48:37.285701Z","shell.execute_reply":"2021-08-09T14:48:37.315294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_train.merge(df_size, on='id')\ndf_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:40.694810Z","iopub.execute_input":"2021-08-09T14:48:40.695201Z","iopub.status.idle":"2021-08-09T14:48:40.718699Z","shell.execute_reply.started":"2021-08-09T14:48:40.695150Z","shell.execute_reply":"2021-08-09T14:48:40.717733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Vamos a realizar el mismo análisis pero con tres variables de salida. Tomado como referencia la variable \"study_label\" clasificamos como negativo, tipico (neumonía) y el resto creamos clase otros","metadata":{}},{"cell_type":"code","source":"def map_values(row, values_dict):\n    return values_dict[row]\n\nvalues_dict = {'typical': 'Yes', 'negative': 'None', 'indeterminate': 'otros', 'atypical': 'otros'}\n\ndf_train['label_opacity'] = df_train['study_label'].apply(map_values, args = (values_dict,))\n\n","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:45.519160Z","iopub.execute_input":"2021-08-09T14:48:45.519526Z","iopub.status.idle":"2021-08-09T14:48:45.528399Z","shell.execute_reply.started":"2021-08-09T14:48:45.519494Z","shell.execute_reply":"2021-08-09T14:48:45.527448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:49.531710Z","iopub.execute_input":"2021-08-09T14:48:49.532021Z","iopub.status.idle":"2021-08-09T14:48:49.545824Z","shell.execute_reply.started":"2021-08-09T14:48:49.531992Z","shell.execute_reply":"2021-08-09T14:48:49.545019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(df_train))","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:53.332402Z","iopub.execute_input":"2021-08-09T14:48:53.332757Z","iopub.status.idle":"2021-08-09T14:48:53.337778Z","shell.execute_reply.started":"2021-08-09T14:48:53.332724Z","shell.execute_reply":"2021-08-09T14:48:53.336670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.groupby(['label_opacity']).size().reset_index(name='Nuevas clases')","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:48:57.032271Z","iopub.execute_input":"2021-08-09T14:48:57.032598Z","iopub.status.idle":"2021-08-09T14:48:57.049150Z","shell.execute_reply.started":"2021-08-09T14:48:57.032570Z","shell.execute_reply":"2021-08-09T14:48:57.048079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, os.path\n\nDIR = '../input/covid-jpg-512/train'\nprint (len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]))","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:49:00.594408Z","iopub.execute_input":"2021-08-09T14:49:00.594770Z","iopub.status.idle":"2021-08-09T14:49:08.862424Z","shell.execute_reply.started":"2021-08-09T14:49:00.594737Z","shell.execute_reply":"2021-08-09T14:49:08.860979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nruta_test=\"/kaggle/input/covid-jpg-512/test\"\nruta_train=\"/kaggle/input/covid-jpg-512/train\"\ntest_img=[]\ntrain_img=[]\nimg_size=224\n\nfor img in os.listdir(ruta_train):\n  img = cv2.imread(os.path.join(ruta_train,img))\n  img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n  img_gray_resize=cv2.resize(img_gray,(img_size,img_size))\n  train_img.append([img_gray_resize])\n\nprint(len(train_img))","metadata":{"execution":{"iopub.status.busy":"2021-08-09T10:49:53.847878Z","iopub.execute_input":"2021-08-09T10:49:53.848259Z","iopub.status.idle":"2021-08-09T10:50:45.7233Z","shell.execute_reply.started":"2021-08-09T10:49:53.848227Z","shell.execute_reply":"2021-08-09T10:50:45.722446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure()\nplt.imshow(np.squeeze(train_img[10]))\nplt.colorbar()\nplt.grid(False)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T10:50:51.209877Z","iopub.execute_input":"2021-08-09T10:50:51.210225Z","iopub.status.idle":"2021-08-09T10:50:51.466769Z","shell.execute_reply.started":"2021-08-09T10:50:51.210193Z","shell.execute_reply":"2021-08-09T10:50:51.46595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for img in os.listdir(ruta_test):\n  img = cv2.imread(os.path.join(ruta_test,img))\n  img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n  img_gray_resize=cv2.resize(img_gray,(img_size,img_size))\n  test_img.append([img_gray_resize])\n\nprint(len(test_img))","metadata":{"execution":{"iopub.status.busy":"2021-08-09T10:50:55.013253Z","iopub.execute_input":"2021-08-09T10:50:55.013593Z","iopub.status.idle":"2021-08-09T10:51:06.140635Z","shell.execute_reply.started":"2021-08-09T10:50:55.013564Z","shell.execute_reply":"2021-08-09T10:51:06.139561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure()\nplt.imshow(np.squeeze(test_img[10]))\nplt.colorbar()\nplt.grid(False)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T10:51:09.22224Z","iopub.execute_input":"2021-08-09T10:51:09.222618Z","iopub.status.idle":"2021-08-09T10:51:09.459547Z","shell.execute_reply.started":"2021-08-09T10:51:09.222587Z","shell.execute_reply":"2021-08-09T10:51:09.458579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3. Visualición imágenes train con cajas que identifican las anomalías.","metadata":{}},{"cell_type":"code","source":"n = 20\ntrain_dir = '/kaggle/input/covid-jpg-512/train'\nfig, axs = plt.subplots(4, 5, figsize=(20,20))\nfig.subplots_adjust(hspace=.2, wspace=.2)\naxs = axs.ravel()\nfor i in range(n):\n    img = cv2.imread(os.path.join(train_dir, df_train['id'][i]))\n    axs[i].imshow(img)\n    if type(df_train['boxes'][i])==str:\n        boxes = literal_eval(df_train['boxes'][i])\n        for box in boxes:\n            axs[i].add_patch(Rectangle((box['x']*(512/df_train['dim1'][i]), box['y']*(512/df_train['dim0'][i])), box['width']*(512/df_train['dim1'][i]), box['height']*(512/df_train['dim0'][i]), fill=0, color='y', linewidth=2))\n            axs[i].set_title(df_train['study_label'][i])\n    else:\n        axs[i].set_title(df_train['study_label'][i])","metadata":{"execution":{"iopub.status.busy":"2021-08-09T10:51:15.216069Z","iopub.execute_input":"2021-08-09T10:51:15.216427Z","iopub.status.idle":"2021-08-09T10:51:18.641204Z","shell.execute_reply.started":"2021-08-09T10:51:15.216396Z","shell.execute_reply":"2021-08-09T10:51:18.640465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Tratamiento de las imágenes y partición de datos en Train y Validación","metadata":{}},{"cell_type":"code","source":"def preprocess_image(img):\n  equ_img = exposure.equalize_hist(img)\n  return equ_img\n\nim= cv2.imread('/kaggle/input/covid-jpg-512/train/000a312787f2.jpg')\nim2 = preprocess_image(im)\nres = np.concatenate((im/255, im2), axis=1)\nplt.imshow(res)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:51:22.700466Z","iopub.execute_input":"2021-08-09T14:51:22.700786Z","iopub.status.idle":"2021-08-09T14:51:22.975087Z","shell.execute_reply.started":"2021-08-09T14:51:22.700758Z","shell.execute_reply":"2021-08-09T14:51:22.974257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_size = 224\nbatch_size = 16\n\nimage_generator = ImageDataGenerator(\n        validation_split=0.2,\n        #rotation_range=20,\n        horizontal_flip = True,\n        zoom_range = 0.1,\n        #shear_range = 0.1,\n        brightness_range = [0.8, 1.1],\n        fill_mode='nearest',\n        preprocessing_function=preprocess_image\n)\n\nimage_generator_valid = ImageDataGenerator(validation_split=0.2,preprocessing_function=preprocess_image)\n\ntrain_generator = image_generator.flow_from_dataframe(\n        dataframe = df_train,\n        directory='../input/covid-jpg-512/train',\n        x_col = 'id',\n        y_col =  'label_opacity',\n        target_size=(img_size, img_size),\n        batch_size=batch_size,\n        subset='training', seed = 10) \n\nvalid_generator=image_generator_valid.flow_from_dataframe(\n    dataframe = df_train,\n    directory='../input/covid-jpg-512/train',\n    x_col = 'id',\n    y_col = 'label_opacity',\n    target_size=(img_size, img_size),\n    batch_size=batch_size,\n    subset='validation', shuffle=False,  seed=10) \n\n","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:51:27.043054Z","iopub.execute_input":"2021-08-09T14:51:27.043427Z","iopub.status.idle":"2021-08-09T14:51:29.159001Z","shell.execute_reply.started":"2021-08-09T14:51:27.043394Z","shell.execute_reply":"2021-08-09T14:51:29.158119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = Xception(weights=None,input_shape=(img_size,img_size,3), include_top=False)\nbase_model.load_weights('../input/keras-pretrained-models/xception_weights_tf_dim_ordering_tf_kernels_notop.h5')\nbase_out = base_model.output\navg = keras.layers.GlobalAveragePooling2D()(base_out)\nbath=keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001)(avg)\noutput = keras.layers.Dense(3, activation=\"softmax\")(bath) \nmodel = keras.Model(inputs=base_model.input, outputs=output)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T11:15:05.985401Z","iopub.execute_input":"2021-08-09T11:15:05.985749Z","iopub.status.idle":"2021-08-09T11:15:08.647579Z","shell.execute_reply.started":"2021-08-09T11:15:05.985702Z","shell.execute_reply":"2021-08-09T11:15:08.646634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in base_model.layers: \n    layer.trainable = False\n    \noptimizer = keras.optimizers.Nadam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, name=\"Nadam\")\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])\nhistory = model.fit_generator(train_generator, validation_data=valid_generator, epochs=10)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T17:42:52.529732Z","iopub.execute_input":"2021-08-08T17:42:52.530087Z","iopub.status.idle":"2021-08-08T18:22:14.973698Z","shell.execute_reply.started":"2021-08-08T17:42:52.530042Z","shell.execute_reply":"2021-08-08T18:22:14.972767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Congelamos los peso del modelo base para sacar el máximo partido del modelo preentrenado\nfor layer in base_model.layers: \n    layer.trainable = True\n\n#Importo EarlyStopping\nfrom keras.callbacks import EarlyStopping\ncallback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n    \noptimizer = keras.optimizers.Nadam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, name=\"Nadam\")\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])\nhistory = model.fit_generator(train_generator, validation_data=valid_generator, epochs=30,callbacks=[callback],verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T18:22:14.975645Z","iopub.execute_input":"2021-08-08T18:22:14.97605Z","iopub.status.idle":"2021-08-08T18:22:14.981954Z","shell.execute_reply.started":"2021-08-08T18:22:14.976008Z","shell.execute_reply":"2021-08-08T18:22:14.98106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"actual =  valid_generator.labels\npreds = np.argmax(model.predict(valid_generator), axis=1)\ncfmx = confusion_matrix(actual, preds)\nacc = accuracy_score(actual, preds)\nprint ('Test Accuracy:', acc )\nprint('Confusion matrix:', cfmx)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs(\"./models\", exist_ok=True)\nmodel.save('./models/model_3labels_xception_2.h5')","metadata":{"execution":{"iopub.status.busy":"2021-08-07T19:32:12.667541Z","iopub.execute_input":"2021-08-07T19:32:12.66786Z","iopub.status.idle":"2021-08-07T19:32:13.415203Z","shell.execute_reply.started":"2021-08-07T19:32:12.66783Z","shell.execute_reply":"2021-08-07T19:32:13.41435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\nmodel = load_model(\"../input/modelo-creado-3-labels/model_3labels_xception.h5\")","metadata":{"execution":{"iopub.status.busy":"2021-08-09T14:50:45.755880Z","iopub.execute_input":"2021-08-09T14:50:45.756217Z","iopub.status.idle":"2021-08-09T14:50:54.205196Z","shell.execute_reply.started":"2021-08-09T14:50:45.756186Z","shell.execute_reply":"2021-08-09T14:50:54.204286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = np.argmax(model.predict(valid_generator), axis=1)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T15:54:43.971282Z","iopub.execute_input":"2021-08-09T15:54:43.971599Z","iopub.status.idle":"2021-08-09T15:54:54.785338Z","shell.execute_reply.started":"2021-08-09T15:54:43.971570Z","shell.execute_reply":"2021-08-09T15:54:54.784537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds.shape","metadata":{"execution":{"iopub.status.busy":"2021-08-09T15:54:56.562187Z","iopub.execute_input":"2021-08-09T15:54:56.562546Z","iopub.status.idle":"2021-08-09T15:54:56.568891Z","shell.execute_reply.started":"2021-08-09T15:54:56.562514Z","shell.execute_reply":"2021-08-09T15:54:56.567715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}}]}