{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":11848,"databundleVersionId":862157,"sourceType":"competition"}],"dockerImageVersionId":30009,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Importing  Libraries\nfrom numpy.random import seed\nseed(101)\n\nimport pandas as pd\nimport numpy as np\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Activation\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.optimizers import Adam\n\nimport os\nimport cv2\n\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nimport itertools\nimport shutil\nimport matplotlib.pyplot as plt\n%matplotlib inline\ntf.random.set_seed(101)","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2024-08-05T17:58:31.044283Z","iopub.execute_input":"2024-08-05T17:58:31.044606Z","iopub.status.idle":"2024-08-05T17:58:36.520501Z","shell.execute_reply.started":"2024-08-05T17:58:31.044572Z","shell.execute_reply":"2024-08-05T17:58:36.519660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Setting Some Pre-Requisites\nIMAGE_SIZE=96\nIMAGE_CHANNELS=3\nSAMPLE_SIZE=80000         # We will be training 80,000 samples from each label","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:58:41.707247Z","iopub.execute_input":"2024-08-05T17:58:41.707600Z","iopub.status.idle":"2024-08-05T17:58:41.711504Z","shell.execute_reply.started":"2024-08-05T17:58:41.707567Z","shell.execute_reply":"2024-08-05T17:58:41.710769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# So, what are the files which are available?\n\nos.listdir('../input/histopathologic-cancer-detection')","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:58:46.200247Z","iopub.execute_input":"2024-08-05T17:58:46.200584Z","iopub.status.idle":"2024-08-05T17:58:46.208456Z","shell.execute_reply.started":"2024-08-05T17:58:46.200554Z","shell.execute_reply":"2024-08-05T17:58:46.207563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# So, how many images are there in each of the folder in the training dataset?\n\nprint(len(os.listdir('../input/histopathologic-cancer-detection/train')))\nprint(len(os.listdir('../input/histopathologic-cancer-detection/test')))","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:58:51.320398Z","iopub.execute_input":"2024-08-05T17:58:51.320773Z","iopub.status.idle":"2024-08-05T17:59:15.810265Z","shell.execute_reply.started":"2024-08-05T17:58:51.320736Z","shell.execute_reply":"2024-08-05T17:59:15.809477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating a dataframe of all the training images\n\ndf_data = pd.read_csv('../input/histopathologic-cancer-detection/train_labels.csv')\n\n# removing this image because it caused a training error previously\ndf_data[df_data['id'] != 'dd6dfed324f9fcb6f93f46f32fc800f2ec196be2']\n\n# removing this image because it's black\ndf_data[df_data['id'] != '9369c7278ec8bcc6c880d99194de09fc2bd4efbe']\n\n\nprint(df_data.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:59:23.499831Z","iopub.execute_input":"2024-08-05T17:59:23.500188Z","iopub.status.idle":"2024-08-05T17:59:23.939362Z","shell.execute_reply.started":"2024-08-05T17:59:23.500153Z","shell.execute_reply":"2024-08-05T17:59:23.938535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_data['label'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:59:39.639805Z","iopub.execute_input":"2024-08-05T17:59:39.640177Z","iopub.status.idle":"2024-08-05T17:59:39.652195Z","shell.execute_reply.started":"2024-08-05T17:59:39.640141Z","shell.execute_reply":"2024-08-05T17:59:39.651265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# source: https://www.kaggle.com/gpreda/honey-bee-subspecies-classification\n\ndef draw_category_images(col_name,figure_cols, df, IMAGE_PATH):\n    \n    \"\"\"\n    Give a column in a dataframe,\n    this function takes a sample of each class and displays that\n    sample on one row. The sample size is the same as figure_cols which\n    is the number of columns in the figure.\n    Because this function takes a random sample, each time the function is run it\n    displays different images.\n    \"\"\"\n    \n\n    categories = (df.groupby([col_name])[col_name].nunique()).index\n    f, ax = plt.subplots(nrows=len(categories),ncols=figure_cols, \n                         figsize=(4*figure_cols,4*len(categories))) # adjust size here\n    # draw a number of images for each location\n    for i, cat in enumerate(categories):\n        sample = df[df[col_name]==cat].sample(figure_cols) # figure_cols is also the sample size\n        for j in range(0,figure_cols):\n            file=IMAGE_PATH + sample.iloc[j]['id'] + '.tif'\n            im=cv2.imread(file)\n            ax[i, j].imshow(im, resample=True, cmap='gray')\n            ax[i, j].set_title(cat, fontsize=16)  \n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:59:48.139516Z","iopub.execute_input":"2024-08-05T17:59:48.139868Z","iopub.status.idle":"2024-08-05T17:59:48.151876Z","shell.execute_reply.started":"2024-08-05T17:59:48.139838Z","shell.execute_reply":"2024-08-05T17:59:48.151010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_PATH = '../input/histopathologic-cancer-detection/train/' \n\ndraw_category_images('label',4, df_data, IMAGE_PATH)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T17:59:53.467088Z","iopub.execute_input":"2024-08-05T17:59:53.467486Z","iopub.status.idle":"2024-08-05T17:59:55.039363Z","shell.execute_reply.started":"2024-08-05T17:59:53.467449Z","shell.execute_reply":"2024-08-05T17:59:55.038024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the Train and Validation Sets\n\ndf_0=df_data[df_data['label']==0].sample(SAMPLE_SIZE,random_state=101)\ndf_1=df_data[df_data['label']==1].sample(SAMPLE_SIZE,random_state=101)\n\n# concat the dataframes\ndf_data = pd.concat([df_0, df_1], axis=0).reset_index(drop=True)\n# shuffle\ndf_data = shuffle(df_data)\n\ndf_data['label'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:01.144312Z","iopub.execute_input":"2024-08-05T18:00:01.144655Z","iopub.status.idle":"2024-08-05T18:00:01.211376Z","shell.execute_reply.started":"2024-08-05T18:00:01.144619Z","shell.execute_reply":"2024-08-05T18:00:01.210604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now, for the train-test split\n\n# stratify=y creates a balanced validation set.\ny = df_data['label']\n\ndf_train, df_val = train_test_split(df_data, test_size=0.10, random_state=101, stratify=y)\n\nprint(df_train.shape)\nprint(df_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:05.145853Z","iopub.execute_input":"2024-08-05T18:00:05.146189Z","iopub.status.idle":"2024-08-05T18:00:05.267617Z","shell.execute_reply.started":"2024-08-05T18:00:05.146161Z","shell.execute_reply":"2024-08-05T18:00:05.266720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a new directory so that we will be using the ImageDataGenerator\nbase_dir='base_dir'\nos.mkdir(base_dir)\n\n# now we create 2 folders inside 'base_dir':\n\n# train_dir\n    # a_no_tumor_tissue\n    # b_has_tumor_tissue\n\n# val_dir\n    # a_no_tumor_tissue\n    # b_has_tumor_tissue\n\n\n\n# create a path to 'base_dir' to which we will join the names of the new folders\n# train_dir\ntrain_dir = os.path.join(base_dir, 'train_dir')\nos.mkdir(train_dir)\n\n# val_dir\nval_dir = os.path.join(base_dir, 'val_dir')\nos.mkdir(val_dir)\n\n\n\n# [CREATE FOLDERS INSIDE THE TRAIN AND VALIDATION FOLDERS]\n# Inside each folder we create seperate folders for each class\n\n# create new folders inside train_dir\nno_tumor_tissue = os.path.join(train_dir, 'a_no_tumor_tissue')\nos.mkdir(no_tumor_tissue)\nhas_tumor_tissue = os.path.join(train_dir, 'b_has_tumor_tissue')\nos.mkdir(has_tumor_tissue)\n\n\n# create new folders inside val_dir\nno_tumor_tissue = os.path.join(val_dir, 'a_no_tumor_tissue')\nos.mkdir(no_tumor_tissue)\nhas_tumor_tissue = os.path.join(val_dir, 'b_has_tumor_tissue')\nos.mkdir(has_tumor_tissue)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:09.041188Z","iopub.execute_input":"2024-08-05T18:00:09.041545Z","iopub.status.idle":"2024-08-05T18:00:09.051538Z","shell.execute_reply.started":"2024-08-05T18:00:09.041510Z","shell.execute_reply":"2024-08-05T18:00:09.050567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check that the folders have been created\nos.listdir('base_dir/train_dir')","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:20.925584Z","iopub.execute_input":"2024-08-05T18:00:20.925960Z","iopub.status.idle":"2024-08-05T18:00:20.931867Z","shell.execute_reply.started":"2024-08-05T18:00:20.925926Z","shell.execute_reply":"2024-08-05T18:00:20.930797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set the id as the index in df_data\ndf_data.set_index('id', inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:26.846406Z","iopub.execute_input":"2024-08-05T18:00:26.846780Z","iopub.status.idle":"2024-08-05T18:00:26.862898Z","shell.execute_reply.started":"2024-08-05T18:00:26.846742Z","shell.execute_reply":"2024-08-05T18:00:26.862043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get a list of train and val images\ntrain_list = list(df_train['id'])\nval_list = list(df_val['id'])\n\n\n\n# Transfer the train images\n\nfor image in train_list:\n    \n    # the id in the csv file does not have the .tif extension therefore we add it here\n    fname = image + '.tif'\n    # get the label for a certain image\n    target = df_data.loc[image,'label']\n    \n    # these must match the folder names\n    if target == 0:\n        label = 'a_no_tumor_tissue'\n    if target == 1:\n        label = 'b_has_tumor_tissue'\n    \n    # source path to image\n    src = os.path.join('../input/histopathologic-cancer-detection/train', fname)\n    # destination path to image\n    dst = os.path.join(train_dir, label, fname)\n    # copy the image from the source to the destination\n    shutil.copyfile(src, dst)\n\n\n# Transfer the val images\n\nfor image in val_list:\n    \n    # the id in the csv file does not have the .tif extension therefore we add it here\n    fname = image + '.tif'\n    # get the label for a certain image\n    target = df_data.loc[image,'label']\n    \n    # these must match the folder names\n    if target == 0:\n        label = 'a_no_tumor_tissue'\n    if target == 1:\n        label = 'b_has_tumor_tissue'\n    \n\n    # source path to image\n    src = os.path.join('../input/histopathologic-cancer-detection/train', fname)\n    # destination path to image\n    dst = os.path.join(val_dir, label, fname)\n    # copy the image from the source to the destination\n    shutil.copyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:00:38.648121Z","iopub.execute_input":"2024-08-05T18:00:38.648488Z","iopub.status.idle":"2024-08-05T18:26:31.181844Z","shell.execute_reply.started":"2024-08-05T18:00:38.648452Z","shell.execute_reply":"2024-08-05T18:26:31.181036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check how many train images we have in each folder\n\nprint(len(os.listdir('base_dir/train_dir/a_no_tumor_tissue')))\nprint(len(os.listdir('base_dir/train_dir/b_has_tumor_tissue')))","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:32:52.138860Z","iopub.execute_input":"2024-08-05T18:32:52.139285Z","iopub.status.idle":"2024-08-05T18:32:52.249022Z","shell.execute_reply.started":"2024-08-05T18:32:52.139251Z","shell.execute_reply":"2024-08-05T18:32:52.248087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check how many val images we have in each folder\n\nprint(len(os.listdir('base_dir/val_dir/a_no_tumor_tissue')))\nprint(len(os.listdir('base_dir/val_dir/b_has_tumor_tissue')))","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:32:55.772348Z","iopub.execute_input":"2024-08-05T18:32:55.772698Z","iopub.status.idle":"2024-08-05T18:32:55.789984Z","shell.execute_reply.started":"2024-08-05T18:32:55.772652Z","shell.execute_reply":"2024-08-05T18:32:55.789209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set up the generators\ntrain_path = 'base_dir/train_dir'\nvalid_path = 'base_dir/val_dir'\ntest_path = '../input/histopathologic-cancer-detection/test'\n\nnum_train_samples = len(df_train)\nnum_val_samples = len(df_val)\ntrain_batch_size = 10\nval_batch_size = 10\n\n\ntrain_steps = np.ceil(num_train_samples / train_batch_size)\nval_steps = np.ceil(num_val_samples / val_batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:32:58.946655Z","iopub.execute_input":"2024-08-05T18:32:58.947041Z","iopub.status.idle":"2024-08-05T18:32:58.953056Z","shell.execute_reply.started":"2024-08-05T18:32:58.947009Z","shell.execute_reply":"2024-08-05T18:32:58.952085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255)\n\ntrain_gen = datagen.flow_from_directory(train_path,\n                                        target_size=(IMAGE_SIZE,IMAGE_SIZE),\n                                        batch_size=train_batch_size,\n                                        class_mode='categorical')\n\nval_gen = datagen.flow_from_directory(valid_path,\n                                        target_size=(IMAGE_SIZE,IMAGE_SIZE),\n                                        batch_size=val_batch_size,\n                                        class_mode='categorical')\n\n# Note: shuffle=False causes the test dataset to not be shuffled\ntest_gen = datagen.flow_from_directory(valid_path,\n                                        target_size=(IMAGE_SIZE,IMAGE_SIZE),\n                                        batch_size=1,\n                                        class_mode='categorical',\n                                        shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:33:03.117621Z","iopub.execute_input":"2024-08-05T18:33:03.117977Z","iopub.status.idle":"2024-08-05T18:33:12.046023Z","shell.execute_reply.started":"2024-08-05T18:33:03.117948Z","shell.execute_reply":"2024-08-05T18:33:12.045125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kernel_size = (3,3)\npool_size= (2,2)\nfirst_filters = 32\nsecond_filters = 64\nthird_filters = 128\n\ndropout_conv = 0.3\ndropout_dense = 0.3\n\n\nmodel = Sequential()\nmodel.add(Conv2D(first_filters, kernel_size, activation = 'relu', input_shape = (96, 96, 3)))\nmodel.add(Conv2D(first_filters, kernel_size, activation = 'relu'))\nmodel.add(Conv2D(first_filters, kernel_size, activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = pool_size)) \nmodel.add(Dropout(dropout_conv))\n\nmodel.add(Conv2D(second_filters, kernel_size, activation ='relu'))\nmodel.add(Conv2D(second_filters, kernel_size, activation ='relu'))\nmodel.add(Conv2D(second_filters, kernel_size, activation ='relu'))\nmodel.add(MaxPooling2D(pool_size = pool_size))\nmodel.add(Dropout(dropout_conv))\n\nmodel.add(Conv2D(third_filters, kernel_size, activation ='relu'))\nmodel.add(Conv2D(third_filters, kernel_size, activation ='relu'))\nmodel.add(Conv2D(third_filters, kernel_size, activation ='relu'))\nmodel.add(MaxPooling2D(pool_size = pool_size))\nmodel.add(Dropout(dropout_conv))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(dropout_dense))\nmodel.add(Dense(2, activation = \"softmax\"))\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:33:24.220256Z","iopub.execute_input":"2024-08-05T18:33:24.220614Z","iopub.status.idle":"2024-08-05T18:33:26.419458Z","shell.execute_reply.started":"2024-08-05T18:33:24.220577Z","shell.execute_reply":"2024-08-05T18:33:26.418651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(Adam(lr=0.0001), loss='binary_crossentropy', \n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:33:34.988174Z","iopub.execute_input":"2024-08-05T18:33:34.988584Z","iopub.status.idle":"2024-08-05T18:33:35.003554Z","shell.execute_reply.started":"2024-08-05T18:33:34.988546Z","shell.execute_reply":"2024-08-05T18:33:35.002832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the labels that are associated with each index\nprint(val_gen.class_indices)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:33:38.674407Z","iopub.execute_input":"2024-08-05T18:33:38.674793Z","iopub.status.idle":"2024-08-05T18:33:38.679283Z","shell.execute_reply.started":"2024-08-05T18:33:38.674756Z","shell.execute_reply":"2024-08-05T18:33:38.678161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filepath = \"model.h5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, \n                             save_best_only=True, mode='max')\n\nreduce_lr = ReduceLROnPlateau(monitor='val_acc', factor=0.5, patience=2, \n                                   verbose=1, mode='max', min_lr=0.00001)\n                              \n                              \ncallbacks_list = [checkpoint, reduce_lr]\n\nhistory = model.fit_generator(train_gen, steps_per_epoch=train_steps, \n                    validation_data=val_gen,\n                    validation_steps=val_steps,\n                    epochs=20, verbose=1,\n                   callbacks=callbacks_list)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T18:33:44.424267Z","iopub.execute_input":"2024-08-05T18:33:44.424645Z","iopub.status.idle":"2024-08-05T19:25:09.498032Z","shell.execute_reply.started":"2024-08-05T18:33:44.424611Z","shell.execute_reply":"2024-08-05T19:25:09.497288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get the metric names so we can use evaulate_generator\nmodel.metrics_names","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:26:28.450927Z","iopub.execute_input":"2024-08-05T19:26:28.451326Z","iopub.status.idle":"2024-08-05T19:26:28.457805Z","shell.execute_reply.started":"2024-08-05T19:26:28.451286Z","shell.execute_reply":"2024-08-05T19:26:28.456773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here the best epoch will be used.\n\n\n\nval_loss, val_acc = \\\nmodel.evaluate_generator(test_gen, \n                        steps=len(df_val))\n\nprint('val_loss:', val_loss)\nprint('val_acc:', val_acc)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:28:43.500878Z","iopub.execute_input":"2024-08-05T19:28:43.501254Z","iopub.status.idle":"2024-08-05T19:29:10.970377Z","shell.execute_reply.started":"2024-08-05T19:28:43.501220Z","shell.execute_reply":"2024-08-05T19:29:10.969566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display the loss and accuracy curves\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:29:20.814100Z","iopub.execute_input":"2024-08-05T19:29:20.814439Z","iopub.status.idle":"2024-08-05T19:29:21.158595Z","shell.execute_reply.started":"2024-08-05T19:29:20.814410Z","shell.execute_reply":"2024-08-05T19:29:21.157396Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. Validation and Analysis \n\n* ### Metrics\n* ### Prediction and Activation Visualizations\n* ### ROC and AUC","metadata":{}},{"cell_type":"code","source":"# make a prediction\npredictions = model.predict_generator(test_gen, steps=len(df_val), verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:29:26.611823Z","iopub.execute_input":"2024-08-05T19:29:26.612157Z","iopub.status.idle":"2024-08-05T19:29:56.811923Z","shell.execute_reply.started":"2024-08-05T19:29:26.612128Z","shell.execute_reply":"2024-08-05T19:29:56.811226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:01.260642Z","iopub.execute_input":"2024-08-05T19:34:01.261046Z","iopub.status.idle":"2024-08-05T19:34:01.266769Z","shell.execute_reply.started":"2024-08-05T19:34:01.261012Z","shell.execute_reply":"2024-08-05T19:34:01.265878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This is how to check what index keras has internally assigned to each class. \ntest_gen.class_indices","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:07.128187Z","iopub.execute_input":"2024-08-05T19:34:07.128518Z","iopub.status.idle":"2024-08-05T19:34:07.134088Z","shell.execute_reply.started":"2024-08-05T19:34:07.128490Z","shell.execute_reply":"2024-08-05T19:34:07.133121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Put the predictions into a dataframe.\n# The columns need to be ordered to match the output of the previous cell\n\ndf_preds = pd.DataFrame(predictions, columns=['no_tumor_tissue', 'has_tumor_tissue'])\n\ndf_preds.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:10.422587Z","iopub.execute_input":"2024-08-05T19:34:10.422965Z","iopub.status.idle":"2024-08-05T19:34:10.438314Z","shell.execute_reply.started":"2024-08-05T19:34:10.422933Z","shell.execute_reply":"2024-08-05T19:34:10.437363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the true labels\ny_true = test_gen.classes\n\n# Get the predicted labels as probabilities\ny_pred = df_preds['has_tumor_tissue']","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:13.839002Z","iopub.execute_input":"2024-08-05T19:34:13.839407Z","iopub.status.idle":"2024-08-05T19:34:13.843746Z","shell.execute_reply.started":"2024-08-05T19:34:13.839369Z","shell.execute_reply":"2024-08-05T19:34:13.843011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\nroc_auc_score(y_true, y_pred)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:19.024383Z","iopub.execute_input":"2024-08-05T19:34:19.024750Z","iopub.status.idle":"2024-08-05T19:34:19.036896Z","shell.execute_reply.started":"2024-08-05T19:34:19.024716Z","shell.execute_reply":"2024-08-05T19:34:19.036137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the labels of the test images.\n\ntest_labels = test_gen.classes\ntest_labels.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:22.336119Z","iopub.execute_input":"2024-08-05T19:34:22.336452Z","iopub.status.idle":"2024-08-05T19:34:22.342008Z","shell.execute_reply.started":"2024-08-05T19:34:22.336425Z","shell.execute_reply":"2024-08-05T19:34:22.341137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# argmax returns the index of the max value in a row\ncm = confusion_matrix(test_labels, predictions.argmax(axis=1))\n# Print the label associated with each class\ntest_gen.class_indices","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:25.690784Z","iopub.execute_input":"2024-08-05T19:34:25.691204Z","iopub.status.idle":"2024-08-05T19:34:25.764282Z","shell.execute_reply.started":"2024-08-05T19:34:25.691156Z","shell.execute_reply":"2024-08-05T19:34:25.763556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import plot_confusion_matrix","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:34:28.514972Z","iopub.execute_input":"2024-08-05T19:34:28.515332Z","iopub.status.idle":"2024-08-05T19:34:28.519105Z","shell.execute_reply.started":"2024-08-05T19:34:28.515298Z","shell.execute_reply":"2024-08-05T19:34:28.518217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Delete base_dir and it's sub folders to free up disk space.\n\nshutil.rmtree('base_dir')\n#[CREATE A TEST FOLDER DIRECTORY STRUCTURE]\n\n# We will be feeding test images from a folder into predict_generator().\n# Keras requires that the path should point to a folder containing images and not\n# to the images themselves. That is why we are creating a folder (test_images) \n# inside another folder (test_dir).\n\n# test_dir\n    # test_images\n\n# create test_dir\ntest_dir = 'test_dir'\nos.mkdir(test_dir)\n    \n# create test_images inside test_dir\ntest_images = os.path.join(test_dir, 'test_images')\nos.mkdir(test_images)\n# check that the directory we created exists\nos.listdir('test_dir')","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:35:22.791749Z","iopub.execute_input":"2024-08-05T19:35:22.792094Z","iopub.status.idle":"2024-08-05T19:35:29.634930Z","shell.execute_reply.started":"2024-08-05T19:35:22.792065Z","shell.execute_reply":"2024-08-05T19:35:29.634199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Transfer the test images into image_dir\n\ntest_list = os.listdir('../input/histopathologic-cancer-detection/test')\n\nfor image in test_list:\n    \n    fname = image\n    \n    # source path to image\n    src = os.path.join('../input/histopathologic-cancer-detection/test', fname)\n    # destination path to image\n    dst = os.path.join(test_images, fname)\n    # copy the image from the source to the destination\n    shutil.copyfile(src, dst)\n# check that the images are now in the test_images\n# Should now be 57458 images in the test_images folder\n\nlen(os.listdir('test_dir/test_images'))","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:35:34.144508Z","iopub.execute_input":"2024-08-05T19:35:34.144874Z","iopub.status.idle":"2024-08-05T19:41:35.078199Z","shell.execute_reply.started":"2024-08-05T19:35:34.144846Z","shell.execute_reply":"2024-08-05T19:41:35.077320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_path ='test_dir'\n\n\n# Here we change the path to point to the test_images folder.\n\ntest_gen = datagen.flow_from_directory(test_path,\n                                        target_size=(IMAGE_SIZE,IMAGE_SIZE),\n                                        batch_size=1,\n                                        class_mode='categorical',\n                                        shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:43:14.616289Z","iopub.execute_input":"2024-08-05T19:43:14.616647Z","iopub.status.idle":"2024-08-05T19:43:16.776527Z","shell.execute_reply.started":"2024-08-05T19:43:14.616617Z","shell.execute_reply":"2024-08-05T19:43:16.775764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_test_images = 57458\n\n\n\npredictions = model.predict_generator(test_gen, steps=num_test_images, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:43:21.168834Z","iopub.execute_input":"2024-08-05T19:43:21.169176Z","iopub.status.idle":"2024-08-05T19:45:09.707077Z","shell.execute_reply.started":"2024-08-05T19:43:21.169148Z","shell.execute_reply":"2024-08-05T19:45:09.706292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Are the number of predictions correct?\n# Should be 57458.\n\nlen(predictions)","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:13.083934Z","iopub.execute_input":"2024-08-05T19:56:13.084327Z","iopub.status.idle":"2024-08-05T19:56:13.091008Z","shell.execute_reply.started":"2024-08-05T19:56:13.084296Z","shell.execute_reply":"2024-08-05T19:56:13.090244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Put the predictions into a dataframe\n\ndf_preds = pd.DataFrame(predictions, columns=['no_tumor_tissue', 'has_tumor_tissue'])\n\ndf_preds.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:20.952861Z","iopub.execute_input":"2024-08-05T19:56:20.953215Z","iopub.status.idle":"2024-08-05T19:56:20.964640Z","shell.execute_reply.started":"2024-08-05T19:56:20.953188Z","shell.execute_reply":"2024-08-05T19:56:20.963797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This outputs the file names in the sequence in which \n# the generator processed the test images.\ntest_filenames = test_gen.filenames\n\n# add the filenames to the dataframe\ndf_preds['file_names'] = test_filenames\n\ndf_preds.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:25.903963Z","iopub.execute_input":"2024-08-05T19:56:25.904285Z","iopub.status.idle":"2024-08-05T19:56:25.922618Z","shell.execute_reply.started":"2024-08-05T19:56:25.904258Z","shell.execute_reply":"2024-08-05T19:56:25.921720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create an id column\n\n# A file name now has this format: \n# test_images/00006537328c33e284c973d7b39d340809f7271b.tif\n\n# This function will extract the id:\n# 00006537328c33e284c973d7b39d340809f7271b\n\n\ndef extract_id(x):\n    \n    # split into a list\n    a = x.split('/')\n    # split into a list\n    b = a[1].split('.')\n    extracted_id = b[0]\n    \n    return extracted_id\n\ndf_preds['id'] = df_preds['file_names'].apply(extract_id)\n\ndf_preds.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:30.777282Z","iopub.execute_input":"2024-08-05T19:56:30.777612Z","iopub.status.idle":"2024-08-05T19:56:30.854405Z","shell.execute_reply.started":"2024-08-05T19:56:30.777583Z","shell.execute_reply":"2024-08-05T19:56:30.853598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the predicted labels.\n# We were asked to predict a probability that the image has tumor tissue\ny_pred = df_preds['has_tumor_tissue']\n\n# get the id column\nimage_id = df_preds['id']","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:36.825462Z","iopub.execute_input":"2024-08-05T19:56:36.825832Z","iopub.status.idle":"2024-08-05T19:56:36.830628Z","shell.execute_reply.started":"2024-08-05T19:56:36.825797Z","shell.execute_reply":"2024-08-05T19:56:36.829664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Confusion Matrix","metadata":{}},{"cell_type":"markdown","source":"# 5. Submission","metadata":{}},{"cell_type":"code","source":"submission = pd.DataFrame({'id':image_id, \n                           'label':y_pred, \n                          }).set_index('id')\n\nsubmission.to_csv('patch_preds.csv', columns=['label']) \nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:49.163228Z","iopub.execute_input":"2024-08-05T19:56:49.163583Z","iopub.status.idle":"2024-08-05T19:56:49.721606Z","shell.execute_reply.started":"2024-08-05T19:56:49.163554Z","shell.execute_reply":"2024-08-05T19:56:49.720651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Delete the test_dir directory we created to prevent a Kaggle error.\n# Kaggle allows a max of 500 files to be saved.\n\nshutil.rmtree('test_dir')","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:56:56.619952Z","iopub.execute_input":"2024-08-05T19:56:56.620315Z","iopub.status.idle":"2024-08-05T19:56:58.747186Z","shell.execute_reply.started":"2024-08-05T19:56:56.620280Z","shell.execute_reply":"2024-08-05T19:56:58.746212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion Matrix","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt     \n\nax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); ","metadata":{"execution":{"iopub.status.busy":"2024-08-05T19:57:02.563559Z","iopub.execute_input":"2024-08-05T19:57:02.563935Z","iopub.status.idle":"2024-08-05T19:57:02.836865Z","shell.execute_reply.started":"2024-08-05T19:57:02.563898Z","shell.execute_reply":"2024-08-05T19:57:02.836111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}