{"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":30176,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Histopathologic Cancer Detection By Team\n","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-08T14:07:23.523329Z","iopub.execute_input":"2024-05-08T14:07:23.524213Z","iopub.status.idle":"2024-05-08T14:07:31.455425Z","shell.execute_reply.started":"2024-05-08T14:07:23.524095Z","shell.execute_reply":"2024-05-08T14:07:31.454635Z"},"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-08T14:07:31.457235Z","iopub.execute_input":"2024-05-08T14:07:31.457562Z","iopub.status.idle":"2024-05-08T14:07:31.470194Z","shell.execute_reply.started":"2024-05-08T14:07:31.457516Z","shell.execute_reply":"2024-05-08T14:07:31.468947Z"},"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-08T14:07:31.471857Z","iopub.execute_input":"2024-05-08T14:07:31.472209Z","iopub.status.idle":"2024-05-08T14:07:31.909725Z","shell.execute_reply.started":"2024-05-08T14:07:31.472163Z","shell.execute_reply":"2024-05-08T14:07:31.908471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:07:31.912326Z","iopub.execute_input":"2024-05-08T14:07:31.912704Z","iopub.status.idle":"2024-05-08T14:07:31.93848Z","shell.execute_reply.started":"2024-05-08T14:07:31.912648Z","shell.execute_reply":"2024-05-08T14:07:31.937522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.id = train.id + '.tif'\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:07:31.939696Z","iopub.execute_input":"2024-05-08T14:07:31.939962Z","iopub.status.idle":"2024-05-08T14:07:31.997588Z","shell.execute_reply.started":"2024-05-08T14:07:31.939931Z","shell.execute_reply":"2024-05-08T14:07:31.996688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:07:31.99893Z","iopub.execute_input":"2024-05-08T14:07:31.99927Z","iopub.status.idle":"2024-05-08T14:07:32.010486Z","shell.execute_reply.started":"2024-05-08T14:07:31.999234Z","shell.execute_reply":"2024-05-08T14:07:32.009332Z"},"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-08T14:07:32.011809Z","iopub.execute_input":"2024-05-08T14:07:32.012063Z","iopub.status.idle":"2024-05-08T14:07:32.067238Z","shell.execute_reply.started":"2024-05-08T14:07:32.012032Z","shell.execute_reply":"2024-05-08T14:07:32.066003Z"},"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-08T14:07:32.068718Z","iopub.execute_input":"2024-05-08T14:07:32.069056Z","iopub.status.idle":"2024-05-08T14:07:33.098479Z","shell.execute_reply.started":"2024-05-08T14:07:32.069018Z","shell.execute_reply":"2024-05-08T14:07:33.097478Z"},"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-08T14:07:33.099848Z","iopub.execute_input":"2024-05-08T14:07:33.100113Z","iopub.status.idle":"2024-05-08T14:07:33.505515Z","shell.execute_reply.started":"2024-05-08T14:07:33.100082Z","shell.execute_reply":"2024-05-08T14:07:33.504638Z"},"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-08T14:07:33.508954Z","iopub.execute_input":"2024-05-08T14:07:33.50936Z","iopub.status.idle":"2024-05-08T14:07:33.51492Z","shell.execute_reply.started":"2024-05-08T14:07:33.509311Z","shell.execute_reply":"2024-05-08T14:07:33.513941Z"},"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-08T14:07:33.516153Z","iopub.execute_input":"2024-05-08T14:07:33.516385Z","iopub.status.idle":"2024-05-08T14:10:35.937853Z","shell.execute_reply.started":"2024-05-08T14:07:33.516351Z","shell.execute_reply":"2024-05-08T14:10:35.936917Z"},"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-08T14:10:35.939132Z","iopub.execute_input":"2024-05-08T14:10:35.939358Z","iopub.status.idle":"2024-05-08T14:10:35.945196Z","shell.execute_reply.started":"2024-05-08T14:10:35.939329Z","shell.execute_reply":"2024-05-08T14:10:35.944299Z"},"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-08T14:28:05.139502Z","iopub.execute_input":"2024-05-08T14:28:05.139894Z","iopub.status.idle":"2024-05-08T14:28:25.508348Z","shell.execute_reply.started":"2024-05-08T14:28:05.139853Z","shell.execute_reply":"2024-05-08T14:28:25.506957Z"},"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-08T14:10:56.831748Z","iopub.status.idle":"2024-05-08T14:10:56.832286Z","shell.execute_reply.started":"2024-05-08T14:10:56.83201Z","shell.execute_reply":"2024-05-08T14:10:56.832037Z"},"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-08T14:10:56.834034Z","iopub.status.idle":"2024-05-08T14:10:56.834393Z","shell.execute_reply.started":"2024-05-08T14:10:56.834206Z","shell.execute_reply":"2024-05-08T14:10:56.834225Z"},"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 = 10,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.835999Z","iopub.status.idle":"2024-05-08T14:10:56.836351Z","shell.execute_reply.started":"2024-05-08T14:10:56.836167Z","shell.execute_reply":"2024-05-08T14:10:56.836185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.838167Z","iopub.status.idle":"2024-05-08T14:10:56.838545Z","shell.execute_reply.started":"2024-05-08T14:10:56.838342Z","shell.execute_reply":"2024-05-08T14:10:56.838371Z"},"trusted":true},"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-08T14:10:56.840203Z","iopub.status.idle":"2024-05-08T14:10:56.84063Z","shell.execute_reply.started":"2024-05-08T14:10:56.840377Z","shell.execute_reply":"2024-05-08T14:10:56.840395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.842259Z","iopub.status.idle":"2024-05-08T14:10:56.842622Z","shell.execute_reply.started":"2024-05-08T14:10:56.842416Z","shell.execute_reply":"2024-05-08T14:10:56.842434Z"},"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 = 10,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.844153Z","iopub.status.idle":"2024-05-08T14:10:56.844484Z","shell.execute_reply.started":"2024-05-08T14:10:56.844307Z","shell.execute_reply":"2024-05-08T14:10:56.844324Z"},"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-08T14:10:56.846181Z","iopub.status.idle":"2024-05-08T14:10:56.846545Z","shell.execute_reply.started":"2024-05-08T14:10:56.846343Z","shell.execute_reply":"2024-05-08T14:10:56.84637Z"},"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-08T14:10:56.849001Z","iopub.status.idle":"2024-05-08T14:10:56.849359Z","shell.execute_reply.started":"2024-05-08T14:10:56.849166Z","shell.execute_reply":"2024-05-08T14:10:56.849193Z"},"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 = 10,\n    validation_data = valid_loader, \n    validation_steps = VA_STEPS, \n    verbose = 1\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.850342Z","iopub.status.idle":"2024-05-08T14:10:56.850733Z","shell.execute_reply.started":"2024-05-08T14:10:56.850498Z","shell.execute_reply":"2024-05-08T14:10:56.850526Z"},"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-08T14:10:56.852601Z","iopub.status.idle":"2024-05-08T14:10:56.852991Z","shell.execute_reply.started":"2024-05-08T14:10:56.852803Z","shell.execute_reply":"2024-05-08T14:10:56.852822Z"},"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-08T14:10:56.854293Z","iopub.status.idle":"2024-05-08T14:10:56.8547Z","shell.execute_reply.started":"2024-05-08T14:10:56.854456Z","shell.execute_reply":"2024-05-08T14:10:56.854482Z"},"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-08T14:10:56.855741Z","iopub.status.idle":"2024-05-08T14:10:56.856073Z","shell.execute_reply.started":"2024-05-08T14:10:56.855896Z","shell.execute_reply":"2024-05-08T14:10:56.855913Z"},"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-08T14:10:56.857838Z","iopub.status.idle":"2024-05-08T14:10:56.858348Z","shell.execute_reply.started":"2024-05-08T14:10:56.858069Z","shell.execute_reply":"2024-05-08T14:10:56.858097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test['filename'] = test.id + '.tif'\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.859491Z","iopub.status.idle":"2024-05-08T14:10:56.860063Z","shell.execute_reply.started":"2024-05-08T14:10:56.859772Z","shell.execute_reply":"2024-05-08T14:10:56.8598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.861142Z","iopub.status.idle":"2024-05-08T14:10:56.861663Z","shell.execute_reply.started":"2024-05-08T14:10:56.861367Z","shell.execute_reply":"2024-05-08T14:10:56.861393Z"},"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-08T14:10:56.863246Z","iopub.status.idle":"2024-05-08T14:10:56.863797Z","shell.execute_reply.started":"2024-05-08T14:10:56.863473Z","shell.execute_reply":"2024-05-08T14:10:56.8635Z"},"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-08T14:10:56.865379Z","iopub.status.idle":"2024-05-08T14:10:56.865919Z","shell.execute_reply.started":"2024-05-08T14:10:56.865626Z","shell.execute_reply":"2024-05-08T14:10:56.865654Z"},"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-08T14:10:56.867123Z","iopub.status.idle":"2024-05-08T14:10:56.867652Z","shell.execute_reply.started":"2024-05-08T14:10:56.867351Z","shell.execute_reply":"2024-05-08T14:10:56.867377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(test_loader))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.869447Z","iopub.status.idle":"2024-05-08T14:10:56.87001Z","shell.execute_reply.started":"2024-05-08T14:10:56.869715Z","shell.execute_reply":"2024-05-08T14:10:56.869742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_probs[:10,].round(2))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.871533Z","iopub.status.idle":"2024-05-08T14:10:56.872065Z","shell.execute_reply.started":"2024-05-08T14:10:56.871844Z","shell.execute_reply":"2024-05-08T14:10:56.871874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred = np.argmax(test_probs, axis=1)\nprint(test_pred[:10])","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.873454Z","iopub.status.idle":"2024-05-08T14:10:56.873827Z","shell.execute_reply.started":"2024-05-08T14:10:56.873641Z","shell.execute_reply":"2024-05-08T14:10:56.873662Z"},"trusted":true},"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-08T14:10:56.875486Z","iopub.status.idle":"2024-05-08T14:10:56.875856Z","shell.execute_reply.started":"2024-05-08T14:10:56.875673Z","shell.execute_reply":"2024-05-08T14:10:56.875692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.label = test_probs[:,1]\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:10:56.877351Z","iopub.status.idle":"2024-05-08T14:10:56.877744Z","shell.execute_reply.started":"2024-05-08T14:10:56.877511Z","shell.execute_reply":"2024-05-08T14:10:56.877538Z"},"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-08T14:10:56.878757Z","iopub.status.idle":"2024-05-08T14:10:56.879125Z","shell.execute_reply.started":"2024-05-08T14:10:56.878927Z","shell.execute_reply":"2024-05-08T14:10:56.878952Z"},"trusted":true},"execution_count":null,"outputs":[]}]}