{"cells":[{"metadata":{},"cell_type":"markdown","source":"# EfficientNet B7 with TPU","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"credits - [Chris Deotte](https://www.kaggle.com/cdeotte) for different tfrecords sizes\n\n**work still in progress","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Accuracy of EfficientNets vs other types of nets.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"![](https://pythonawesome.com/content/images/2019/06/params.png)","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"DEVICE = \"TPU\"\nBASEPATH = \"../input/siim-isic-melanoma-classification\"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Install EfficientNet","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Import necessary files","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport random, re, math, time\nrandom.seed(a=42)\n\nfrom os.path import join \n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n#import tensorflow_addons as tfa\nimport efficientnet.tfkeras as efn\n\nfrom tqdm.keras import TqdmCallback\n\nfrom PIL import Image\nimport PIL\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import KFold\n\nfrom sklearn.utils.class_weight import compute_class_weight\n\nimport plotly\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\n\nfrom pandas_summary import DataFrameSummary\n\nfrom kaggle_datasets import KaggleDatasets\n\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configs","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"if DEVICE == \"TPU\":\n    print(\"connecting to TPU...\")\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\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    \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Configuration\nEPOCHS = 8\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\n\nIMAGE_SIZE1 = [256, 256]\nIMAGE_SIZE2 = [384, 384]\nIMAGE_SIZE3 = [512, 512]\nIMAGE_SIZE4 = [768, 768]\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load the files","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv'))\ndf_test = pd.read_csv(os.path.join(BASEPATH, 'test.csv'))\nsub = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv'))\n\nCLASSES = [0,1]   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_PATH1 = KaggleDatasets().get_gcs_path('melanoma-256x256')\nTRAINING_FILENAMES1 = np.array(tf.io.gfile.glob(GCS_PATH1 + '/train*.tfrec'))\nTEST_FILENAMES1 = np.array(tf.io.gfile.glob(GCS_PATH1 + '/test*.tfrec'))\n\nGCS_PATH2 = KaggleDatasets().get_gcs_path('melanoma-384x384')\nTRAINING_FILENAMES2 = np.array(tf.io.gfile.glob(GCS_PATH2 + '/train*.tfrec'))\nTEST_FILENAMES2 = np.array(tf.io.gfile.glob(GCS_PATH2 + '/test*.tfrec'))\n\nGCS_PATH3 = KaggleDatasets().get_gcs_path('melanoma-512x512')\nTRAINING_FILENAMES3 = np.array(tf.io.gfile.glob(GCS_PATH3 + '/train*.tfrec'))\nTEST_FILENAMES3 = np.array(tf.io.gfile.glob(GCS_PATH3 + '/test*.tfrec'))\n\nGCS_PATH4 = KaggleDatasets().get_gcs_path('melanoma-768x768')\nTRAINING_FILENAMES4 = np.array(tf.io.gfile.glob(GCS_PATH4 + '/train*.tfrec'))\nTEST_FILENAMES4 = np.array(tf.io.gfile.glob(GCS_PATH4 + '/test*.tfrec'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image loading from TFrecords","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"1","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image1(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_SIZE1, 3])\n    return image\n\ndef read_labeled_tfrecord1(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_image1(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_tfrecord1(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_image1(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset1(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_tfrecord1 if labeled else read_unlabeled_tfrecord1, 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 get_training_dataset1():\n    dataset = load_dataset1(TRAINING_FILENAMES1, 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_test_dataset1(ordered=False):\n    dataset = load_dataset1(TEST_FILENAMES1, 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"2","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image2(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_SIZE2, 3])\n    return image\n\ndef read_labeled_tfrecord2(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_image2(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_tfrecord2(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_image2(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset2(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_tfrecord2 if labeled else read_unlabeled_tfrecord2, 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 get_training_dataset2():\n    dataset = load_dataset2(TRAINING_FILENAMES2, 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_test_dataset2(ordered=False):\n    dataset = load_dataset2(TEST_FILENAMES2, 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"3","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image3(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_SIZE3, 3])\n    return image\n\ndef read_labeled_tfrecord3(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_image3(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_tfrecord3(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_image3(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset3(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_tfrecord3 if labeled else read_unlabeled_tfrecord3, 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 get_training_dataset3():\n    dataset = load_dataset3(TRAINING_FILENAMES3, 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_test_dataset3(ordered=False):\n    dataset = load_dataset3(TEST_FILENAMES3, 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"4","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image4(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_SIZE4, 3])\n    return image\n\ndef read_labeled_tfrecord4(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_image4(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_tfrecord4(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_image4(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset4(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_tfrecord4 if labeled else read_unlabeled_tfrecord4, 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_flip_up_down(image)\n    image = tf.image.random_hue(image, 0.01)\n    image = tf.image.random_saturation(image, 0.7, 1.3)\n    image = tf.image.random_contrast(image, 0.8, 1.2)\n    image = tf.image.random_brightness(image, 0.1)\n    return image, label   \n\ndef get_training_dataset4():\n    dataset = load_dataset4(TRAINING_FILENAMES4, 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_dataset4(ordered=False):\n    dataset = load_dataset4(TEST_FILENAMES4, 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_FILENAMES1)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES1)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"training_set1 = get_training_dataset1()\ntraining_set2 = get_training_dataset2()\ntraining_set3 = get_training_dataset3()\ntraining_set4 = get_training_dataset4()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Let's create an EfficientNet B7 model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def lrfn(epoch):\n    LR_START          = 0.000005\n    LR_MAX            = 0.000020 * strategy.num_replicas_in_sync\n    LR_MIN            = 0.000001\n    LR_RAMPUP_EPOCHS = 5\n    LR_SUSTAIN_EPOCHS = 0\n    LR_EXP_DECAY = .8\n    \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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, BatchNormalization, Activation, Dropout\nfrom tensorflow.keras.regularizers import l2\nreg_l2 = 0.001","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#L2 tried = 0.0001/0.001/0.01\n#LR = 0.0003\n#opt = tf.keras.optimizers.Adam(learning_rate = LR)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"\"\"\"def get_model(base_model):\n        model = tf.keras.Sequential([\n            base_model,\n            GlobalAveragePooling2D(),\n            Dense(512, activation='relu', kernel_regularizer=l2(reg_l2),\n            bias_regularizer=l2(reg_l2)),\n            BatchNormalization(),\n            Dropout(0.2),\n            Dense(182, activation='relu', kernel_regularizer=l2(reg_l2),\n            bias_regularizer=l2(reg_l2)),\n            BatchNormalization(),\n            Dropout(0.2),\n            Dense(1, activation='sigmoid')\n        ])\n        return model\n\ndef compile_model(base_model):\n        with strategy.scope():\n            model = get_model(base_model)\n            \n            model.compile(optimizer='adam',loss = 'binary_crossentropy',metrics=['accuracy'])\n        return model\n    \nmodel1 = compile_model(base_model1)\nmodel2 = compile_model(base_model2)\nmodel3 = compile_model(base_model3)\nmodel4 = compile_model(base_model4)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model1 = tf.keras.Sequential([\n        efn.EfficientNetB3(\n            input_shape=(*IMAGE_SIZE1, 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        GlobalAveragePooling2D(),\n        Dense(512, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(182, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(1, activation='sigmoid')\n    ])\n    \nmodel1.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['accuracy']\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model2 = tf.keras.Sequential([\n        efn.EfficientNetB3(\n            input_shape=(*IMAGE_SIZE2, 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        GlobalAveragePooling2D(),\n        Dense(512, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(182, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(1, activation='sigmoid')\n    ])\n    \nmodel2.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model3 = tf.keras.Sequential([\n        efn.EfficientNetB3(\n            input_shape=(*IMAGE_SIZE3, 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        GlobalAveragePooling2D(),\n        Dense(512, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(182, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(1, activation='sigmoid')\n    ])\n    \nmodel3.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model4 = tf.keras.Sequential([\n        efn.EfficientNetB3(\n            input_shape=(*IMAGE_SIZE4, 3),\n            weights='imagenet',\n            include_top=False\n        ),\n        GlobalAveragePooling2D(),\n        Dense(512, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(182, activation='relu', kernel_regularizer=l2(reg_l2),\n    bias_regularizer=l2(reg_l2)),\n        BatchNormalization(),\n        Dropout(0.2),\n        Dense(1, activation='sigmoid')\n    ])\n    \nmodel4.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_schedule1 = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nlr_schedule2 = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nlr_schedule3 = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nlr_schedule4 = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\n\nhistory1 = model1.fit(training_set1, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule1])\nhistory2 = model2.fit(training_set2, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule2])\nhistory3 = model3.fit(training_set3, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule3])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history4 = model4.fit(training_set4, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule4])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds1 = get_test_dataset1(ordered=True)\ntest_ds2 = get_test_dataset2(ordered=True)\ntest_ds3 = get_test_dataset3(ordered=True)\ntest_ds4 = get_test_dataset4(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds1 = test_ds1.map(lambda image, idnum: image)\ntest_images_ds2 = test_ds2.map(lambda image, idnum: image)\ntest_images_ds3 = test_ds3.map(lambda image, idnum: image)\ntest_images_ds4 = test_ds4.map(lambda image, idnum: image)\n\nprobabilities1 = model1.predict(test_images_ds1)\nprobabilities2 = model2.predict(test_images_ds2)\nprobabilities3 = model3.predict(test_images_ds3)\nprobabilities4 = model4.predict(test_images_ds4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Generating submission.csv files...')\ntest_ids_ds1 = test_ds1.map(lambda image, idnum: idnum).unbatch()\ntest_ids_ds2 = test_ds2.map(lambda image, idnum: idnum).unbatch()\ntest_ids_ds3 = test_ds3.map(lambda image, idnum: idnum).unbatch()\ntest_ids_ds4 = test_ds4.map(lambda image, idnum: idnum).unbatch()\n\ntest_ids1 = next(iter(test_ids_ds1.batch(NUM_TEST_IMAGES))).numpy().astype('U')\ntest_ids2 = next(iter(test_ids_ds2.batch(NUM_TEST_IMAGES))).numpy().astype('U')\ntest_ids3 = next(iter(test_ids_ds3.batch(NUM_TEST_IMAGES))).numpy().astype('U')\ntest_ids4 = next(iter(test_ids_ds4.batch(NUM_TEST_IMAGES))).numpy().astype('U')# all in one batch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df1 = pd.DataFrame({'image_name': test_ids1, 'target': np.concatenate(probabilities1)})\npred_df2 = pd.DataFrame({'image_name': test_ids2, 'target': np.concatenate(probabilities2)})\npred_df3 = pd.DataFrame({'image_name': test_ids3, 'target': np.concatenate(probabilities3)})\npred_df4 = pd.DataFrame({'image_name': test_ids4, 'target': np.concatenate(probabilities4)})\n\npred_df4.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub1 = sub.copy()\nsub2 = sub.copy()\nsub3 = sub.copy()\nsub4 = sub.copy()\n\nsub4.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del sub1['target']\nsub1 = sub1.merge(pred_df1, on='image_name')\nsub1.to_csv('submission1.csv', index=False)\n\ndel sub2['target']\nsub2 = sub2.merge(pred_df2, on='image_name')\nsub2.to_csv('submission2.csv', index=False)\n\ndel sub3['target']\nsub3 = sub3.merge(pred_df3, on='image_name')\nsub3.to_csv('submission3.csv', index=False)\n\ndel sub4['target']\nsub4 = sub4.merge(pred_df4, on='image_name')\nsub4.to_csv('submission4.csv', index=False)\nsub4.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#average\n\nensemble1 = (sub1['target'] + sub2['target'] + sub3['target'] + sub4['target'])/4\nensemble_img1 = sub1['image_name']\nensemble_sub1 = pd.concat([ensemble_img1, ensemble1], axis = 1)\nensemble_sub1.to_csv('submission5.csv', index=False)\nensemble_sub1.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# weighted average??\n\nensemble2 = 0.15 * sub1['target'] + 0.2 * sub2['target']  + 0.3 * sub3['target'] + 0.35 * sub4['target']\nensemble_img2 = sub1['image_name']\nensemble_sub2 = pd.concat([ensemble_img2, ensemble2], axis = 1)\nensemble_sub2.to_csv('submission6.csv', index=False)\nensemble_sub2.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#random mixup??\n\nfrac1 = sub1.sample(frac = 0.25)\nfrac2 = sub2.sample(frac = 0.25)\nfrac3 = sub3.sample(frac = 0.25)\nfrac4 = sub4.sample(frac = 0.25)\n\nensemble3 = pd.concat([frac1,frac2,frac3,frac4], axis = 0)\nensemble3_sub = sub.copy()\n\nensemble3_sub = ensemble3_sub.merge(ensemble3, on='image_name')\n\nensemble3_sub['target'] = ensemble3_sub['target_y']\nensemble3_sub = ensemble3_sub.drop(['target_x'], axis = 1)\nensemble3_sub = ensemble3_sub.drop(['target_y'], axis = 1)\n\nensemble3_sub.to_csv('submission7.csv', index=False)\nensemble3_sub.head()\n","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}