{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-23T05:29:25.199611Z","iopub.execute_input":"2022-09-23T05:29:25.20018Z","iopub.status.idle":"2022-09-23T05:29:25.395339Z","shell.execute_reply.started":"2022-09-23T05:29:25.200081Z","shell.execute_reply":"2022-09-23T05:29:25.394306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport openslide\nfrom openslide import OpenSlide\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom tqdm import tqdm\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dropout \nfrom tensorflow.keras.layers import Conv2DTranspose\nfrom tensorflow.keras.layers import concatenate\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2022-09-23T05:32:31.870669Z","iopub.execute_input":"2022-09-23T05:32:31.871151Z","iopub.status.idle":"2022-09-23T05:32:37.488055Z","shell.execute_reply.started":"2022-09-23T05:32:31.87111Z","shell.execute_reply":"2022-09-23T05:32:37.487015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''!wget --no-check-certificate \\\n    https://storage.googleapis.com/mledu-datasets/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 \\\n    -O /tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'''","metadata":{"execution":{"iopub.status.busy":"2022-09-06T06:33:01.159453Z","iopub.execute_input":"2022-09-06T06:33:01.159847Z","iopub.status.idle":"2022-09-06T06:33:01.167039Z","shell.execute_reply.started":"2022-09-06T06:33:01.159814Z","shell.execute_reply":"2022-09-06T06:33:01.165581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras import layers\n\n# Set the weights file you downloaded into a variable\nlocal_weights_file = '../input/inepetion-v-3-weights/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\n# Initialize the base model.\n# Set the input shape and remove the dense layers.\npre_trained_model = InceptionV3(input_shape = (256, 256, 3), \n                                include_top = False, \n                                weights = None)\n\n# Load the pre-trained weights you downloaded.\npre_trained_model.load_weights(local_weights_file)\n\n# Freeze the weights of the layers.\nfor layer in pre_trained_model.layers:\n  layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:28:50.348471Z","iopub.execute_input":"2022-09-23T06:28:50.3491Z","iopub.status.idle":"2022-09-23T06:28:53.694709Z","shell.execute_reply.started":"2022-09-23T06:28:50.349065Z","shell.execute_reply":"2022-09-23T06:28:53.693749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pre_trained_model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-21T09:30:09.846813Z","iopub.execute_input":"2022-09-21T09:30:09.847867Z","iopub.status.idle":"2022-09-21T09:30:09.892311Z","shell.execute_reply.started":"2022-09-21T09:30:09.847818Z","shell.execute_reply":"2022-09-21T09:30:09.891297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Choose `mixed_7` as the last layer of your base model\nlast_layer = pre_trained_model.get_layer('mixed7')\nprint('last layer output shape: ', last_layer.output_shape)\nlast_output = last_layer.output","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:28:57.243786Z","iopub.execute_input":"2022-09-23T06:28:57.244138Z","iopub.status.idle":"2022-09-23T06:28:57.250888Z","shell.execute_reply.started":"2022-09-23T06:28:57.244106Z","shell.execute_reply":"2022-09-23T06:28:57.249731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras import Model\n\n# Flatten the output layer to 1 dimension\nx = layers.Flatten()(last_output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\nx = layers.Dense(1024, activation='relu')(x)\n# Add a dropout rate of 0.2\nx = layers.Dropout(0.2)(x)                  \n# Add a final sigmoid layer for classification\nx = layers.Dense  (1, activation='sigmoid')(x)           \n\n# Append the dense network to the base model\nmodel = Model(pre_trained_model.input, x) \n\n# Print the model summary. See your dense network connected at the end.\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:28:59.567915Z","iopub.execute_input":"2022-09-23T06:28:59.568278Z","iopub.status.idle":"2022-09-23T06:28:59.630729Z","shell.execute_reply.started":"2022-09-23T06:28:59.568246Z","shell.execute_reply":"2022-09-23T06:28:59.629617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = RMSprop(learning_rate=0.0001), \n              loss = 'binary_crossentropy', \n              metrics = ['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:29:13.060469Z","iopub.execute_input":"2022-09-23T06:29:13.061185Z","iopub.status.idle":"2022-09-23T06:29:13.075356Z","shell.execute_reply.started":"2022-09-23T06:29:13.061147Z","shell.execute_reply":"2022-09-23T06:29:13.074322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('../input/mayo-clinic-strip-ai/train.csv')\ntest_df  = pd.read_csv('../input/mayo-clinic-strip-ai/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:29:15.366608Z","iopub.execute_input":"2022-09-23T06:29:15.36767Z","iopub.status.idle":"2022-09-23T06:29:15.38316Z","shell.execute_reply.started":"2022-09-23T06:29:15.36761Z","shell.execute_reply":"2022-09-23T06:29:15.382271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[\"file_path\"] = train_df[\"image_id\"].apply(lambda x: \"../input/mayo-clinic-strip-ai/train/\" + x + \".tif\")\ntest_df[\"file_path\"]  = test_df[\"image_id\"].apply(lambda x: \"../input/mayo-clinic-strip-ai/test/\" + x + \".tif\")","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:29:17.958322Z","iopub.execute_input":"2022-09-23T06:29:17.958949Z","iopub.status.idle":"2022-09-23T06:29:17.96953Z","shell.execute_reply.started":"2022-09-23T06:29:17.958903Z","shell.execute_reply":"2022-09-23T06:29:17.968592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[\"target\"] = train_df[\"label\"].apply(lambda x : 1 if x==\"CE\" else 0)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:29:21.271391Z","iopub.execute_input":"2022-09-23T06:29:21.271895Z","iopub.status.idle":"2022-09-23T06:29:21.279363Z","shell.execute_reply.started":"2022-09-23T06:29:21.271837Z","shell.execute_reply":"2022-09-23T06:29:21.278168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_sample = train_df.iloc[:754].copy()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T05:33:04.290803Z","iopub.execute_input":"2022-09-23T05:33:04.291285Z","iopub.status.idle":"2022-09-23T05:33:04.299727Z","shell.execute_reply.started":"2022-09-23T05:33:04.291239Z","shell.execute_reply":"2022-09-23T05:33:04.297944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess(image_path):\n    slide=OpenSlide(image_path)\n    region= (1000,1000)    \n    size  = (5000, 5000)\n    image = slide.read_region(region, 0, size)\n    image = image.convert('RGB')\n    image = tf.image.resize(image, (256, 256))\n    image = np.array(image)    \n    return image\n\nx_train=[]\nfor i in tqdm(train_df_sample['file_path']):\n    x1=preprocess(i)\n    x_train.append(x1)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T05:47:37.851776Z","iopub.execute_input":"2022-09-23T05:47:37.852157Z","iopub.status.idle":"2022-09-23T06:26:22.950017Z","shell.execute_reply.started":"2022-09-23T05:47:37.852126Z","shell.execute_reply":"2022-09-23T06:26:22.948978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train=np.array(x_train)\ny_train=np.array(train_df_sample['target'])\n\nX_train,X_test,Y_train,Y_test=train_test_split(x_train,y_train,test_size=0.2)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T07:44:11.028123Z","iopub.execute_input":"2022-09-23T07:44:11.028524Z","iopub.status.idle":"2022-09-23T07:44:12.332329Z","shell.execute_reply.started":"2022-09-23T07:44:11.028489Z","shell.execute_reply":"2022-09-23T07:44:12.331287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentor = ImageDataGenerator(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# fit the training data\ndata_augmentor.fit(x_train)\n\naugment = data_augmentor.flow(x_train, batch_size=1)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T07:44:14.682416Z","iopub.execute_input":"2022-09-23T07:44:14.68313Z","iopub.status.idle":"2022-09-23T07:44:15.831021Z","shell.execute_reply.started":"2022-09-23T07:44:14.683092Z","shell.execute_reply":"2022-09-23T07:44:15.829951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train,Y_train,epochs=150,validation_data = (X_test,Y_test),batch_size = 32,verbose=1)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:57:10.18704Z","iopub.execute_input":"2022-09-23T06:57:10.187662Z","iopub.status.idle":"2022-09-23T07:02:28.024208Z","shell.execute_reply.started":"2022-09-23T06:57:10.187613Z","shell.execute_reply":"2022-09-23T07:02:28.023268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:57:01.093552Z","iopub.status.idle":"2022-09-23T06:57:01.09445Z","shell.execute_reply.started":"2022-09-23T06:57:01.094156Z","shell.execute_reply":"2022-09-23T06:57:01.094202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test1=[]\nfor i in test_df['file_path']:\n    x1=preprocess(i)\n    test1.append(x1)\ntest1=np.array(test1)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:40:51.343562Z","iopub.execute_input":"2022-09-23T06:40:51.344066Z","iopub.status.idle":"2022-09-23T06:41:08.800656Z","shell.execute_reply.started":"2022-09-23T06:40:51.344026Z","shell.execute_reply":"2022-09-23T06:41:08.799615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=model.predict(test1)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:41:30.333849Z","iopub.execute_input":"2022-09-23T06:41:30.334225Z","iopub.status.idle":"2022-09-23T06:41:31.386589Z","shell.execute_reply.started":"2022-09-23T06:41:30.334193Z","shell.execute_reply":"2022-09-23T06:41:31.3854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.DataFrame(test_df[\"patient_id\"].copy())\nsub[\"CE\"] = pred\nsub[\"CE\"] = sub[\"CE\"].apply(lambda x : 0 if x<0 else x)\nsub[\"CE\"] = sub[\"CE\"].apply(lambda x : 1 if x>1 else x)\nsub[\"LAA\"] = 1- sub[\"CE\"]\n\nsub = sub.groupby(\"patient_id\").mean()\nsub = sub[[\"CE\", \"LAA\"]].round(6).reset_index()\nsub","metadata":{"execution":{"iopub.status.busy":"2022-09-23T06:41:33.323103Z","iopub.execute_input":"2022-09-23T06:41:33.324279Z","iopub.status.idle":"2022-09-23T06:41:33.366592Z","shell.execute_reply.started":"2022-09-23T06:41:33.324233Z","shell.execute_reply":"2022-09-23T06:41:33.365338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-09-20T06:51:11.154264Z","iopub.execute_input":"2022-09-20T06:51:11.154712Z","iopub.status.idle":"2022-09-20T06:51:11.165123Z","shell.execute_reply.started":"2022-09-20T06:51:11.154677Z","shell.execute_reply":"2022-09-20T06:51:11.163919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}