{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"#import packages\nimport 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 *\nfrom kerastuner.tuners import RandomSearch\nfrom kerastuner.engine.hyperparameters import HyperParameters","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-09T23:56:18.195031Z","iopub.execute_input":"2023-12-09T23:56:18.195379Z","iopub.status.idle":"2023-12-09T23:56:22.196279Z","shell.execute_reply.started":"2023-12-09T23:56:18.195348Z","shell.execute_reply":"2023-12-09T23:56:22.195314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#train and test folder\nprint('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":"2023-12-09T23:56:22.197569Z","iopub.execute_input":"2023-12-09T23:56:22.198235Z","iopub.status.idle":"2023-12-09T23:56:22.398884Z","shell.execute_reply.started":"2023-12-09T23:56:22.198197Z","shell.execute_reply":"2023-12-09T23:56:22.397964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the training data into a DataFrame. \n# Print the shape of the resulting DataFrame.\n\nhcd = pd.read_csv('/kaggle/input/histopathologic-cancer-detection/train_labels.csv')\nprint(hcd.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:22.399952Z","iopub.execute_input":"2023-12-09T23:56:22.400254Z","iopub.status.idle":"2023-12-09T23:56:22.622353Z","shell.execute_reply.started":"2023-12-09T23:56:22.400227Z","shell.execute_reply":"2023-12-09T23:56:22.621443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display the first few rows of the dataframe.\nhcd.head() ","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:22.625099Z","iopub.execute_input":"2023-12-09T23:56:22.625409Z","iopub.status.idle":"2023-12-09T23:56:22.637105Z","shell.execute_reply.started":"2023-12-09T23:56:22.625383Z","shell.execute_reply":"2023-12-09T23:56:22.636190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#label distrobution\n(hcd.label.value_counts() / len(hcd)).to_frame()","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:22.638308Z","iopub.execute_input":"2023-12-09T23:56:22.638599Z","iopub.status.idle":"2023-12-09T23:56:22.651096Z","shell.execute_reply.started":"2023-12-09T23:56:22.638573Z","shell.execute_reply":"2023-12-09T23:56:22.650091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Adding a variable for the image directory\nimg_dir = '/kaggle/input/histopathologic-cancer-detection/train'\n","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:22.652240Z","iopub.execute_input":"2023-12-09T23:56:22.652518Z","iopub.status.idle":"2023-12-09T23:56:22.660945Z","shell.execute_reply.started":"2023-12-09T23:56:22.652493Z","shell.execute_reply":"2023-12-09T23:56:22.659918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = hcd.sample(n=9).reset_index()\n\nplt.figure(figsize=(3,3))\n\nfor i, row in sample.iterrows():\n\n    img = mpimg.imread(f'{img_dir}/{row.id}.tif')    \n    label = row.label\n\n    plt.subplot(3,3,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":"2023-12-09T23:56:22.662199Z","iopub.execute_input":"2023-12-09T23:56:22.662917Z","iopub.status.idle":"2023-12-09T23:56:23.276420Z","shell.execute_reply.started":"2023-12-09T23:56:22.662890Z","shell.execute_reply":"2023-12-09T23:56:23.274971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#using data generators \ntrain_df, valid_df = train_test_split(hcd, test_size=0.2, random_state=39, stratify=hcd.label)\n\nprint(train_df.shape)\nprint(valid_df.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:23.277916Z","iopub.execute_input":"2023-12-09T23:56:23.278628Z","iopub.status.idle":"2023-12-09T23:56:23.405934Z","shell.execute_reply.started":"2023-12-09T23:56:23.278573Z","shell.execute_reply":"2023-12-09T23:56:23.404897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['id'] = train_df['id'] + '.tif'\nvalid_df['id'] = valid_df['id'] + '.tif'\n","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:23.407125Z","iopub.execute_input":"2023-12-09T23:56:23.407435Z","iopub.status.idle":"2023-12-09T23:56:23.468898Z","shell.execute_reply.started":"2023-12-09T23:56:23.407409Z","shell.execute_reply":"2023-12-09T23:56:23.468028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating Data Generators for CNN\ntrain_datagen = ImageDataGenerator(\n    rescale=1/255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\nvalid_datagen = ImageDataGenerator(rescale=1/255)\n\ntrain_df['label'] = train_df['label'].astype(str)\nvalid_df['label'] = valid_df['label'].astype(str)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=img_dir,\n    x_col='id',\n    y_col='label',\n    target_size=(96, 96),\n    batch_size=64,\n    class_mode='binary'\n)\n\nvalidation_generator = valid_datagen.flow_from_dataframe(\n    dataframe=valid_df,\n    directory=img_dir,\n    x_col='id',\n    y_col='label',\n    target_size=(96, 96),\n    batch_size=64,\n    class_mode='binary'\n)","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:56:23.470046Z","iopub.execute_input":"2023-12-09T23:56:23.470362Z","iopub.status.idle":"2023-12-09T23:57:51.003708Z","shell.execute_reply.started":"2023-12-09T23:56:23.470335Z","shell.execute_reply":"2023-12-09T23:57:51.002876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TR_STEPS = len(train_generator)\nVA_STEPS = len(validation_generator)\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":"2023-12-09T23:57:51.004864Z","iopub.execute_input":"2023-12-09T23:57:51.005160Z","iopub.status.idle":"2023-12-09T23:57:51.010535Z","shell.execute_reply.started":"2023-12-09T23:57:51.005122Z","shell.execute_reply":"2023-12-09T23:57:51.009572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model(hp):\n    model = Sequential()\n\n    # Convolutional layers\n    model.add(Conv2D(hp.Int('conv1_units', min_value=32, max_value=128, step=32), (3, 3), activation='relu', input_shape=(96, 96, 3)))\n    model.add(MaxPooling2D((2, 2)))\n\n    model.add(Conv2D(hp.Int('conv2_units', min_value=32, max_value=128, step=32), (3, 3), activation='relu'))\n    model.add(MaxPooling2D((2, 2)))\n\n    model.add(Conv2D(hp.Int('conv3_units', min_value=32, max_value=128, step=32), (3, 3), activation='relu'))\n    model.add(MaxPooling2D((2, 2)))\n\n    model.add(Flatten())\n\n    # Dense layers\n    model.add(Dense(hp.Int('dense_units', min_value=32, max_value=64, step=64), activation='relu'))\n\n    # Dropout layer\n    model.add(Dropout(hp.Float('dropout_rate', min_value=0.2, max_value=0.5, step=0.1)))\n\n    # Output layer\n    model.add(Dense(1, activation='sigmoid'))\n\n    # Compile the model\n    opt = tf.keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-1]))\n    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:57:51.011692Z","iopub.execute_input":"2023-12-09T23:57:51.011969Z","iopub.status.idle":"2023-12-09T23:57:51.033568Z","shell.execute_reply.started":"2023-12-09T23:57:51.011944Z","shell.execute_reply":"2023-12-09T23:57:51.032395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tuner = RandomSearch(\n    build_model,\n    objective='val_accuracy',\n    max_trials=3,  \n    directory='HCD_tuner_dir',  \n    project_name='HCD_SB_6'\n)\n\ntuner.search(train_generator, epochs=5, validation_data=validation_generator, validation_steps=VA_STEPS)\n\n# Get the best hyperparameters\nbest_hps = tuner.get_best_hyperparameters(num_trials=1)[0]","metadata":{"execution":{"iopub.status.busy":"2023-12-09T23:57:51.038097Z","iopub.execute_input":"2023-12-09T23:57:51.038522Z","iopub.status.idle":"2023-12-10T02:59:31.072879Z","shell.execute_reply.started":"2023-12-09T23:57:51.038463Z","shell.execute_reply":"2023-12-10T02:59:31.071929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_model = tuner.hypermodel.build(best_hps)","metadata":{"execution":{"iopub.status.busy":"2023-12-10T02:59:31.074243Z","iopub.execute_input":"2023-12-10T02:59:31.074944Z","iopub.status.idle":"2023-12-10T02:59:31.167607Z","shell.execute_reply.started":"2023-12-10T02:59:31.074907Z","shell.execute_reply":"2023-12-10T02:59:31.166828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h1 = final_model.fit(\n    train_generator,\n    steps_per_epoch=TR_STEPS,\n    epochs=3,\n    validation_data=validation_generator,\n    validation_steps=VA_STEPS,\n    verbose=1\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-10T02:59:31.168743Z","iopub.execute_input":"2023-12-10T02:59:31.169048Z","iopub.status.idle":"2023-12-10T03:33:49.934990Z","shell.execute_reply.started":"2023-12-10T02:59:31.169021Z","shell.execute_reply":"2023-12-10T03:33:49.933955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = h1.history\nepoch_range =range(1, len(history['loss'])+1)\n\nplt.figure(figsize=[14,4])\nplt.subplot(1,2,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,2,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.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-10T03:33:49.938740Z","iopub.execute_input":"2023-12-10T03:33:49.939048Z","iopub.status.idle":"2023-12-10T03:33:50.634647Z","shell.execute_reply.started":"2023-12-10T03:33:49.939021Z","shell.execute_reply":"2023-12-10T03:33:50.633661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the model\nfinal_model.save('HCD_SB_6_3_Model.h5')\n\n# Save the history\nwith open('HCD_SB_6_3_Model_history.pkl', 'wb') as file:\n    pickle.dump(h1.history, file)","metadata":{"execution":{"iopub.status.busy":"2023-12-10T03:35:03.027360Z","iopub.execute_input":"2023-12-10T03:35:03.027801Z","iopub.status.idle":"2023-12-10T03:35:03.073543Z","shell.execute_reply.started":"2023-12-10T03:35:03.027769Z","shell.execute_reply":"2023-12-10T03:35:03.072628Z"},"trusted":true},"execution_count":null,"outputs":[]}]}