{"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":"# Histopathologic Cancer Detection\n## Identify metastatic tissue in histopathologic scans of lymph node sections","metadata":{}},{"cell_type":"markdown","source":"# About the images","metadata":{}},{"cell_type":"markdown","source":"#### There are 220,025 training images and 57,456 test images.\n#### The images are 96x96 pixels and are full color.","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# Import Packages","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nimport pickle\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import *\n\nimport zipfile ","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:22.910120Z","iopub.execute_input":"2021-11-14T15:33:22.910510Z","iopub.status.idle":"2021-11-14T15:33:28.418488Z","shell.execute_reply.started":"2021-11-14T15:33:22.910436Z","shell.execute_reply":"2021-11-14T15:33:28.417578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Working Directory","metadata":{}},{"cell_type":"code","source":"working_dir = '../input/histopathologic-cancer-detection'\nos.listdir(working_dir)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:28.424224Z","iopub.execute_input":"2021-11-14T15:33:28.424423Z","iopub.status.idle":"2021-11-14T15:33:28.434958Z","shell.execute_reply.started":"2021-11-14T15:33:28.424393Z","shell.execute_reply":"2021-11-14T15:33:28.434190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label as per csv file¶","metadata":{}},{"cell_type":"markdown","source":"#### 0 = no tumor tissue\n#### 1 = has tumor tissue","metadata":{}},{"cell_type":"markdown","source":"# Number of images in the train and test folder","metadata":{}},{"cell_type":"code","source":"print('Number of images in train set',len(os.listdir('../input/histopathologic-cancer-detection/train')))\nprint('Number of images in test set',len(os.listdir('../input/histopathologic-cancer-detection/test')))","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:28.436209Z","iopub.execute_input":"2021-11-14T15:33:28.436515Z","iopub.status.idle":"2021-11-14T15:33:30.631566Z","shell.execute_reply.started":"2021-11-14T15:33:28.436480Z","shell.execute_reply":"2021-11-14T15:33:30.630886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Training DataFrame","metadata":{}},{"cell_type":"code","source":"# Load the training data into a DataFrame named 'train'.\ntrain = pd.read_csv(f'../input/histopathologic-cancer-detection/train_labels.csv',dtype = 'str')\n\n# Print the shape of the resulting DataFrame.\nprint('Training set size', train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:30.634015Z","iopub.execute_input":"2021-11-14T15:33:30.634513Z","iopub.status.idle":"2021-11-14T15:33:31.086321Z","shell.execute_reply.started":"2021-11-14T15:33:30.634474Z","shell.execute_reply":"2021-11-14T15:33:31.085527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display the first few rows of the dataframe.\ntrain.head(10) ","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:31.087686Z","iopub.execute_input":"2021-11-14T15:33:31.088123Z","iopub.status.idle":"2021-11-14T15:33:31.103120Z","shell.execute_reply.started":"2021-11-14T15:33:31.088084Z","shell.execute_reply":"2021-11-14T15:33:31.102311Z"},"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-14T15:33:31.104531Z","iopub.execute_input":"2021-11-14T15:33:31.104783Z","iopub.status.idle":"2021-11-14T15:33:31.191912Z","shell.execute_reply.started":"2021-11-14T15:33:31.104749Z","shell.execute_reply":"2021-11-14T15:33:31.191196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label Distribution","metadata":{}},{"cell_type":"code","source":"#Let's check the class distribution\n#train['label'].value_counts()\ntrain.label.value_counts() ","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:31.193208Z","iopub.execute_input":"2021-11-14T15:33:31.193621Z","iopub.status.idle":"2021-11-14T15:33:31.227098Z","shell.execute_reply.started":"2021-11-14T15:33:31.193582Z","shell.execute_reply":"2021-11-14T15:33:31.226257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Let's check the class distribution in proportion\n#y_train = train.label\nround((train.label.value_counts() / len(train)).to_frame()*100,2)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:31.228581Z","iopub.execute_input":"2021-11-14T15:33:31.229069Z","iopub.status.idle":"2021-11-14T15:33:31.267588Z","shell.execute_reply.started":"2021-11-14T15:33:31.229026Z","shell.execute_reply":"2021-11-14T15:33:31.266755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_size = 160000\ntrain = train.sample(sample_size, random_state=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:31.269077Z","iopub.execute_input":"2021-11-14T15:33:31.269353Z","iopub.status.idle":"2021-11-14T15:33:31.296638Z","shell.execute_reply.started":"2021-11-14T15:33:31.269318Z","shell.execute_reply":"2021-11-14T15:33:31.295926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# View Sample of Images","metadata":{}},{"cell_type":"code","source":"#display 16 images\n\nsample = train.sample(n=16).reset_index()\nplt.figure(figsize=(6,6)) # specifying the overall grid size\n\nfor i, row in sample.iterrows():  \n    img = mpimg.imread(f'../input/histopathologic-cancer-detection/train/{row.id}')\n    label = row.label\n    \n    plt.subplot(4,4,i+1)    # the number of images in the grid is 6*6 (16)\n    plt.imshow(img)\n    plt.text(0, -5, f'Class {label}', color='k')\n    plt.axis('off')\n    \nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:31.297863Z","iopub.execute_input":"2021-11-14T15:33:31.298144Z","iopub.status.idle":"2021-11-14T15:33:32.301295Z","shell.execute_reply.started":"2021-11-14T15:33:31.298110Z","shell.execute_reply":"2021-11-14T15:33:32.300445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data generator","metadata":{}},{"cell_type":"code","source":"# Split the dataframe train into two DataFrames named train_df and valid_df. \n\ntrain_df, valid_df = train_test_split(train, test_size=0.20, random_state=1, stratify=train.label)\n\nprint(train_df.shape)\nprint(valid_df.shape)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:32.302204Z","iopub.execute_input":"2021-11-14T15:33:32.302417Z","iopub.status.idle":"2021-11-14T15:33:32.560373Z","shell.execute_reply.started":"2021-11-14T15:33:32.302389Z","shell.execute_reply":"2021-11-14T15:33:32.559452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Create image data generators for both the training set and the validation set. \n# Here we 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-14T15:33:32.561949Z","iopub.execute_input":"2021-11-14T15:33:32.562248Z","iopub.status.idle":"2021-11-14T15:33:32.566871Z","shell.execute_reply.started":"2021-11-14T15:33:32.562210Z","shell.execute_reply":"2021-11-14T15:33:32.566160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_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 = (64,64)\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 = (64,64)\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:33:32.570220Z","iopub.execute_input":"2021-11-14T15:33:32.570728Z","iopub.status.idle":"2021-11-14T15:35:26.836409Z","shell.execute_reply.started":"2021-11-14T15:33:32.570689Z","shell.execute_reply":"2021-11-14T15:35:26.834766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's determine the number of training and validation batches. \n\nTR_STEPS = len(train_loader)\nVA_STEPS = len(valid_loader)\n\nprint('Number of batches in the training set:',TR_STEPS)\nprint('Number of batches in the validation set:',VA_STEPS)","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:35:26.837855Z","iopub.execute_input":"2021-11-14T15:35:26.838167Z","iopub.status.idle":"2021-11-14T15:35:26.844654Z","shell.execute_reply.started":"2021-11-14T15:35:26.838127Z","shell.execute_reply":"2021-11-14T15:35:26.843919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build network","metadata":{}},{"cell_type":"code","source":"np.random.seed(1)\ntf.random.set_seed(1)\n\ncnn_model = Sequential([\n    Conv2D(filters=32, kernel_size=(3,3), padding='valid', activation='relu', input_shape=(64,64,3)),\n    Conv2D(filters=32, kernel_size=(3,3), padding='valid', activation='relu'),\n    MaxPooling2D(2,2),\n    Dropout(0.25),\n    BatchNormalization(),\n\n    Conv2D(filters=64, kernel_size=(3,3), padding='valid', activation='relu'),\n    Conv2D(filters=64, kernel_size=(3,3), padding='valid', activation='relu'),\n    MaxPooling2D(2,2),\n    Dropout(0.25),\n    BatchNormalization(),\n\n    Flatten(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.25),\n    Dense(64, activation='relu'),\n    Dropout(0.25),\n    Dense(32, activation='relu'),\n    Dropout(0.25),\n    BatchNormalization(),\n    Dense(2, activation='softmax')\n])\n \n\ncnn_model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:35:26.846127Z","iopub.execute_input":"2021-11-14T15:35:26.847079Z","iopub.status.idle":"2021-11-14T15:35:29.492213Z","shell.execute_reply.started":"2021-11-14T15:35:26.847039Z","shell.execute_reply":"2021-11-14T15:35:29.491405Z"},"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# And then compile the model. \nimport tensorflow as tf\n\nopt = tf.keras.optimizers.Adam(0.001)\ncnn_model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy',tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2021-11-14T15:35:29.493478Z","iopub.execute_input":"2021-11-14T15:35:29.493816Z","iopub.status.idle":"2021-11-14T15:35:29.513376Z","shell.execute_reply.started":"2021-11-14T15:35:29.493776Z","shell.execute_reply":"2021-11-14T15:35:29.512724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh1 = cnn_model.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-11-14T15:35:29.514515Z","iopub.execute_input":"2021-11-14T15:35:29.514825Z","iopub.status.idle":"2021-11-14T17:25:12.943345Z","shell.execute_reply.started":"2021-11-14T15:35:29.514789Z","shell.execute_reply":"2021-11-14T17:25:12.942586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training Kurves","metadata":{}},{"cell_type":"code","source":"history = h1.history\nprint(history.keys())","metadata":{"execution":{"iopub.status.busy":"2021-11-14T17:25:12.944801Z","iopub.execute_input":"2021-11-14T17:25:12.945254Z","iopub.status.idle":"2021-11-14T17:25:12.951293Z","shell.execute_reply.started":"2021-11-14T17:25:12.945213Z","shell.execute_reply":"2021-11-14T17:25:12.950595Z"},"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-14T17:25:12.952728Z","iopub.execute_input":"2021-11-14T17:25:12.953240Z","iopub.status.idle":"2021-11-14T17:25:13.474432Z","shell.execute_reply.started":"2021-11-14T17:25:12.953205Z","shell.execute_reply":"2021-11-14T17:25:13.473790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Same model and history","metadata":{}},{"cell_type":"code","source":"# save the model and the combined history dictionary to files.\ncnn_model.save('cancer_model_v03.h5')\npickle.dump(history, open(f'cancer_history_v03.pkl', 'wb'))","metadata":{"execution":{"iopub.status.busy":"2021-11-14T17:25:49.369492Z","iopub.execute_input":"2021-11-14T17:25:49.369754Z","iopub.status.idle":"2021-11-14T17:25:49.463532Z","shell.execute_reply.started":"2021-11-14T17:25:49.369725Z","shell.execute_reply":"2021-11-14T17:25:49.462808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}