{"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","collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **EffientNet**","metadata":{}},{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **Library import**","metadata":{}},{"cell_type":"code","source":"# Importing Necessary Libraries\n%matplotlib inline\nimport tensorflow as tf\nimport plotly.express as px\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm.notebook import tqdm\nfrom kaggle_datasets import KaggleDatasets\nfrom collections import Counter\nimport efficientnet.tfkeras as efn\nimport re\nfrom tensorflow.keras import layers as L\nimport sklearn\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nsns.set_style(\"dark\")\nsns.set(rc={'figure.figsize':(12,8)})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **TPU detection**","metadata":{}},{"cell_type":"code","source":"try:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **Reading Dataset**","metadata":{}},{"cell_type":"code","source":"import pandas as pd\ndataset = pd.read_csv(\"../input/siim-isic-melanoma-classification/train.csv\")\ndataset","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **SIIM-ISIC Melanoma Classification**","metadata":{}},{"cell_type":"markdown","source":"# **Data Exploration**","metadata":{}},{"cell_type":"code","source":"dataset.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.isnull().sum()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.describe()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.info()","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.nunique()","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Data Visualisations**","metadata":{}},{"cell_type":"code","source":"f, axes = plt.subplots(2, 2, figsize=(12,12))\nf.tight_layout() \nplt.subplots_adjust(left=0.01, wspace=0.6, hspace=0.4)\nsns.countplot(y=\"anatom_site_general_challenge\", data=dataset,  ax=axes[0][1])\nsns.countplot(y=\"diagnosis\", data=dataset,  ax=axes[0][0])\nsns.countplot(x='sex', data=dataset, ax=axes[1][0])\nsns.countplot(\"benign_malignant\", data=dataset,  ax=axes[1][1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.distplot(dataset['age_approx'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.countplot(\"target\", data=dataset)","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset['target'].value_counts(normalize=True) * 10","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Images Visualisations**","metadata":{}},{"cell_type":"markdown","source":"> **Sample image**","metadata":{}},{"cell_type":"code","source":"# Showing a sample image\nimage = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/ISIC_5766923.jpg')\nplt.imshow(image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **Sample benign**","metadata":{}},{"cell_type":"code","source":"w = 10\nh = 10\nfig = plt.figure(figsize=(15, 15))\ncolumns = 4\nrows = 4\n\n# ax enables access to manipulate each of subplots\nax = []\n\nfor i in range(columns*rows):\n    img = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'+dataset.loc[dataset['target'] == 0]['image_name'].values[i]+'.jpg')\n    # create subplot and append to ax\n    ax.append( fig.add_subplot(rows, columns, i+1) )\n    # Hide grid lines\n    ax[-1].grid(False)\n\n    # Hide axes ticks\n    ax[-1].set_xticks([])\n    ax[-1].set_yticks([])\n    ax[-1].set_title(dataset.loc[dataset['target'] == 0]['benign_malignant'].values[i])   # set title\n    plt.imshow(img)\n\n\n\nplt.show()  # finally, render the plot","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **Sample malignant**","metadata":{}},{"cell_type":"code","source":"w = 10\nh = 10\nfig = plt.figure(figsize=(15, 15))\ncolumns = 4\nrows = 4\n\n# ax enables access to manipulate each of subplots\nax = []\n\nfor i in range(columns*rows):\n    img = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'+dataset.loc[dataset['target'] == 1]['image_name'].values[i]+'.jpg')\n    # create subplot and append to ax\n    ax.append( fig.add_subplot(rows, columns, i+1) )\n    # Hide grid lines\n    ax[-1].grid(False)\n\n    # Hide axes ticks\n    ax[-1].set_xticks([])\n    ax[-1].set_yticks([])\n    ax[-1].set_title(dataset.loc[dataset['target'] == 1]['benign_malignant'].values[i])  # set title\n    plt.imshow(img)\n\n\n\nplt.show()  # finally, render the plot","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Cleaning Dataset**","metadata":{}},{"cell_type":"markdown","source":">**Removing Null value**","metadata":{}},{"cell_type":"code","source":"dataset.isnull().sum()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.loc[dataset.isnull().any(axis=1)]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = dataset.dropna(axis=0)\ndataset.isnull().sum()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset['target'].value_counts(normalize=True) * 10","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.nunique()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Changing all column into categorical**","metadata":{}},{"cell_type":"code","source":"cleaned_dataset = dataset.copy()\ncleaned_dataset","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cleaned_dataset.sex = cleaned_dataset.sex.replace({'male':0, 'female':1})\ncleaned_dataset = cleaned_dataset.join(pd.get_dummies(cleaned_dataset.anatom_site_general_challenge))\ncleaned_dataset = cleaned_dataset.join(pd.get_dummies(cleaned_dataset.diagnosis))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.options.display.max_rows = 999\ncleaned_dataset = cleaned_dataset.reset_index()\ncleaned_dataset.head(35)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Creating the Training & Testing Dataset**","metadata":{}},{"cell_type":"code","source":"#For tf.dataset\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords/train*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords/test*.tfrec')\n\nCLASSES = [0,1]   \nIMAGE_SIZE = [1024, 1024]\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n       \n        \"target\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['target'], tf.int32)\n    \n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_brightness(image, 0.1)\n    image = tf.image.random_flip_up_down(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images and {} unlabeled test images'.format(NUM_TRAINING_IMAGES,NUM_TEST_IMAGES))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nEPOCHS = 10","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.0001, \n               lr_min=0.000001, lr_rampup_epochs=20, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + lr_start\n        elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_exp_decay**(epoch - lr_rampup_epochs - lr_sustain_epochs) + lr_min\n        return lr\n    \n    return lrfn","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    efficientnetb5_model = tf.keras.Sequential([\n        efn.EfficientNetB5(\n            input_shape=(*IMAGE_SIZE, 3),\n            #weights='imagenet',\n            weights='imagenet',\n            include_top=False\n        ),\n        L.GlobalAveragePooling2D(),\n        L.Dense(1024, activation = 'relu'), \n        L.Dropout(0.3), \n        L.Dense(512, activation= 'relu'), \n        L.Dropout(0.2), \n        L.Dense(256, activation='relu'), \n        L.Dropout(0.2), \n        L.Dense(128, activation='relu'), \n        L.Dropout(0.1), \n        L.Dense(1, activation='sigmoid')\n    ])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\n# Compatible with tensorflow backend\n\ndef focal_loss(gamma=2., alpha=.25):\n\tdef focal_loss_fixed(y_true, y_pred):\n\t\tpt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n\t\tpt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n\t\treturn -K.mean(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) - K.mean((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\treturn focal_loss_fixed","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"efficientnetb5_model.compile(\n    optimizer='adam',\n    loss = focal_loss(gamma=2., alpha=.25),\n    #loss = tf.keras.losses.BinaryCrossentropy(label_smoothing = 0.1),\n    metrics=['binary_crossentropy', 'accuracy']\n)\nefficientnetb5_model.summary()","metadata":{"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = efficientnetb5_model.fit(\n    get_training_dataset(), \n    epochs=EPOCHS, \n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_schedule],\n    class_weight = {0:0.50899675,1: 28.28782609}\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# summarize history for accuracy\nplt.plot(history.history['loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# summarize history for loss\nplt.plot(history.history['binary_crossentropy'])\nplt.title('model crossentropy')\nplt.ylabel('crossentropy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","metadata":{"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"efficientnetb5_model.save('complete_data_efficient_modelte10.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"efficientnetb5_model.save_weights('complete_data_efficient_weightste10.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}