{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","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":30177,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Histopathic Cancer Detection (HCD)\n### Taylor Kern","metadata":{}},{"cell_type":"markdown","source":"# Prepare Enviornment","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nimport os\n\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import * \n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import backend as k\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:24:20.851453Z","iopub.execute_input":"2024-05-30T12:24:20.851761Z","iopub.status.idle":"2024-05-30T12:24:26.981636Z","shell.execute_reply.started":"2024-05-30T12:24:20.851677Z","shell.execute_reply":"2024-05-30T12:24:26.980835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Helper Functions","metadata":{}},{"cell_type":"code","source":"def merge_history(hlist):\n    history = {}\n    for k in hlist[0].history.keys():\n        history[k] = sum([h.history[k] for h in hlist], [])\n    return history\n\ndef vis_training(h, start=1):\n    epoch_range = range(start, len(h['loss'])+1)\n    s = slice(start-1, None)\n\n    plt.figure(figsize=[14,4])\n\n    n = int(len(h.keys()) / 2)\n\n    for i in range(n):\n        k = list(h.keys())[i]\n        plt.subplot(1,n,i+1)\n        plt.plot(epoch_range, h[k][s], label='Training')\n        plt.plot(epoch_range, h['val_' + k][s], label='Validation')\n        plt.xlabel('Epoch'); plt.ylabel(k); plt.title(k)\n        plt.grid()\n        plt.legend()\n\n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:24:33.020152Z","iopub.execute_input":"2024-05-30T12:24:33.020913Z","iopub.status.idle":"2024-05-30T12:24:33.030326Z","shell.execute_reply.started":"2024-05-30T12:24:33.020872Z","shell.execute_reply":"2024-05-30T12:24:33.029479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Training 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":"2024-05-30T12:24:41.314955Z","iopub.execute_input":"2024-05-30T12:24:41.315725Z","iopub.status.idle":"2024-05-30T12:24:41.670925Z","shell.execute_reply.started":"2024-05-30T12:24:41.315683Z","shell.execute_reply":"2024-05-30T12:24:41.670182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:24:44.254568Z","iopub.execute_input":"2024-05-30T12:24:44.255408Z","iopub.status.idle":"2024-05-30T12:24:44.273819Z","shell.execute_reply.started":"2024-05-30T12:24:44.255366Z","shell.execute_reply":"2024-05-30T12:24:44.273027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.id = train.id + '.tif'\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:24:51.274700Z","iopub.execute_input":"2024-05-30T12:24:51.274980Z","iopub.status.idle":"2024-05-30T12:24:51.321781Z","shell.execute_reply.started":"2024-05-30T12:24:51.274950Z","shell.execute_reply":"2024-05-30T12:24:51.321123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:24:53.734608Z","iopub.execute_input":"2024-05-30T12:24:53.734868Z","iopub.status.idle":"2024-05-30T12:24:53.743856Z","shell.execute_reply.started":"2024-05-30T12:24:53.734842Z","shell.execute_reply":"2024-05-30T12:24:53.743114Z"},"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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:25:00.882470Z","iopub.execute_input":"2024-05-30T12:25:00.883227Z","iopub.status.idle":"2024-05-30T12:25:00.923068Z","shell.execute_reply.started":"2024-05-30T12:25:00.883190Z","shell.execute_reply":"2024-05-30T12:25:00.922358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Extract Images","metadata":{}},{"cell_type":"code","source":"train_path = \"../input/histopathologic-cancer-detection/train\"\n\nsample = train.sample(n=16).reset_index()\n\nplt.figure(figsize=(6,6))\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":"2024-05-30T12:25:09.295796Z","iopub.execute_input":"2024-05-30T12:25:09.296124Z","iopub.status.idle":"2024-05-30T12:25:10.174230Z","shell.execute_reply.started":"2024-05-30T12:25:09.296069Z","shell.execute_reply":"2024-05-30T12:25:10.173493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training and Validation Sets","metadata":{}},{"cell_type":"code","source":"train_df, valid_df = train_test_split(train, test_size=0.2, random_state=1, stratify=train.label)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:25:17.343000Z","iopub.execute_input":"2024-05-30T12:25:17.343650Z","iopub.status.idle":"2024-05-30T12:25:17.664959Z","shell.execute_reply.started":"2024-05-30T12:25:17.343610Z","shell.execute_reply":"2024-05-30T12:25:17.664313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Generators","metadata":{}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1/255)\nvalidation_datagen = ImageDataGenerator(rescale=1/255)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:25:23.923372Z","iopub.execute_input":"2024-05-30T12:25:23.924057Z","iopub.status.idle":"2024-05-30T12:25:23.928432Z","shell.execute_reply.started":"2024-05-30T12:25:23.924017Z","shell.execute_reply":"2024-05-30T12:25:23.927647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 64\n\ntrain_loader = train_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)\n\nvalid_loader = train_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":"2024-05-30T12:25:31.774417Z","iopub.execute_input":"2024-05-30T12:25:31.774705Z","iopub.status.idle":"2024-05-30T12:27:13.736514Z","shell.execute_reply.started":"2024-05-30T12:25:31.774673Z","shell.execute_reply":"2024-05-30T12:27:13.735802Z"},"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":"2024-05-30T12:27:33.661688Z","iopub.execute_input":"2024-05-30T12:27:33.661923Z","iopub.status.idle":"2024-05-30T12:27:33.671963Z","shell.execute_reply.started":"2024-05-30T12:27:33.661868Z","shell.execute_reply":"2024-05-30T12:27:33.671149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Base Model","metadata":{}},{"cell_type":"code","source":"base_model = tf.keras.applications.VGG19(\n    input_shape=(96,96,3), \n    include_top=False, \n    weights='imagenet'\n)\n\nbase_model.trainable = False\n\nbase_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:27:41.055066Z","iopub.execute_input":"2024-05-30T12:27:41.055336Z","iopub.status.idle":"2024-05-30T12:27:44.630175Z","shell.execute_reply.started":"2024-05-30T12:27:41.055306Z","shell.execute_reply":"2024-05-30T12:27:44.629534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build and Train","metadata":{}},{"cell_type":"code","source":"np.random.seed(1)\ntf.random.set_seed(1)\n\ncnn = Sequential([\n    base_model,\n    BatchNormalization(),\n\n    Flatten(),\n    \n    Dense(16, activation='relu'),\n    Dropout(0.5),\n    Dense(8, activation='relu'),\n    Dropout(0.5),\n    BatchNormalization(),\n    Dense(2, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:27:53.756759Z","iopub.execute_input":"2024-05-30T12:27:53.757420Z","iopub.status.idle":"2024-05-30T12:27:53.887808Z","shell.execute_reply.started":"2024-05-30T12:27:53.757385Z","shell.execute_reply":"2024-05-30T12:27:53.887050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.001)\ncnn.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:28:01.342554Z","iopub.execute_input":"2024-05-30T12:28:01.342914Z","iopub.status.idle":"2024-05-30T12:28:01.364097Z","shell.execute_reply.started":"2024-05-30T12:28:01.342865Z","shell.execute_reply":"2024-05-30T12:28:01.363482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh1 = cnn.fit(\n    x = train_loader, \n    steps_per_epoch = TR_STEPS, \n    epochs = 40,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T12:28:04.244488Z","iopub.execute_input":"2024-05-30T12:28:04.245277Z","iopub.status.idle":"2024-05-30T13:48:13.291446Z","shell.execute_reply.started":"2024-05-30T12:28:04.245241Z","shell.execute_reply":"2024-05-30T13:48:13.290623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Fine Tuning","metadata":{}},{"cell_type":"code","source":"base_model.trainable = True\nk.set_value(cnn.optimizer.learning_rate, 0.00001)\ncnn.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])","metadata":{"execution":{"iopub.status.busy":"2024-05-30T13:49:02.775919Z","iopub.execute_input":"2024-05-30T13:49:02.776542Z","iopub.status.idle":"2024-05-30T13:49:02.794221Z","shell.execute_reply.started":"2024-05-30T13:49:02.776502Z","shell.execute_reply":"2024-05-30T13:49:02.793619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T13:49:07.215780Z","iopub.execute_input":"2024-05-30T13:49:07.216400Z","iopub.status.idle":"2024-05-30T13:49:07.226516Z","shell.execute_reply.started":"2024-05-30T13:49:07.216366Z","shell.execute_reply":"2024-05-30T13:49:07.225833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train 2","metadata":{}},{"cell_type":"code","source":"%%time \n\nh2 = cnn.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":"2024-05-30T13:49:17.215462Z","iopub.execute_input":"2024-05-30T13:49:17.215768Z","iopub.status.idle":"2024-05-30T14:53:58.952288Z","shell.execute_reply.started":"2024-05-30T13:49:17.215735Z","shell.execute_reply":"2024-05-30T14:53:58.951552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h2.history['auc'] = h2.history['auc_1']\nh2.history['val_auc'] = h2.history['val_auc_1']","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:21.463332Z","iopub.execute_input":"2024-05-30T15:43:21.463618Z","iopub.status.idle":"2024-05-30T15:43:21.468355Z","shell.execute_reply.started":"2024-05-30T15:43:21.463562Z","shell.execute_reply":"2024-05-30T15:43:21.467603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:28.383961Z","iopub.execute_input":"2024-05-30T15:43:28.384235Z","iopub.status.idle":"2024-05-30T15:43:28.967178Z","shell.execute_reply.started":"2024-05-30T15:43:28.384205Z","shell.execute_reply":"2024-05-30T15:43:28.966425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training 3","metadata":{}},{"cell_type":"code","source":"%%time \n\nh3 = 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":"2024-05-30T14:59:25.644195Z","iopub.execute_input":"2024-05-30T14:59:25.644478Z","iopub.status.idle":"2024-05-30T15:42:29.072979Z","shell.execute_reply.started":"2024-05-30T14:59:25.644446Z","shell.execute_reply":"2024-05-30T15:42:29.072128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h3.history['auc'] = h3.history['auc_1'] \nh3.history['val_auc'] = h3.history['val_auc_1'] ","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:37.803619Z","iopub.execute_input":"2024-05-30T15:43:37.804381Z","iopub.status.idle":"2024-05-30T15:43:37.808389Z","shell.execute_reply.started":"2024-05-30T15:43:37.804347Z","shell.execute_reply":"2024-05-30T15:43:37.807508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2, h3])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:41.251337Z","iopub.execute_input":"2024-05-30T15:43:41.252037Z","iopub.status.idle":"2024-05-30T15:43:41.840528Z","shell.execute_reply.started":"2024-05-30T15:43:41.252004Z","shell.execute_reply":"2024-05-30T15:43:41.839813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.save('HCDv01.h5')\npickle.dump(history, open(f'HCDv01.pkl', 'wb'))","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:48.927407Z","iopub.execute_input":"2024-05-30T15:43:48.928111Z","iopub.status.idle":"2024-05-30T15:43:49.397016Z","shell.execute_reply.started":"2024-05-30T15:43:48.928072Z","shell.execute_reply":"2024-05-30T15:43:49.396231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"test = pd.read_csv('../input/histopathologic-cancer-detection/sample_submission.csv')\n\nprint('Test Set Size:', test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:43:58.183639Z","iopub.execute_input":"2024-05-30T15:43:58.183994Z","iopub.status.idle":"2024-05-30T15:43:58.274072Z","shell.execute_reply.started":"2024-05-30T15:43:58.183951Z","shell.execute_reply":"2024-05-30T15:43:58.273171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test['filename'] = test.id + '.tif'\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:44:08.383236Z","iopub.execute_input":"2024-05-30T15:44:08.383514Z","iopub.status.idle":"2024-05-30T15:44:08.398724Z","shell.execute_reply.started":"2024-05-30T15:44:08.383482Z","shell.execute_reply":"2024-05-30T15:44:08.398061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:44:11.631371Z","iopub.execute_input":"2024-05-30T15:44:11.632123Z","iopub.status.idle":"2024-05-30T15:44:11.641521Z","shell.execute_reply.started":"2024-05-30T15:44:11.632082Z","shell.execute_reply":"2024-05-30T15:44:11.640814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_path = \"../input/histopathologic-cancer-detection/test\"\nprint('Test Images:', len(os.listdir(test_path)))","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:44:17.833233Z","iopub.execute_input":"2024-05-30T15:44:17.833510Z","iopub.status.idle":"2024-05-30T15:44:18.774405Z","shell.execute_reply.started":"2024-05-30T15:44:17.833477Z","shell.execute_reply":"2024-05-30T15:44:18.773617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 64\n\ntest_datagen = ImageDataGenerator(rescale=1/255)\n\ntest_loader = test_datagen.flow_from_dataframe(\n    dataframe = test,\n    directory = test_path,\n    x_col = 'filename',\n    batch_size = BATCH_SIZE,\n    shuffle = False,\n    class_mode = None,\n    target_size = (96,96)\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:47:00.611371Z","iopub.execute_input":"2024-05-30T15:47:00.611981Z","iopub.status.idle":"2024-05-30T15:47:59.710883Z","shell.execute_reply.started":"2024-05-30T15:47:00.611936Z","shell.execute_reply":"2024-05-30T15:47:59.710117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_probs = cnn.predict(test_loader)\nprint(test_probs.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:49:43.723495Z","iopub.execute_input":"2024-05-30T15:49:43.724177Z","iopub.status.idle":"2024-05-30T15:50:02.864901Z","shell.execute_reply.started":"2024-05-30T15:49:43.724140Z","shell.execute_reply":"2024-05-30T15:50:02.863581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(test_loader))\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_probs[:10,].round(2))\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred = np.argmax(test_probs, axis=1)\nprint(test_pred[:10])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare Submission","metadata":{}},{"cell_type":"code","source":"submission = pd.read_csv('../input/histopathologic-cancer-detection/sample_submission.csv')\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:50:12.573124Z","iopub.execute_input":"2024-05-30T15:50:12.573397Z","iopub.status.idle":"2024-05-30T15:50:12.630492Z","shell.execute_reply.started":"2024-05-30T15:50:12.573366Z","shell.execute_reply":"2024-05-30T15:50:12.629761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.label = test_probs[:,1]\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:50:19.191718Z","iopub.execute_input":"2024-05-30T15:50:19.191994Z","iopub.status.idle":"2024-05-30T15:50:19.215280Z","shell.execute_reply.started":"2024-05-30T15:50:19.191963Z","shell.execute_reply":"2024-05-30T15:50:19.214361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', header=True, index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T15:50:30.077908Z","iopub.execute_input":"2024-05-30T15:50:30.078175Z","iopub.status.idle":"2024-05-30T15:50:30.244303Z","shell.execute_reply.started":"2024-05-30T15:50:30.078144Z","shell.execute_reply":"2024-05-30T15:50:30.243636Z"},"trusted":true},"execution_count":null,"outputs":[]}]}