{"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":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import Packages","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import backend as K\nimport pickle\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 os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-21T20:03:09.237755Z","iopub.execute_input":"2021-11-21T20:03:09.238550Z","iopub.status.idle":"2021-11-21T20:03:14.878555Z","shell.execute_reply.started":"2021-11-21T20:03:09.238460Z","shell.execute_reply":"2021-11-21T20:03:14.877867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load dataframe","metadata":{}},{"cell_type":"code","source":"# Load the training data into a DataFrame named 'train'. \n# Print the shape of the resulting DataFrame. \n\n\ntrain = pd.read_csv(f'../input/histopathologic-cancer-detection/train_labels.csv', dtype=str)\n\nprint('Training Set Size:', train.shape)\n\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:06:06.974238Z","iopub.execute_input":"2021-11-21T20:06:06.974528Z","iopub.status.idle":"2021-11-21T20:06:07.509341Z","shell.execute_reply.started":"2021-11-21T20:06:06.974499Z","shell.execute_reply":"2021-11-21T20:06:07.508632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#The id in the csv file does not have .tif extension, let's add it.\ntrain['id'] = train['id'].apply(lambda x: f'{x}.tif')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:06:18.397670Z","iopub.execute_input":"2021-11-21T20:06:18.398375Z","iopub.status.idle":"2021-11-21T20:06:18.487930Z","shell.execute_reply.started":"2021-11-21T20:06:18.398336Z","shell.execute_reply":"2021-11-21T20:06:18.487107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label distribution","metadata":{}},{"cell_type":"code","source":"(train.label.value_counts() / len(train)).to_frame().sort_index().T","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:06:21.996324Z","iopub.execute_input":"2021-11-21T20:06:21.996621Z","iopub.status.idle":"2021-11-21T20:06:22.039785Z","shell.execute_reply.started":"2021-11-21T20:06:21.996590Z","shell.execute_reply":"2021-11-21T20:06:22.038987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# View sample images","metadata":{}},{"cell_type":"code","source":"train_path = \"../input/histopathologic-cancer-detection/train\"\nprint('Training Images:', len(os.listdir(train_path)))\n\nsample = train.sample(n=16).reset_index()\n\nplt.figure(figsize=(8,8))\n\nfor i, row in sample.iterrows():\n\n    img = mpimg.imread(f'../input/histopathologic-cancer-detection/train/{row.id}')    \n    label = row.label\n\n    plt.subplot(4,4,i+1)\n    plt.imshow(img)\n    plt.text(0, -5, f'Class {label}', color='k')\n        \n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:06:28.956967Z","iopub.execute_input":"2021-11-21T20:06:28.957617Z","iopub.status.idle":"2021-11-21T20:06:33.677210Z","shell.execute_reply.started":"2021-11-21T20:06:28.957581Z","shell.execute_reply":"2021-11-21T20:06:33.676591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data generators","metadata":{}},{"cell_type":"markdown","source":"In this section, we will split the labeled observations into training and validation sets. We will then create data loaders to feed the images into our neural network during training.","metadata":{}},{"cell_type":"code","source":"train_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-11-21T20:06:41.861879Z","iopub.execute_input":"2021-11-21T20:06:41.862149Z","iopub.status.idle":"2021-11-21T20:06:42.213686Z","shell.execute_reply.started":"2021-11-21T20:06:41.862120Z","shell.execute_reply":"2021-11-21T20:06:42.212152Z"},"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. \n\ntrain_datagen = ImageDataGenerator(rescale=1/255)\nvalid_datagen = ImageDataGenerator(rescale=1/255)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:08:19.584504Z","iopub.execute_input":"2021-11-21T20:08:19.584778Z","iopub.status.idle":"2021-11-21T20:08:19.589602Z","shell.execute_reply.started":"2021-11-21T20:08:19.584749Z","shell.execute_reply":"2021-11-21T20:08:19.588665Z"},"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 = train_path,\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 = (96,96)\n)\n\nvalid_loader = valid_datagen.flow_from_dataframe(\n    dataframe = valid_df,\n    directory = train_path,\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 = (96,96)\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:12:31.170635Z","iopub.execute_input":"2021-11-21T20:12:31.170906Z","iopub.status.idle":"2021-11-21T20:15:20.221777Z","shell.execute_reply.started":"2021-11-21T20:12:31.170875Z","shell.execute_reply":"2021-11-21T20:15:20.221082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TR_STEPS = len(train_loader)\nVA_STEPS = len(valid_loader)\n\nprint(TR_STEPS)\nprint(VA_STEPS)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:20:48.184517Z","iopub.execute_input":"2021-11-21T20:20:48.184797Z","iopub.status.idle":"2021-11-21T20:20:48.190254Z","shell.execute_reply.started":"2021-11-21T20:20:48.184767Z","shell.execute_reply":"2021-11-21T20:20:48.189502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Network","metadata":{}},{"cell_type":"code","source":"base_model = tf.keras.applications.VGG16(input_shape=(96,96,3),\n                                         include_top=False,\n                                         weights='imagenet')\n\nbase_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:20:55.281495Z","iopub.execute_input":"2021-11-21T20:20:55.281744Z","iopub.status.idle":"2021-11-21T20:20:58.354175Z","shell.execute_reply.started":"2021-11-21T20:20:55.281717Z","shell.execute_reply":"2021-11-21T20:20:58.353418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:21:09.927464Z","iopub.execute_input":"2021-11-21T20:21:09.928143Z","iopub.status.idle":"2021-11-21T20:21:09.944535Z","shell.execute_reply.started":"2021-11-21T20:21:09.928103Z","shell.execute_reply":"2021-11-21T20:21:09.943873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    base_model,\n    \n    Flatten(),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.5),\n    Dense(32, activation='relu'),\n    Dropout(0.25),\n    BatchNormalization(),\n    Dense(2, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:21:17.231156Z","iopub.execute_input":"2021-11-21T20:21:17.231438Z","iopub.status.idle":"2021-11-21T20:21:17.335067Z","shell.execute_reply.started":"2021-11-21T20:21:17.231411Z","shell.execute_reply":"2021-11-21T20:21:17.334410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train Network","metadata":{}},{"cell_type":"code","source":"# Define an optimizer and select a learning rate. \n# Then compile the model. \n\nopt = tf.keras.optimizers.Adam(0.001)\ncnn.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:23:51.405647Z","iopub.execute_input":"2021-11-21T20:23:51.405917Z","iopub.status.idle":"2021-11-21T20:23:51.428530Z","shell.execute_reply.started":"2021-11-21T20:23:51.405888Z","shell.execute_reply":"2021-11-21T20:23:51.427871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\n# Complete one or more training runs. \n# Display training curves after each run. \n\nh1 = cnn.fit(\n    x = train_loader, \n    steps_per_epoch = TR_STEPS, \n    epochs = 15,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)\n\nhistory = h1.history\nprint(history.keys())","metadata":{"execution":{"iopub.status.busy":"2021-11-21T20:24:11.460538Z","iopub.execute_input":"2021-11-21T20:24:11.460786Z","iopub.status.idle":"2021-11-21T22:00:18.359787Z","shell.execute_reply.started":"2021-11-21T20:24:11.460758Z","shell.execute_reply":"2021-11-21T22:00:18.358589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epoch_range = range(1, len(history['loss'])+1)\n\nplt.figure(figsize=[14,4])\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()\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()\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()\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T22:05:56.706979Z","iopub.execute_input":"2021-11-21T22:05:56.707518Z","iopub.status.idle":"2021-11-21T22:05:57.236602Z","shell.execute_reply.started":"2021-11-21T22:05:56.707483Z","shell.execute_reply":"2021-11-21T22:05:57.235793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training Run 2","metadata":{}},{"cell_type":"code","source":"tf.keras.backend.set_value(cnn.optimizer.learning_rate, 0.0001)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T22:06:13.758768Z","iopub.execute_input":"2021-11-21T22:06:13.759442Z","iopub.status.idle":"2021-11-21T22:06:13.764993Z","shell.execute_reply.started":"2021-11-21T22:06:13.759403Z","shell.execute_reply":"2021-11-21T22:06:13.764242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn.fit(\n    x = train_loader, \n    steps_per_epoch = TR_STEPS, \n    epochs = 20,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T22:07:01.571102Z","iopub.execute_input":"2021-11-21T22:07:01.571361Z","iopub.status.idle":"2021-11-21T23:54:22.439775Z","shell.execute_reply.started":"2021-11-21T22:07:01.571333Z","shell.execute_reply":"2021-11-21T23:54:22.439087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for k in history.keys():\n    history[k] += h2.history[k]\n\nepoch_range = range(1, len(history['loss'])+1)\n\nplt.figure(figsize=[14,4])\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()\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()\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()\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T23:57:16.189373Z","iopub.execute_input":"2021-11-21T23:57:16.189643Z","iopub.status.idle":"2021-11-21T23:57:16.716576Z","shell.execute_reply.started":"2021-11-21T23:57:16.189613Z","shell.execute_reply":"2021-11-21T23:57:16.715944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save model and history","metadata":{}},{"cell_type":"code","source":"cnn.save('cancer_model_v00.h5')\npickle.dump(history, open(f'cancer_history_v00.pkl', 'wb'))","metadata":{"execution":{"iopub.status.busy":"2021-11-21T23:57:43.724940Z","iopub.execute_input":"2021-11-21T23:57:43.725193Z","iopub.status.idle":"2021-11-21T23:57:43.883132Z","shell.execute_reply.started":"2021-11-21T23:57:43.725167Z","shell.execute_reply":"2021-11-21T23:57:43.882424Z"},"trusted":true},"execution_count":null,"outputs":[]}]}