{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\n#for 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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"import the required packages","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from os import listdir\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#plotly\n!pip install chart_studio\nimport plotly.express as px\nimport chart_studio.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot\nimport cufflinks\ncufflinks.go_offline()\ncufflinks.set_config_file(world_readable=True, theme='pearl')\n\nimport seaborn as sns\nsns.set(style=\"whitegrid\")\n\nfrom sklearn.model_selection import train_test_split\n\n#pydicom\nimport pydicom\n\n# Suppress warnings \nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# Settings for pretty nice plots\nplt.style.use('fivethirtyeight')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nfrom kaggle_datasets import KaggleDatasets\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_PATH='/kaggle/input/siim-isic-melanoma-classification/'\nTRAIN_IMG_PATH='/kaggle/input/siim-isic-melanoma-classification/train/'\nTRAIN_IMG_JPG_PATH='/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'\nTEST_IMG_JPG_PATH='/kaggle/input/siim-isic-melanoma-classification/jpeg/test/'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**First lets see a few training images to get a feel of it**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# https://www.kaggle.com/schlerp/getting-to-know-dicom-and-the-data\ndef show_dcm_info(dataset):\n    print(\"Filename.........:\", file_name)\n    print(\"Storage type.....:\", dataset.SOPClassUID)\n    print()\n\n    pat_name = dataset.PatientName\n    display_name = pat_name.family_name + \", \" + pat_name.given_name\n    print(\"Patient's name......:\", display_name)\n    print(\"Patient id..........:\", dataset.PatientID)\n    print(\"Patient's Age.......:\", dataset.PatientAge)\n    print(\"Patient's Sex.......:\", dataset.PatientSex)\n    print(\"Modality............:\", dataset.Modality)\n    print(\"Body Part Examined..:\", dataset.BodyPartExamined)\n   \n    if 'PixelData' in dataset:\n        rows = int(dataset.Rows)\n        cols = int(dataset.Columns)\n        print(\"Image size.......: {rows:d} x {cols:d}, {size:d} bytes\".format(\n            rows=rows, cols=cols, size=len(dataset.PixelData)))\n        if 'PixelSpacing' in dataset:\n            print(\"Pixel spacing....:\", dataset.PixelSpacing)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_pixel_array(dataset, figsize=(5,5)):\n    plt.figure(figsize=figsize)\n    plt.grid(False)\n    plt.imshow(dataset.pixel_array)\n    plt.show()\n    \ni = 1\nnum_to_plot = 5\nfor file_name in os.listdir(TRAIN_IMG_PATH):\n        file_path = TRAIN_IMG_PATH+file_name\n        dcm_data = pydicom.dcmread(file_path)\n        show_dcm_info(dcm_data)\n        plot_pixel_array(dcm_data)\n    \n        if i >= num_to_plot:\n            break\n    \n        i += 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets create train and test dataframe to explore various aspects of the dataset.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/siim-isic-melanoma-classification/train.csv')\ntest_df = pd.read_csv('../input/siim-isic-melanoma-classification/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"lets explore every feature of the training data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print('train data shape: {}'.format(train_df.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# check for NaN values\ntrain_df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets check how the data is distributed among the male/females. ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['sex'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Refer https://medium.com/@ozan/interactive-plots-with-plotly-and-cufflinks-on-pandas-dataframes-af6f86f62d94\n\nLets plot the male/female distribution","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['sex'].value_counts(normalize=True).iplot(kind='bar', yTitle='percentage', bargap=0.8, title=\"Sex distribution in the training data\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There might be multiple images from every patient, which is quite common in medical data sets.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"There are {} unique patients among {} records\".format(len(train_df['patient_id'].unique()), train_df.shape[0]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"That means for many patients multiple images are taken.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['patient_id'].value_counts().hist(bins=7)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"So majority of the patients are having less than 20 images each.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Lets check the age distribution of the patients.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['age_approx'].value_counts(sort=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Plot the Age ditribution in training data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['age_approx'].iplot(kind='hist', yTitle='count', title=\"Age distribution in the training data\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"So the majority of the patinets age is between 30 to 70.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Lets exlore the anatom_site_general_challenge distribtion","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"anatom=train_df['anatom_site_general_challenge'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(10, 5))\nax = fig.add_axes([0,0,1,1])\n\nax.bar(x=anatom.index,height=anatom.values)\n\nplt.title(\"anatom site of the patients\", fontsize=18)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets see how diagnosis data is distributed ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['diagnosis'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(15, 5))\nax = fig.add_axes([0,0,1,1])\n\nax.bar(x=train_df['diagnosis'].value_counts().index,height=train_df['diagnosis'].value_counts().values)\n\nplt.title(\"diagnosis\", fontsize=18)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For diagnosis field lots of values are unknown","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**Benign tumor:**\nA benign tumor put simply is one that will not cause any cancerous growth. It will not damage anythin, it's just a small blot on the landscape of your skin.\n![](https://thegastrosurgeon.com/admin/uploads/pages/2018/11/08/non-cancerous-tumors.jpg)\n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**Malignant tumor:**\nA malignant tumor is the evil twin of the benign tumor: it causes cancerous growth.\n![](https://image.shutterstock.com/image-vector/cancer-cells-growing-malignant-tumor-260nw-224168434.jpg)","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"![](https://gotalktogetherdotcom.files.wordpress.com/2016/05/cancerbenignmalig1.jpg?w=550)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['benign_malignant'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(3, 5))\nax = fig.add_axes([0,0,1,1])\n\nax.bar(x=train_df['benign_malignant'].value_counts().index,height=train_df['benign_malignant'].value_counts().values)\n\nplt.title(\"benign and malignant distribution in training data\", fontsize=10)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['target'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(1, 5))\nax = fig.add_axes([0,0,1,1])\n\nax.bar(x=train_df['target'].value_counts().index,height=train_df['target'].value_counts().values)\n\nplt.title(\"target distribution\", fontsize=10)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"in the target, there is a huge difference in two types. Needs extrapolation.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Lets display some training images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images=train_df['image_name'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot the dcm Images\nfig=plt.figure(figsize=(15, 10))\ncolumns = 3; rows = 4\nplt.title(\"Digital Imaging and Communications in Medicine (DICOM) images\", fontsize=14)\nfor i in range(1, columns*rows +1):\n    ds = pydicom.dcmread(TRAIN_IMG_PATH + train_images[i]+'.dcm')\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(-ds.pixel_array, cmap=plt.cm.bone)\n    fig.add_subplot\nfig.tight_layout()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot the JPEG Images\nfig=plt.figure(figsize=(15, 10))\ncolumns = 3; rows = 4\nplt.title(\"JPEG Images\", fontsize=18)\n\nfor i in range(1, columns*rows +1):\n    img = plt.imread(TRAIN_IMG_JPG_PATH + train_images[i]+'.jpg')\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img)\n    fig.add_subplot\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets plot some benign images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot the JPEG Images\nfig=plt.figure(figsize=(15, 10))\ncolumns = 3; rows = 4\nplt.title(\"Benign images\", fontsize=18)\n\nfor i in range(1, columns*rows +1):\n    if train_df.iloc[i].benign_malignant=='benign':\n        img = plt.imread(TRAIN_IMG_JPG_PATH + train_images[i]+'.jpg')\n        fig.add_subplot(rows, columns, i)\n        plt.imshow(img)\n        fig.add_subplot","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot the JPEG Images\nfig=plt.figure(figsize=(15, 10))\ncolumns = 3; rows = 4\nplt.title(\"Malignant images\", fontsize=18)\nidx=0\ni=1\nwhile idx < train_df.shape[0]:\n    if i < (columns*rows + 1):\n        if train_df.iloc[idx].benign_malignant=='malignant':\n            img = plt.imread(TRAIN_IMG_JPG_PATH + train_images[idx]+'.jpg')\n            fig.add_subplot(rows, columns, i)\n            plt.imshow(img)\n        \n            fig.add_subplot\n            i = i + 1\n    idx=idx+1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets see a few test images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images=test_df['image_name'].values\n\n# plot the JPEG Images\nfig=plt.figure(figsize=(15, 10))\ncolumns = 3; rows = 4\nplt.title(\"Test images\", fontsize=18)\n\nfor i in range(1, columns*rows +1):\n    img = plt.imread(TEST_IMG_JPG_PATH + test_images[i]+'.jpg')\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img)\n    fig.add_subplot","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Custom Data cleaning ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"In many of this images are having hairs, lets try to clean it","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# https://www.kaggle.com/vatsalparsaniya/melanoma-hair-remove\ndef hair_remove(image):\n    # convert image to grayScale\n    grayScale = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    \n    # kernel for morphologyEx\n    #kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(17,17))\n    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(20,20))\n    \n    # apply MORPH_BLACKHAT to grayScale image\n    blackhat = cv2.morphologyEx(grayScale, cv2.MORPH_BLACKHAT, kernel)\n    \n    # apply thresholding to blackhat\n    _,threshold = cv2.threshold(blackhat,10,255,cv2.THRESH_BINARY)\n    \n    # inpaint with original image and threshold image\n    final_image = cv2.inpaint(image,threshold,1,cv2.INPAINT_TELEA)\n    \n    return final_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Cross-shaped Kernel\ncv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ISIC_0078712\nhair_img1 = plt.imread(TRAIN_IMG_JPG_PATH +'ISIC_0078712'+'.jpg')\nplt.imshow(hair_img1)\nplt.title(\"Image with hairs\", fontsize=18)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#%%time\n## image with hairs removed for 1024,1024 image\nimage_resize = cv2.resize(hair_img1,(1024,1024))\nfinal_image = hair_remove(image_resize)\n\nplt.imshow(final_image)\nplt.title(\"Hairs removed\", fontsize=18)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"check the impact of this logic on a image with no hairs","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"normal_img1 = plt.imread(TRAIN_IMG_JPG_PATH +'ISIC_0052212'+'.jpg')\nplt.imshow(normal_img1)\nplt.title(\"No hair image\", fontsize=18)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## image with hairs removed.\n## for 1024,1024 image\nimage_resize = cv2.resize(normal_img1,(1024,1024))\nfinal_image = hair_remove(image_resize)\n\nplt.imshow(final_image)\nplt.title(\"After hair removal process\", fontsize=18)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TBD : image augmentation & creating model.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#!pip install tf-explain\n!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\n#from tf_explain.core.activations import ExtractActivations\n#from tensorflow.keras.applications.xception import decode_predictions\nfrom sklearn.utils import class_weight\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping \nimport efficientnet.tfkeras as efn ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_val = train_test_split(train_df, test_size=0.2, random_state=42)\nx_train['image_name'] = x_train['image_name'].apply(lambda x: x + '.jpg')\nx_val['image_name'] = x_val['image_name'].apply(lambda x: x + '.jpg')\ntest_df['image_name'] = test_df['image_name'].apply(lambda x: x + '.jpg')\nx_train['target'] = x_train['target'].apply(lambda x: str(x))\nx_val['target'] = x_val['target'].apply(lambda x: str(x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# detect TPU\nDEVICE='TPU'\nif DEVICE == \"TPU\":\n    print(\"connecting to TPU...\")\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print(\"Could not connect to TPU\")\n        tpu = None\n\n    if tpu:\n        try:\n            print(\"initializing  TPU ...\")\n            tf.config.experimental_connect_to_cluster(tpu)\n            tf.tpu.experimental.initialize_tpu_system(tpu)\n            strategy = tf.distribute.experimental.TPUStrategy(tpu)\n            print(\"TPU initialized\")\n        except _:\n            print(\"failed to initialize TPU\")\n    else:\n        DEVICE = \"GPU\"\n\nif DEVICE != \"TPU\":\n    print(\"Using default strategy for CPU and single GPU\")\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == \"GPU\":\n    print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nIMG_HEIGHT = 256\nIMG_WIDTH = 256\nN_CHANNELS = 3\nepochs = 16\nBATCH_SIZE = 16 * REPLICAS\nIMAGE_SIZE = [IMG_HEIGHT, IMG_WIDTH]\nIMAGE_RESIZE = [IMG_HEIGHT, IMG_WIDTH]\ninput_shape = (IMG_HEIGHT, IMG_WIDTH, N_CHANNELS)\nBALANCE_DATA = True\naug_data = True\nNETWORK_MODEL = 'EfficientNetB0'\n\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\n#train_df = pd.read_csv(base_dir + 'train.csv')\ny_train = train_df['target']\n\nclass_weights = class_weight.compute_class_weight('balanced',\n                                                 classes=np.unique(y_train),\n                                                 y=y_train)\n\n\n\nclass_weights = {0: class_weights[1],1: class_weights[0]}\nif not BALANCE_DATA:\n    class_weights = {0: 1,1: 1}\nprint(class_weights)\n\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}