{"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":"#Required Imports\nfrom numpy.random import seed\nseed(101)\nfrom tensorflow import set_random_seed\nset_random_seed(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","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2021-11-16T03:42:11.262236Z","iopub.execute_input":"2021-11-16T03:42:11.262632Z","iopub.status.idle":"2021-11-16T03:42:12.047857Z","shell.execute_reply.started":"2021-11-16T03:42:11.262565Z","shell.execute_reply":"2021-11-16T03:42:12.046897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Image size - L*B ; No of channels - RGB - 3 ; Sample_Size - Sample being considered.\nIMAGE_SIZE = 96\nIMAGE_CHANNELS = 3\n\nSAMPLE_SIZE = 8000 \n","metadata":{"_uuid":"b7bbdd52c81188b8e9c528b88d9fd0da176bf4bc","execution":{"iopub.status.busy":"2021-11-16T03:42:12.050943Z","iopub.execute_input":"2021-11-16T03:42:12.051278Z","iopub.status.idle":"2021-11-16T03:42:12.057045Z","shell.execute_reply.started":"2021-11-16T03:42:12.051221Z","shell.execute_reply":"2021-11-16T03:42:12.055775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.listdir('../input')#inputs","metadata":{"_uuid":"699bb899bde433ba20fb0d086fa0f33a0f61a250","execution":{"iopub.status.busy":"2021-11-16T03:42:12.059808Z","iopub.execute_input":"2021-11-16T03:42:12.060531Z","iopub.status.idle":"2021-11-16T03:42:12.076862Z","shell.execute_reply.started":"2021-11-16T03:42:12.060464Z","shell.execute_reply":"2021-11-16T03:42:12.075563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Labels as per csv file\n\n0 = no tumor tissue<br>\n1 =   has tumor tissue. <br>\n","metadata":{"_uuid":"c24d1662f8bd5fc4d8c57c29449990a3520cd96b"}},{"cell_type":"markdown","source":"### How many images are in each folder?","metadata":{"_uuid":"5a285343c286be191aa827ff9b836b67821176a5"}},{"cell_type":"code","source":"# No of files in actual folders\nprint(len(os.listdir('../input/train')))\nprint(len(os.listdir('../input/test')))","metadata":{"_uuid":"54461212efed65ac377369a468c80e7d708010f4","execution":{"iopub.status.busy":"2021-11-16T03:42:12.078919Z","iopub.execute_input":"2021-11-16T03:42:12.079604Z","iopub.status.idle":"2021-11-16T03:42:17.386775Z","shell.execute_reply.started":"2021-11-16T03:42:12.079543Z","shell.execute_reply":"2021-11-16T03:42:17.385570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Create a Dataframe containing all images","metadata":{"_uuid":"b90854e07d495d9f945a0e40189fd32a0c32bff5"}},{"cell_type":"code","source":"#Train labels - using val as test set as a metric to understand the performance. \ndf_data = pd.read_csv('../input/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":{"_uuid":"e9c9f40ffab35044641b0dc7d9b18609af1aa25e","execution":{"iopub.status.busy":"2021-11-16T03:42:17.387862Z","iopub.execute_input":"2021-11-16T03:42:17.388153Z","iopub.status.idle":"2021-11-16T03:42:18.147749Z","shell.execute_reply.started":"2021-11-16T03:42:17.388097Z","shell.execute_reply":"2021-11-16T03:42:18.146510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Checking class distribution","metadata":{"_uuid":"cfbd53b7f8ea1929952ffed6221b380012618e32"}},{"cell_type":"code","source":"df_data['label'].value_counts() #Understanding the class distribution.","metadata":{"_uuid":"e18560bf69d3dfc0c4772e7c79bb119fd2eb634b","execution":{"iopub.status.busy":"2021-11-16T03:42:31.834000Z","iopub.execute_input":"2021-11-16T03:42:31.834425Z","iopub.status.idle":"2021-11-16T03:42:31.848936Z","shell.execute_reply.started":"2021-11-16T03:42:31.834360Z","shell.execute_reply":"2021-11-16T03:42:31.848125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Display a random sample of train images  by class","metadata":{"_uuid":"6efe2e5de99c4bf92079b1a7d0b892d30fc9d518"}},{"cell_type":"code","source":"def 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()\n    ","metadata":{"_kg_hide-input":true,"_uuid":"1c5143f227da4262eafce8cf0210a02c8072fb8e","execution":{"iopub.status.busy":"2021-11-16T03:42:35.404857Z","iopub.execute_input":"2021-11-16T03:42:35.405208Z","iopub.status.idle":"2021-11-16T03:42:35.416845Z","shell.execute_reply.started":"2021-11-16T03:42:35.405120Z","shell.execute_reply":"2021-11-16T03:42:35.415618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_PATH = '../input/train/' \n#Plotting images randomly\ndraw_category_images('label',4, df_data, IMAGE_PATH)","metadata":{"_uuid":"bd38bcfb5839975e4fee9e70b93d42c29c1b5d2e","execution":{"iopub.status.busy":"2021-11-16T03:42:37.770470Z","iopub.execute_input":"2021-11-16T03:42:37.770828Z","iopub.status.idle":"2021-11-16T03:42:39.391440Z","shell.execute_reply.started":"2021-11-16T03:42:37.770765Z","shell.execute_reply":"2021-11-16T03:42:39.389187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating training and validation sets","metadata":{"_uuid":"1da4226777aefe65b1bb3430208ea91ea7ca7d9a"}},{"cell_type":"code","source":"df_data.head()","metadata":{"_uuid":"547f9f571ee82e20b7647e16ed36de7550046032","execution":{"iopub.status.busy":"2021-11-16T03:42:57.927504Z","iopub.execute_input":"2021-11-16T03:42:57.927863Z","iopub.status.idle":"2021-11-16T03:42:57.949783Z","shell.execute_reply.started":"2021-11-16T03:42:57.927793Z","shell.execute_reply":"2021-11-16T03:42:57.948476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Balance the target distribution\nWe will reduce the number of samples in class 0.","metadata":{"_uuid":"c1150500d2772b7f36cdaa5aa5fd7f0fb4a72628"}},{"cell_type":"code","source":"# take a random sample of class 0 with size equal to num samples in class 1\ndf_0 = df_data[df_data['label'] == 0].sample(SAMPLE_SIZE, random_state = 101)\n# filter out class 1\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":{"_uuid":"270fc18640b552ecc3cb0e1dd3036441db7a4a2b","execution":{"iopub.status.busy":"2021-11-16T03:43:00.846278Z","iopub.execute_input":"2021-11-16T03:43:00.846663Z","iopub.status.idle":"2021-11-16T03:43:00.886669Z","shell.execute_reply.started":"2021-11-16T03:43:00.846582Z","shell.execute_reply":"2021-11-16T03:43:00.885814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_data.head()","metadata":{"_uuid":"a166dec3ef84c66ad9cd815b63fc1a753df2eb76","execution":{"iopub.status.busy":"2021-11-16T03:43:03.363100Z","iopub.execute_input":"2021-11-16T03:43:03.363445Z","iopub.status.idle":"2021-11-16T03:43:03.381816Z","shell.execute_reply.started":"2021-11-16T03:43:03.363379Z","shell.execute_reply":"2021-11-16T03:43:03.380230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Stratification of dataset.\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":{"_uuid":"15ba9792e6a370b7560330af15b3cfe21185c1cb","execution":{"iopub.status.busy":"2021-11-16T03:43:03.580544Z","iopub.execute_input":"2021-11-16T03:43:03.580907Z","iopub.status.idle":"2021-11-16T03:43:03.609534Z","shell.execute_reply.started":"2021-11-16T03:43:03.580841Z","shell.execute_reply":"2021-11-16T03:43:03.608535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['label'].value_counts()","metadata":{"_uuid":"7de70d915a5f1d2599725e00bdb3b9103d947883","execution":{"iopub.status.busy":"2021-11-16T03:43:07.497208Z","iopub.execute_input":"2021-11-16T03:43:07.497553Z","iopub.status.idle":"2021-11-16T03:43:07.507126Z","shell.execute_reply.started":"2021-11-16T03:43:07.497476Z","shell.execute_reply":"2021-11-16T03:43:07.505901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_val['label'].value_counts()","metadata":{"_uuid":"392c0eea00be8e43a6e55438d1458650e842030b","execution":{"iopub.status.busy":"2021-11-16T03:43:07.694047Z","iopub.execute_input":"2021-11-16T03:43:07.694422Z","iopub.status.idle":"2021-11-16T03:43:07.706548Z","shell.execute_reply.started":"2021-11-16T03:43:07.694361Z","shell.execute_reply":"2021-11-16T03:43:07.705216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating a Directory Structure","metadata":{"_uuid":"ba17dd34b75367fc61df6634d51dac94c3ab4951"}},{"cell_type":"code","source":"# Create a new directory\nbase_dir = 'base_dir'\nos.mkdir(base_dir)\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\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)\n\n","metadata":{"_uuid":"ff8acc2e92a1b1b5002d6e1bf9a1180c3256f19d","execution":{"iopub.status.busy":"2021-11-16T03:43:19.013142Z","iopub.execute_input":"2021-11-16T03:43:19.013492Z","iopub.status.idle":"2021-11-16T03:43:19.024071Z","shell.execute_reply.started":"2021-11-16T03:43:19.013423Z","shell.execute_reply":"2021-11-16T03:43:19.022987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check that the folders have been created\nos.listdir('base_dir/train_dir')","metadata":{"_uuid":"03ca5d4b8b027c2712d7096314d3a79ef829b23c","execution":{"iopub.status.busy":"2021-11-16T03:43:19.298123Z","iopub.execute_input":"2021-11-16T03:43:19.298462Z","iopub.status.idle":"2021-11-16T03:43:19.306420Z","shell.execute_reply.started":"2021-11-16T03:43:19.298399Z","shell.execute_reply":"2021-11-16T03:43:19.305022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transferring the images into the respective folders","metadata":{"_uuid":"6a2e56340ba18f3b63c1b129fd995fecfadaa21d"}},{"cell_type":"code","source":"# Set the id as the index in df_data\ndf_data.set_index('id', inplace=True)","metadata":{"_uuid":"e84c8a9642b030094b1888af3299063f883112a6","execution":{"iopub.status.busy":"2021-11-16T03:43:35.603796Z","iopub.execute_input":"2021-11-16T03:43:35.604166Z","iopub.status.idle":"2021-11-16T03:43:35.610889Z","shell.execute_reply.started":"2021-11-16T03:43:35.604107Z","shell.execute_reply":"2021-11-16T03:43:35.609690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Mapping images and labels with folders.\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/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/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)\n    \n\n\n   ","metadata":{"_uuid":"afb8969a9ee75c13bddc808a4bcc326611baaaaf","execution":{"iopub.status.busy":"2021-11-16T03:43:36.172936Z","iopub.execute_input":"2021-11-16T03:43:36.173265Z","iopub.status.idle":"2021-11-16T03:45:20.044794Z","shell.execute_reply.started":"2021-11-16T03:43:36.173188Z","shell.execute_reply":"2021-11-16T03:45:20.043590Z"},"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')))\n","metadata":{"_uuid":"71532bfc32608289b1f773ffdbc8a7cea1bfb94c","execution":{"iopub.status.busy":"2021-11-16T03:45:20.047116Z","iopub.execute_input":"2021-11-16T03:45:20.047444Z","iopub.status.idle":"2021-11-16T03:45:20.071760Z","shell.execute_reply.started":"2021-11-16T03:45:20.047382Z","shell.execute_reply":"2021-11-16T03:45:20.070890Z"},"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')))\n","metadata":{"_uuid":"897e9df543bb65b47bb00019dc681125ca08ee5d","execution":{"iopub.status.busy":"2021-11-16T03:45:20.075624Z","iopub.execute_input":"2021-11-16T03:45:20.076199Z","iopub.status.idle":"2021-11-16T03:45:20.086037Z","shell.execute_reply.started":"2021-11-16T03:45:20.075946Z","shell.execute_reply":"2021-11-16T03:45:20.084510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating image generators","metadata":{"_uuid":"f8dce940ee8a7a42aacb062e4c6b5a4a54dba58f"}},{"cell_type":"code","source":"train_path = 'base_dir/train_dir'\nvalid_path = 'base_dir/val_dir'\ntest_path = '../input/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":{"_uuid":"ef4fe7be09f11ff4badfd22d5fd5e03f8521ed58","execution":{"iopub.status.busy":"2021-11-16T03:45:20.089793Z","iopub.execute_input":"2021-11-16T03:45:20.090555Z","iopub.status.idle":"2021-11-16T03:45:20.098563Z","shell.execute_reply.started":"2021-11-16T03:45:20.090476Z","shell.execute_reply":"2021-11-16T03:45:20.097466Z"},"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":{"_uuid":"68fbd9d5fbb80859a82f94a12e335ce05a93bd51","execution":{"iopub.status.busy":"2021-11-16T03:45:20.100090Z","iopub.execute_input":"2021-11-16T03:45:20.100413Z","iopub.status.idle":"2021-11-16T03:45:21.867912Z","shell.execute_reply.started":"2021-11-16T03:45:20.100345Z","shell.execute_reply":"2021-11-16T03:45:21.866836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#custom-cnn\nkernel_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()\n","metadata":{"_uuid":"b9835ea0fd0bca54138904895c39d38227a70c22","execution":{"iopub.status.busy":"2021-11-16T03:45:21.869130Z","iopub.execute_input":"2021-11-16T03:45:21.869426Z","iopub.status.idle":"2021-11-16T03:45:22.226723Z","shell.execute_reply.started":"2021-11-16T03:45:21.869367Z","shell.execute_reply":"2021-11-16T03:45:22.225787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train the Model","metadata":{"_uuid":"75cfc4fcb8dd3408d1c4fcf8cd85e0e2f5b611d7"}},{"cell_type":"code","source":"model.compile(Adam(lr=0.0001), loss='binary_crossentropy', \n              metrics=['accuracy'])","metadata":{"_uuid":"9de9715f49a63b55775b10abd2f461b395e23b5d","execution":{"iopub.status.busy":"2021-11-16T03:45:22.227953Z","iopub.execute_input":"2021-11-16T03:45:22.228243Z","iopub.status.idle":"2021-11-16T03:45:22.415311Z","shell.execute_reply.started":"2021-11-16T03:45:22.228184Z","shell.execute_reply":"2021-11-16T03:45:22.414130Z"},"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":{"_uuid":"227d84a4f44c0b7256855c06ba04dabd58d89d84","execution":{"iopub.status.busy":"2021-11-16T03:45:22.416534Z","iopub.execute_input":"2021-11-16T03:45:22.416890Z","iopub.status.idle":"2021-11-16T03:45:22.426076Z","shell.execute_reply.started":"2021-11-16T03:45:22.416831Z","shell.execute_reply":"2021-11-16T03:45:22.425049Z"},"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":{"scrolled":true,"_uuid":"a746769db61563f226288eba9aa8a6584b9e8e0b","execution":{"iopub.status.busy":"2021-11-16T03:45:22.427503Z","iopub.execute_input":"2021-11-16T03:45:22.428157Z","iopub.status.idle":"2021-11-16T03:53:48.630642Z","shell.execute_reply.started":"2021-11-16T03:45:22.428085Z","shell.execute_reply":"2021-11-16T03:53:48.629691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Evaluation","metadata":{"_uuid":"fa15a8afda3593973726e9087cbd98073041c908"}},{"cell_type":"code","source":"# get the metric names so we can use evaulate_generator\nmodel.metrics_names","metadata":{"_uuid":"70104420ec7f400cd06203f875dbeba30f4d8a96","execution":{"iopub.status.busy":"2021-11-16T03:53:48.631746Z","iopub.execute_input":"2021-11-16T03:53:48.632006Z","iopub.status.idle":"2021-11-16T03:53:48.643599Z","shell.execute_reply.started":"2021-11-16T03:53:48.631951Z","shell.execute_reply":"2021-11-16T03:53:48.642285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here the best epoch will be used.\n\nmodel.load_weights('model.h5')\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":{"_uuid":"428bdf5b24ff8cef35012205c3f2eb37006fc9e9","execution":{"iopub.status.busy":"2021-11-16T03:53:48.653677Z","iopub.execute_input":"2021-11-16T03:53:48.654293Z","iopub.status.idle":"2021-11-16T03:53:54.494385Z","shell.execute_reply.started":"2021-11-16T03:53:48.654013Z","shell.execute_reply":"2021-11-16T03:53:54.493462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Plot the Training Curves","metadata":{"_uuid":"93556c9e4b6a188cf9cb67a6519c9bc365c60caf"}},{"cell_type":"code","source":"# display the loss and accuracy curves\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\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":{"_uuid":"385da8ba94a1079d17909790716b295fc2737584","_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-11-16T03:53:54.497367Z","iopub.execute_input":"2021-11-16T03:53:54.498049Z","iopub.status.idle":"2021-11-16T03:53:55.184602Z","shell.execute_reply.started":"2021-11-16T03:53:54.497988Z","shell.execute_reply":"2021-11-16T03:53:55.183192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Make a prediction on the val set\nWe need these predictions to calculate the AUC score, print the Confusion Matrix and calculate the F1 score.","metadata":{"_uuid":"5636e76f23202dd1f2a27ace25e15e09619a5e4e"}},{"cell_type":"code","source":"# make a prediction\npredictions = model.predict_generator(test_gen, steps=len(df_val), verbose=1)","metadata":{"_uuid":"652d9d6aa51dc1818d1c5171212d10e141ad7de9","execution":{"iopub.status.busy":"2021-11-16T03:53:55.189108Z","iopub.execute_input":"2021-11-16T03:53:55.192342Z","iopub.status.idle":"2021-11-16T03:53:59.205313Z","shell.execute_reply.started":"2021-11-16T03:53:55.189518Z","shell.execute_reply":"2021-11-16T03:53:59.204308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions.shape","metadata":{"_uuid":"edf1866df4638ded26de2e0e3d2ba0f5e00e1ace","execution":{"iopub.status.busy":"2021-11-16T03:53:59.206862Z","iopub.execute_input":"2021-11-16T03:53:59.207222Z","iopub.status.idle":"2021-11-16T03:53:59.214592Z","shell.execute_reply.started":"2021-11-16T03:53:59.207148Z","shell.execute_reply":"2021-11-16T03:53:59.213414Z"},"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":{"_uuid":"dc71f69944e7db83329417c5265a5bc31f9c4fc3","execution":{"iopub.status.busy":"2021-11-16T03:53:59.216279Z","iopub.execute_input":"2021-11-16T03:53:59.216941Z","iopub.status.idle":"2021-11-16T03:53:59.228504Z","shell.execute_reply.started":"2021-11-16T03:53:59.216852Z","shell.execute_reply":"2021-11-16T03:53:59.227190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Put the predictions into a dataframe.\n# The columns need to be oredered 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()","metadata":{"_uuid":"4a6709d73969f7fd597128223b110be077f84edb","execution":{"iopub.status.busy":"2021-11-16T03:53:59.230177Z","iopub.execute_input":"2021-11-16T03:53:59.230823Z","iopub.status.idle":"2021-11-16T03:53:59.251778Z","shell.execute_reply.started":"2021-11-16T03:53:59.230757Z","shell.execute_reply":"2021-11-16T03:53:59.250942Z"},"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']\n","metadata":{"_uuid":"0954d61a4ef8bc056452b3bbad9456d45c00bed1","execution":{"iopub.status.busy":"2021-11-16T03:53:59.252544Z","iopub.execute_input":"2021-11-16T03:53:59.252879Z","iopub.status.idle":"2021-11-16T03:53:59.259605Z","shell.execute_reply.started":"2021-11-16T03:53:59.252822Z","shell.execute_reply":"2021-11-16T03:53:59.257943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### What is the AUC Score?","metadata":{"_uuid":"f07c814d213e814cdac4e3d05d0a8db847fbfe28"}},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\nroc_auc_score(y_true, y_pred)","metadata":{"_uuid":"0b7b7a56c6fa47cc40764d0c06d64860580cbea1","execution":{"iopub.status.busy":"2021-11-16T03:53:59.261548Z","iopub.execute_input":"2021-11-16T03:53:59.262312Z","iopub.status.idle":"2021-11-16T03:53:59.276974Z","shell.execute_reply.started":"2021-11-16T03:53:59.262232Z","shell.execute_reply":"2021-11-16T03:53:59.275250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Create a Confusion Matrix","metadata":{"_uuid":"9d8404e8e6b6008c8989b8184700ec5562b99366"}},{"cell_type":"code","source":"# Source: Scikit Learn website\n# http://scikit-learn.org/stable/auto_examples/\n# model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-\n# selection-plot-confusion-matrix-py\n\n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    print(cm)\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.tight_layout()","metadata":{"_uuid":"91f570e8e5f07126e5361bbf92929d786e853a09","_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-11-16T03:53:59.278862Z","iopub.execute_input":"2021-11-16T03:53:59.279157Z","iopub.status.idle":"2021-11-16T03:53:59.292135Z","shell.execute_reply.started":"2021-11-16T03:53:59.279097Z","shell.execute_reply":"2021-11-16T03:53:59.290441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the labels of the test images.\n\ntest_labels = test_gen.classes","metadata":{"_uuid":"c20bc358dc753020d5a560dc56f2350c7f40a4f9","execution":{"iopub.status.busy":"2021-11-16T03:53:59.294067Z","iopub.execute_input":"2021-11-16T03:53:59.294911Z","iopub.status.idle":"2021-11-16T03:53:59.303219Z","shell.execute_reply.started":"2021-11-16T03:53:59.294803Z","shell.execute_reply":"2021-11-16T03:53:59.301863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_labels.shape","metadata":{"_uuid":"3a537724473df19c74bb1bf6928f531dd0fcfdb3","execution":{"iopub.status.busy":"2021-11-16T03:53:59.305083Z","iopub.execute_input":"2021-11-16T03:53:59.306052Z","iopub.status.idle":"2021-11-16T03:53:59.316219Z","shell.execute_reply.started":"2021-11-16T03:53:59.305985Z","shell.execute_reply":"2021-11-16T03:53:59.314746Z"},"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))","metadata":{"_uuid":"0bb4323e931ff53081994bbf58e82b1ec93ab327","execution":{"iopub.status.busy":"2021-11-16T03:53:59.318423Z","iopub.execute_input":"2021-11-16T03:53:59.319099Z","iopub.status.idle":"2021-11-16T03:53:59.335605Z","shell.execute_reply.started":"2021-11-16T03:53:59.318854Z","shell.execute_reply":"2021-11-16T03:53:59.334602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print the label associated with each class\ntest_gen.class_indices","metadata":{"_uuid":"ec2058223eb30485898a12c0e904bb170c0aa884","execution":{"iopub.status.busy":"2021-11-16T03:53:59.336731Z","iopub.execute_input":"2021-11-16T03:53:59.337030Z","iopub.status.idle":"2021-11-16T03:53:59.347204Z","shell.execute_reply.started":"2021-11-16T03:53:59.336960Z","shell.execute_reply":"2021-11-16T03:53:59.345516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the labels of the class indices. These need to match the \n# order shown above.\ncm_plot_labels = ['no_tumor_tissue', 'has_tumor_tissue']\n\nplot_confusion_matrix(cm, cm_plot_labels, title='Confusion Matrix')","metadata":{"_uuid":"ba26c7e718df937a18aa2035c4ba883252e44c79","execution":{"iopub.status.busy":"2021-11-16T03:53:59.349061Z","iopub.execute_input":"2021-11-16T03:53:59.350020Z","iopub.status.idle":"2021-11-16T03:53:59.670085Z","shell.execute_reply.started":"2021-11-16T03:53:59.349525Z","shell.execute_reply":"2021-11-16T03:53:59.668831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Create a Classification Report","metadata":{"_uuid":"2576c1144cfe93d66f3197396990f3e43addd499"}},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\n# Generate a classification report\n\n# For this to work we need y_pred as binary labels not as probabilities\ny_pred_binary = predictions.argmax(axis=1)\n\nreport = classification_report(y_true, y_pred_binary, target_names=cm_plot_labels)\n\nprint(report)\n","metadata":{"_uuid":"91dcace7eb99aca310774b7a3a55535c9127ce55","execution":{"iopub.status.busy":"2021-11-16T03:53:59.671561Z","iopub.execute_input":"2021-11-16T03:53:59.672253Z","iopub.status.idle":"2021-11-16T03:53:59.683325Z","shell.execute_reply.started":"2021-11-16T03:53:59.672146Z","shell.execute_reply":"2021-11-16T03:53:59.681929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Comparing with pretrained model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.layers import Concatenate,GlobalAveragePooling2D,Dense,Dropout,Input\nfrom tensorflow.keras import Model\ninput_shape = (96, 96, 3)\ninputs = Input(input_shape)\n\nxception = keras.applications.Xception(include_top=False, input_shape=input_shape)  \nnas_net = keras.applications.NASNetMobile(include_top=False, input_shape=input_shape)\n\noutputs = Concatenate(axis=-1)([GlobalAveragePooling2D()(xception(inputs)),\n                                GlobalAveragePooling2D()(nas_net(inputs))])\noutputs = Dropout(0.5)(outputs)\noutputs = Dense(2, activation='sigmoid')(outputs)\n\nmodel = Model(inputs, outputs)\n\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2021-11-16T03:57:57.569349Z","iopub.execute_input":"2021-11-16T03:57:57.569792Z","iopub.status.idle":"2021-11-16T03:58:53.913513Z","shell.execute_reply.started":"2021-11-16T03:57:57.569724Z","shell.execute_reply":"2021-11-16T03:58:53.911558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(lr=0.0001, decay=0.00001),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-11-16T03:59:12.648366Z","iopub.execute_input":"2021-11-16T03:59:12.648834Z","iopub.status.idle":"2021-11-16T03:59:12.908677Z","shell.execute_reply.started":"2021-11-16T03:59:12.648751Z","shell.execute_reply":"2021-11-16T03:59:12.907481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(train_gen, steps_per_epoch=train_steps, \n                    validation_data=val_gen,\n                    validation_steps=val_steps,\n                    epochs=5, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-16T03:59:15.972012Z","iopub.execute_input":"2021-11-16T03:59:15.972319Z","iopub.status.idle":"2021-11-16T04:38:20.744659Z","shell.execute_reply.started":"2021-11-16T03:59:15.972258Z","shell.execute_reply":"2021-11-16T04:38:20.743227Z"},"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['acc']\nval_acc = history.history['val_acc']\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":"2021-11-16T04:41:17.154002Z","iopub.execute_input":"2021-11-16T04:41:17.154423Z","iopub.status.idle":"2021-11-16T04:41:17.842240Z","shell.execute_reply.started":"2021-11-16T04:41:17.154361Z","shell.execute_reply":"2021-11-16T04:41:17.840917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# make a prediction\npredictions = model.predict_generator(test_gen, steps=len(df_val), verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-16T04:41:48.742391Z","iopub.execute_input":"2021-11-16T04:41:48.743149Z","iopub.status.idle":"2021-11-16T04:43:00.444199Z","shell.execute_reply.started":"2021-11-16T04:41:48.742978Z","shell.execute_reply":"2021-11-16T04:43:00.443135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Put the predictions into a dataframe.\n# The columns need to be oredered 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()","metadata":{"execution":{"iopub.status.busy":"2021-11-16T04:44:12.504503Z","iopub.execute_input":"2021-11-16T04:44:12.504954Z","iopub.status.idle":"2021-11-16T04:44:12.522312Z","shell.execute_reply.started":"2021-11-16T04:44:12.504883Z","shell.execute_reply":"2021-11-16T04:44:12.521207Z"},"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']\n","metadata":{"execution":{"iopub.status.busy":"2021-11-16T04:44:27.223258Z","iopub.execute_input":"2021-11-16T04:44:27.223609Z","iopub.status.idle":"2021-11-16T04:44:27.229239Z","shell.execute_reply.started":"2021-11-16T04:44:27.223534Z","shell.execute_reply":"2021-11-16T04:44:27.228182Z"},"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":"2021-11-16T04:44:40.075390Z","iopub.execute_input":"2021-11-16T04:44:40.075761Z","iopub.status.idle":"2021-11-16T04:44:40.087493Z","shell.execute_reply.started":"2021-11-16T04:44:40.075671Z","shell.execute_reply":"2021-11-16T04:44:40.086121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\n# Generate a classification report\n\n# For this to work we need y_pred as binary labels not as probabilities\ny_pred_binary = predictions.argmax(axis=1)\n\nreport = classification_report(y_true, y_pred_binary, target_names=cm_plot_labels)\n\nprint(report)\n","metadata":{"execution":{"iopub.status.busy":"2021-11-16T04:46:18.482363Z","iopub.execute_input":"2021-11-16T04:46:18.482788Z","iopub.status.idle":"2021-11-16T04:46:18.492853Z","shell.execute_reply.started":"2021-11-16T04:46:18.482720Z","shell.execute_reply":"2021-11-16T04:46:18.491229Z"},"trusted":true},"execution_count":null,"outputs":[]}]}