{"cells":[{"metadata":{},"cell_type":"markdown","source":"Hello Everyone, \nThis notebook uses the data put together by [Alex Shonenkov](https://www.kaggle.com/shonenkov) and later on converted to **TFRecrods** format by [Chris Deotte](https://www.kaggle.com/cdeotte).  \n\n---\n [Alex Shonenkov](https://www.kaggle.com/shonenkov) merged some of the well known melanoma detection datasets together [here](https://www.kaggle.com/shonenkov/melanoma-merged-external-data-512x512-jpeg). Then  [Chris Deotte](https://www.kaggle.com/cdeotte) converted the whole dataset into **TFRecords** format [here](https://www.kaggle.com/cdeotte/512x512-melanoma-tfrecords-70k-images). Please upvote them for their excellent dedication. \n \n ### The four merged datasets are: \n \n- [Melanoma Detection Dataset](https://www.kaggle.com/wanderdust/skin-lesion-analysis-toward-melanoma-detection)\n- [Skin Lesion Images for Melanoma Classification](https://www.kaggle.com/andrewmvd/isic-2019)\n- [Skin Cancer MNIST: HAM10000](https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000)\n- [SIIM-ISIC Melanoma Classification](https://www.kaggle.com/c/siim-isic-melanoma-classification/data)\n---\n\n# Here, I just used basic EfficentNetB7 model to train and predict without any ensemble. \n\n# I will add several optimizations gradually.\n\n\n# Please upvote, if you like this kernel. ","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"# 1. Loading Libraries","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet\n!pip install -q pyyaml h5py\n\n#basic libraries\nimport os, re, math\nimport numpy as np\nimport pandas as pd\n\n#plot libraries\nimport matplotlib.pyplot as plt\nimport plotly.express as px\n\n#utilities library\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\n#background library for learning \nimport tensorflow as tf\nimport tensorflow.keras.layers as Layers\n\nfrom kaggle_datasets import KaggleDatasets\n\nimport efficientnet.tfkeras as efn\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/train.csv')\ntest_df = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/test.csv')\nsub = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 4. TPU Setup Code","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 5. Setting up Running Configuration ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# For tf.dataset Tensorflow tf. data AUTOTUNE. ... prefetch transformation, \n# which can be used to decouple the time when data is produced from the time when data is consumed. \n# In particular, the transformation uses a background thread and an internal buffer to prefetch \n# elements from the input dataset ahead of the time they are requested.\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Get data access to the dataset for TPUs\nGCS_PATH_ORIGINAL = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nGCS_PATH_MERGED = KaggleDatasets().get_gcs_path('512x512-melanoma-tfrecords-70k-images')\n\n# Running Configuration \nEPOCHS = 20\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512, 512]\n\nTRAINING = True\n\n# Listing the filenames in TFRecords fomat\n# TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH1 + '/tfrecords/train*.tfrec')\n# TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH1 + '/tfrecords/test*.tfrec')\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH_MERGED + '/train*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH_MERGED + '/test*.tfrec')\n\nCLASSES = [0,1]\nprint('Training filenames\\n', list(TRAINING_FILENAMES))\nprint('Test file names\\n', list(TEST_FILENAMES))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 6. Training Validation Split","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# import random \n# random.shuffle(TRAINING_FILENAMES)\nVALIDATION_FILENAMES = TRAINING_FILENAMES[0:5]\nTRAINING_FILENAMES = TRAINING_FILENAMES[5:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"VALIDATION_FILENAMES","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 6. Helper Functions","execution_count":null},{"metadata":{"trusted":true},"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        #\"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\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['class'], tf.int32)\n    label = tf.cast(example['target'], tf.int32)\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\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\n\n\ndef visualize_training(history, lw = 3):\n    plt.figure(figsize=(10,6))\n    plt.plot(history.history['accuracy'], label = 'training', marker = '*', linewidth = lw)\n    plt.plot(history.history['val_accuracy'], label = 'validation', marker = 'o', linewidth = lw)\n    plt.title('Training Accuracy vs Validation Accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend(fontsize = 'x-large')\n    plt.show()\n\n    plt.figure(figsize=(10,6))\n    plt.plot(history.history['loss'], label = 'training', marker = '*', linewidth = lw)\n    plt.plot(history.history['val_loss'], label = 'validation', marker = 'o', linewidth = lw)\n    plt.title('Training Loss vs Validation Loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend(fontsize = 'x-large')\n    plt.show()\n\n    plt.figure(figsize=(10,6))\n    plt.plot(history.history['lr'], label = 'lr', marker = '*',linewidth = lw)\n    plt.title('Learning Rate')\n    plt.xlabel('Epochs')\n    plt.ylabel('Learning Rate')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 7. Data Augmentation ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (above),\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_flip_up_down(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 8. Data Sumamry","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nNUM_VALID_IMAGES = count_data_items(VALIDATION_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nprint('Dataset Details:\\nTraining images: {},  \\nValidation Images: {} \\nTest Images (unlabeled): {}'.format(NUM_TRAINING_IMAGES, NUM_VALID_IMAGES, NUM_TEST_IMAGES))\n\n\ndf = pd.DataFrame({'data':['NUM_TRAINING_IMAGES', 'NUM_TEST_IMAGES'],\n                   'No of Samples':[NUM_TRAINING_IMAGES, NUM_TEST_IMAGES]})\nplt.figure()\nx = df.plot.bar(x='data', y='No of Samples', rot=0)\nplt.ylabel('No of Samples')\nplt.title('No of Training and Test Images')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 9. Learning Rate Scheduler","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.000075, \n               lr_min=0.000001, lr_rampup_epochs=8, \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\n\nlrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stopper = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', \n                                                 patience=4,  \n                                                 mode='max',\n                                                 baseline=None, \n                                                 restore_best_weights=True)\n\nmodel_checkpoint_callback_efnB7 = tf.keras.callbacks.ModelCheckpoint(\n    filepath='model_efnB7_all_four_data_best_val_acc.hdf5',\n    save_weights_only=True,\n    monitor='val_accuracy',\n    mode='max',\n    save_best_only=True)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Getting Ready with the Test Dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\nprint('Generating test file list')\ntest_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 10. Training Models","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model_efn_b7 = tf.keras.Sequential([\n        efn.EfficientNetB7(\n            input_shape=(*IMAGE_SIZE, 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        Layers.GlobalAveragePooling2D(),\n        Layers.Dense(1, activation='sigmoid')\n    ])\n    model_efn_b7.compile(\n        optimizer='adam',\n        loss = 'binary_crossentropy',\n        metrics=['accuracy']\n    )\n    model_efn_b7.summary()\n\n    \nif TRAINING:\n    history_efn_b7 = model_efn_b7.fit(\n        get_training_dataset(), \n        epochs=EPOCHS, \n        callbacks=[lr_schedule, model_checkpoint_callback_efnB7, early_stopper],\n        steps_per_epoch=NUM_TRAINING_IMAGES // BATCH_SIZE,\n        validation_data=get_validation_dataset()\n    )\n    \nif TRAINING:\n    pd.DataFrame.from_dict(history_efn_b7.history).to_csv('history_efn_b7.csv' , index=False)\n    visualize_training(history_efn_b7)\nelse:\n    model_efn_b7.load_weights('/kaggle/input/efficent-net-pretrained-24-epoch/model_efnB7_all_four_data_best_val_acc.hdf5')\n        \nprobabilities_efn_b7 = model_efn_b7.predict(test_images_ds)\n# tf.tpu.experimental.initialize_tpu_system(tpu)\n# visualize_training(history_efn_b7)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 11. Prediction and Submission Generation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') \n# all in one batch ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_efn_b7 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities_efn_b7)})\npred_efn_b7.to_csv('submission_efn_b7_all_four_datasets.csv', index = False)\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# pred_efn_b0 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities_efn_b0)}) pred_efn_b7 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities_efn_b7)}) pred_dnet201 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities_dnet201)})\n\n# mean_output = pred_efn_b0.copy() mean_output.target = pred_efn_b0.target *0.2 + pred_efn_b7.target * 0.7 + pred_dnet201.target * 0.1 mean_output.to_csv('mean_submission.csv', index = False)\n\n\n# sub_pred_efn_b0 = sub.copy()\n# sub_pred_efn_b7 = sub.copy()\n# sub_pred_dnet201 = sub.copy()\n\n\n\n# del sub_pred_efn_b0['target']\n# sub_pred_efn_b0 = sub_pred_efn_b0.merge(pred_efn_b0, on='image_name')\n\n\n# del sub_pred_efn_b7['target']\n# sub_pred_efn_b7 = sub_pred_efn_b7.merge(pred_efn_b7, on='image_name')\n\n\n# del sub_pred_dnet201['target']\n# sub_pred_dnet201 = sub_pred_dnet201.merge(pred_dnet201, on='image_name')\n\n# sub_pred_efn_b0.to_csv('submission_efn_b0.csv', index = False)\n# sub_pred_efn_b7.to_csv('submission_efn_b7.csv', index = False)\n# sub_pred_dnet201.to_csv('submission_dnet201.csv', index = False)\n# sub_pred_efn_b0.target =(sub_pred_efn_b0.target + sub_pred_efn_b7.target +  sub_pred_dnet201.target)/3.0\n# sub_pred_efn_b0.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# References: \n* https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/155251\n* https://www.kaggle.com/redwankarimsony/power-of-metadata-xgboost-cnn-ensemble/\n* https://www.kaggle.com/cdeotte/512x512-melanoma-tfrecords-70k-images\n* https://www.kaggle.com/shonenkov/melanoma-merged-external-data-512x512-jpeg\n\n\n","execution_count":null}],"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}