{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Load Packages\n\n","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pandas as pd\nimport pickle\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimport zipfile ","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:38.864971Z","iopub.execute_input":"2021-12-11T17:34:38.865684Z","iopub.status.idle":"2021-12-11T17:34:44.339685Z","shell.execute_reply.started":"2021-12-11T17:34:38.865590Z","shell.execute_reply":"2021-12-11T17:34:44.338963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load DataFrame","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"../input/histopathologic-cancer-detection/train_labels.csv\", dtype=str)\nprint(train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:44.343446Z","iopub.execute_input":"2021-12-11T17:34:44.343642Z","iopub.status.idle":"2021-12-11T17:34:44.874602Z","shell.execute_reply.started":"2021-12-11T17:34:44.343618Z","shell.execute_reply":"2021-12-11T17:34:44.873805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head(10)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:44.875945Z","iopub.execute_input":"2021-12-11T17:34:44.876336Z","iopub.status.idle":"2021-12-11T17:34:44.895833Z","shell.execute_reply.started":"2021-12-11T17:34:44.876301Z","shell.execute_reply":"2021-12-11T17:34:44.895116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label Distribution","metadata":{}},{"cell_type":"code","source":"y_train = train.label\n\n(train.label.value_counts() / len(train)).to_frame().T","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:44.897008Z","iopub.execute_input":"2021-12-11T17:34:44.897297Z","iopub.status.idle":"2021-12-11T17:34:44.935822Z","shell.execute_reply.started":"2021-12-11T17:34:44.897262Z","shell.execute_reply":"2021-12-11T17:34:44.935016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# View Sample of Images","metadata":{}},{"cell_type":"code","source":"# Sample 16 images from the training set and display these along with their labels.\n\nplt.figure(figsize=(10,10)) # specifying the overall grid size\n\nfor i in range(16):\n    plt.subplot(4,4,i+1)    # the number of images in the grid is 6*6 (16)\n    img = mpimg.imread(f'../input/histopathologic-cancer-detection/train/{train[\"id\"][i]}.tif')\n    plt.imshow(img)\n    plt.text(0, -5, f'Label {train[\"label\"][i]}')\n    plt.axis('off')\n    \nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:44.938741Z","iopub.execute_input":"2021-12-11T17:34:44.939238Z","iopub.status.idle":"2021-12-11T17:34:46.247476Z","shell.execute_reply.started":"2021-12-11T17:34:44.939200Z","shell.execute_reply":"2021-12-11T17:34:46.246814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Split & Sample Data","metadata":{}},{"cell_type":"code","source":"train_neg = train[train['label']=='0'].sample(4000,random_state=1)\ntrain_pos = train[train['label']=='1'].sample(4000,random_state=1)\n\ntrain_data = pd.concat([train_neg, train_pos], axis=0).reset_index(drop=True)\n\ntrain = shuffle(train_data)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.248407Z","iopub.execute_input":"2021-12-11T17:34:46.248667Z","iopub.status.idle":"2021-12-11T17:34:46.343569Z","shell.execute_reply.started":"2021-12-11T17:34:46.248613Z","shell.execute_reply":"2021-12-11T17:34:46.342893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['label'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.344713Z","iopub.execute_input":"2021-12-11T17:34:46.345480Z","iopub.status.idle":"2021-12-11T17:34:46.353456Z","shell.execute_reply.started":"2021-12-11T17:34:46.345439Z","shell.execute_reply":"2021-12-11T17:34:46.352746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# function to apply the .tif extension\ndef append_ext(fn):\n    return fn+\".tif\"\n\n\ntrain['id'] = train['id'].apply(append_ext)\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.354796Z","iopub.execute_input":"2021-12-11T17:34:46.355218Z","iopub.status.idle":"2021-12-11T17:34:46.371457Z","shell.execute_reply.started":"2021-12-11T17:34:46.355182Z","shell.execute_reply":"2021-12-11T17:34:46.370676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the dataframe train into two DataFrames named train_df and valid_df. \n# Use 20% of the data for the validation set. \n# Use stratified sampling so that the label proportions are preserved.\n# Set a random seed for the split. \n\ntrain_df, valid_df = train_test_split(train, test_size=0.2, random_state=1, stratify=train.label)\n\nprint(train_df.shape)\nprint(valid_df.shape)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.373078Z","iopub.execute_input":"2021-12-11T17:34:46.373593Z","iopub.status.idle":"2021-12-11T17:34:46.394268Z","shell.execute_reply.started":"2021-12-11T17:34:46.373557Z","shell.execute_reply":"2021-12-11T17:34:46.393278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create image data generators for both the training set and the validation set. \n# Use the data generators to scale the pixel values by a factor of 1/255. \ntrain_datagen = ImageDataGenerator(rescale=1/255)\nvalid_datagen = ImageDataGenerator(rescale=1/255)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.395915Z","iopub.execute_input":"2021-12-11T17:34:46.396229Z","iopub.status.idle":"2021-12-11T17:34:46.401788Z","shell.execute_reply.started":"2021-12-11T17:34:46.396188Z","shell.execute_reply":"2021-12-11T17:34:46.400684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Complete the code for the data loaders below. \n\nBATCH_SIZE = 64\n\ntrain_loader = train_datagen.flow_from_dataframe(\n    dataframe = train_df,\n    directory = '../input/histopathologic-cancer-detection/train/',\n    x_col = 'id',\n    y_col = 'label',\n    batch_size = BATCH_SIZE,\n    seed = 1,\n    shuffle = True,\n    class_mode = 'categorical',\n    target_size = (32,32)\n)\n\nvalid_loader = train_datagen.flow_from_dataframe(\n    dataframe = valid_df,\n    directory = '../input/histopathologic-cancer-detection/train/',\n    x_col = 'id',\n    y_col = 'label',\n    batch_size = BATCH_SIZE,\n    seed = 1,\n    shuffle = True,\n    class_mode = 'categorical',\n    target_size = (32,32)\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:34:46.403816Z","iopub.execute_input":"2021-12-11T17:34:46.404323Z","iopub.status.idle":"2021-12-11T17:35:01.992521Z","shell.execute_reply.started":"2021-12-11T17:34:46.404105Z","shell.execute_reply":"2021-12-11T17:35:01.991713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Run this cell to determine the number of training and validation batches. \n\nTR_STEPS = len(train_loader)\nVA_STEPS = len(valid_loader)\n\nprint(TR_STEPS)\nprint(VA_STEPS)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:35:01.994277Z","iopub.execute_input":"2021-12-11T17:35:01.994553Z","iopub.status.idle":"2021-12-11T17:35:02.001619Z","shell.execute_reply.started":"2021-12-11T17:35:01.994517Z","shell.execute_reply":"2021-12-11T17:35:02.000784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Network","metadata":{}},{"cell_type":"code","source":"# Use this cell to construct a convolutional neural network model. \n# Your model should make use of each of the following layer types:\n#    Conv2D, MaxPooling2D, Dropout, BatchNormalization, Flatten, Dense\n# You can start by mimicking the architecture used in the \n# Aerial Cactus competetition, but you should explore different architectures\n# by adding more layers and/or adding more nodes in individual layers\n\nnp.random.seed(1)\ntf.random.set_seed(1)\n\ncnn1 = Sequential([\n    Conv2D(32, (3,3), activation = 'relu', padding = 'same', input_shape=(32,32,3)),\n    Conv2D(32, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.25),\n    BatchNormalization(),\n\n    Conv2D(64, (3,3), activation = 'relu', padding = 'same'),\n    Conv2D(64, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.5),\n    BatchNormalization(),\n    \n    Conv2D(128, (3,3), activation = 'relu', padding = 'same'),\n    Conv2D(128, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.5),\n    BatchNormalization(),\n\n    Flatten(),\n    \n    Dense(32, activation='relu'),\n    Dropout(0.5),\n    Dense(16, activation='relu'),\n    Dropout(0.25),\n    BatchNormalization(),\n    # we have 2 here because we have 2 classes\n    Dense(2, activation='softmax')\n])\n\ncnn1.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:35:02.003428Z","iopub.execute_input":"2021-12-11T17:35:02.004152Z","iopub.status.idle":"2021-12-11T17:35:04.553248Z","shell.execute_reply.started":"2021-12-11T17:35:02.004092Z","shell.execute_reply":"2021-12-11T17:35:04.552564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train Network","metadata":{}},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.001)\ncnn1.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:35:04.556005Z","iopub.execute_input":"2021-12-11T17:35:04.556599Z","iopub.status.idle":"2021-12-11T17:35:04.575573Z","shell.execute_reply.started":"2021-12-11T17:35:04.556558Z","shell.execute_reply":"2021-12-11T17:35:04.574927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training Run 1","metadata":{}},{"cell_type":"code","source":"%%time \n\nh1 = cnn1.fit(\n    x = train_loader, \n    steps_per_epoch = TR_STEPS, \n    epochs = 30,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:35:04.576754Z","iopub.execute_input":"2021-12-11T17:35:04.577071Z","iopub.status.idle":"2021-12-11T17:40:14.401211Z","shell.execute_reply.started":"2021-12-11T17:35:04.577035Z","shell.execute_reply":"2021-12-11T17:40:14.400511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = h1.history\nprint(history.keys())","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:40:14.402652Z","iopub.execute_input":"2021-12-11T17:40:14.403177Z","iopub.status.idle":"2021-12-11T17:40:14.409407Z","shell.execute_reply.started":"2021-12-11T17:40:14.403136Z","shell.execute_reply":"2021-12-11T17:40:14.408366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Graph the result\n\nepoch_range = range(1, len(history['loss'])+1)\n\nplt.figure(figsize=[14,4])\n\nplt.subplot(1,3,1)\nplt.plot(epoch_range, history['loss'], label='Training')\nplt.plot(epoch_range, history['val_loss'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('Loss'); plt.title('Loss')\nplt.legend()\n\nplt.subplot(1,3,2)\nplt.plot(epoch_range, history['accuracy'], label='Training')\nplt.plot(epoch_range, history['val_accuracy'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('Accuracy'); plt.title('Accuracy')\nplt.legend()\n\nplt.subplot(1,3,3)\nplt.plot(epoch_range, history['auc'], label='Training')\nplt.plot(epoch_range, history['val_auc'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('AUC'); plt.title('AUC')\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:40:14.410854Z","iopub.execute_input":"2021-12-11T17:40:14.411560Z","iopub.status.idle":"2021-12-11T17:40:15.138565Z","shell.execute_reply.started":"2021-12-11T17:40:14.411527Z","shell.execute_reply":"2021-12-11T17:40:15.137928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model 2","metadata":{}},{"cell_type":"markdown","source":"### Build Network","metadata":{}},{"cell_type":"code","source":"# Use this cell to construct a convolutional neural network model. \n# Your model should make use of each of the following layer types:\n#    Conv2D, MaxPooling2D, Dropout, BatchNormalization, Flatten, Dense\n# You can start by mimicking the architecture used in the \n# Aerial Cactus competetition, but you should explore different architectures\n# by adding more layers and/or adding more nodes in individual layers\n\nnp.random.seed(1)\ntf.random.set_seed(1)\n\ncnn2 = Sequential([\n    Conv2D(32, (3,3), activation = 'relu', padding = 'same', input_shape=(32,32,3)),\n    Conv2D(32, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.20),\n    BatchNormalization(),\n\n    Conv2D(64, (3,3), activation = 'relu', padding = 'same'),\n    Conv2D(64, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.6),\n    BatchNormalization(),\n    \n    Conv2D(128, (3,3), activation = 'relu', padding = 'same'),\n    Conv2D(128, (3,3), activation = 'relu', padding = 'same'),\n    MaxPooling2D(2,2),\n    Dropout(0.6),\n    BatchNormalization(),\n\n    Flatten(),\n    \n    Dense(32, activation='relu'),\n    Dropout(0.6),\n    Dense(16, activation='relu'),\n    Dropout(0.20),\n    BatchNormalization(),\n    # we have 2 here because we have 2 classes\n    Dense(2, activation='softmax')\n])\n\ncnn2.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:40:15.139981Z","iopub.execute_input":"2021-12-11T17:40:15.140438Z","iopub.status.idle":"2021-12-11T17:40:15.297836Z","shell.execute_reply.started":"2021-12-11T17:40:15.140401Z","shell.execute_reply":"2021-12-11T17:40:15.297148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Network","metadata":{}},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.001)\ncnn2.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:40:15.299250Z","iopub.execute_input":"2021-12-11T17:40:15.299485Z","iopub.status.idle":"2021-12-11T17:40:15.314171Z","shell.execute_reply.started":"2021-12-11T17:40:15.299451Z","shell.execute_reply":"2021-12-11T17:40:15.313530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn2.fit(\n    x = train_loader, \n    steps_per_epoch = TR_STEPS, \n    epochs = 50,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:40:15.315319Z","iopub.execute_input":"2021-12-11T17:40:15.315637Z","iopub.status.idle":"2021-12-11T17:47:48.742960Z","shell.execute_reply.started":"2021-12-11T17:40:15.315599Z","shell.execute_reply":"2021-12-11T17:47:48.742253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = h2.history\nprint(history.keys())","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:47:48.744491Z","iopub.execute_input":"2021-12-11T17:47:48.745316Z","iopub.status.idle":"2021-12-11T17:47:48.750120Z","shell.execute_reply.started":"2021-12-11T17:47:48.745277Z","shell.execute_reply":"2021-12-11T17:47:48.749420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Graph the result\n\nepoch_range = range(1, len(history['loss'])+1)\n\nplt.figure(figsize=[14,4])\n\nplt.subplot(1,3,1)\nplt.plot(epoch_range, history['loss'], label='Training')\nplt.plot(epoch_range, history['val_loss'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('Loss'); plt.title('Loss')\nplt.legend()\n\nplt.subplot(1,3,2)\nplt.plot(epoch_range, history['accuracy'], label='Training')\nplt.plot(epoch_range, history['val_accuracy'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('Accuracy'); plt.title('Accuracy')\nplt.legend()\n\nplt.subplot(1,3,3)\nplt.plot(epoch_range, history['auc_1'], label='Training')\nplt.plot(epoch_range, history['val_auc_1'], label='Validation')\nplt.xlabel('Epoch'); plt.ylabel('AUC'); plt.title('AUC')\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:47:48.751552Z","iopub.execute_input":"2021-12-11T17:47:48.752329Z","iopub.status.idle":"2021-12-11T17:47:49.440823Z","shell.execute_reply.started":"2021-12-11T17:47:48.752291Z","shell.execute_reply":"2021-12-11T17:47:49.440144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save Model and History","metadata":{}},{"cell_type":"code","source":"\ncnn2.save('cancer_model.h5')\npickle.dump(history, open(f'cancer_history.pkl', 'wb'))","metadata":{"execution":{"iopub.status.busy":"2021-12-11T17:50:40.421945Z","iopub.execute_input":"2021-12-11T17:50:40.422546Z","iopub.status.idle":"2021-12-11T17:50:40.508733Z","shell.execute_reply.started":"2021-12-11T17:50:40.422504Z","shell.execute_reply":"2021-12-11T17:50:40.507945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}